pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
39,520,562
0
<p>You can reference Microsoft.SqlServer.Types and set "Copy Local" in its Properties. Should help.</p>
33,516,227
0
Eclipse: Error importing android-support-v7-appcompat to workspace <p>I'm new. I use Eclipse.</p> <p>As it is shown in several video tutorials.</p> <p>File> Import -> Existing Android Project -> (Route sdk / extas / android / support / v7 / appcompat).</p> <p>Imports almost all very well, however these errors appear within me res / values-v21</p> <p>[2015-11-04 02:35:50 - android-support-v7-appcompat] D:\workspace\android-support-v7-appcompat\res\values-v21\themes_base.xml:131: error: Error: No resource found that matches the given name: attr 'android:colorPrimaryDark'.</p> <p>[2015-11-04 02:35:50 - android-support-v7-appcompat] [2015-11-04 02:35:50 - android-support-v7-appcompat] D:\workspace\android-support-v7-appcompat\res\values-v21\themes_base.xml:140: error: Error: No resource found that matches the given name: attr 'android:windowElevation'.</p> <p>[2015-11-04 02:35:50 - android-support-v7-appcompat] [2015-11-04 02:35:50 - android-support-v7-appcompat] D:\workspace\android-support-v7-appcompat\res\values-v21\themes_base.xml:144: error: Error: No resource found that matches the given name: attr 'android:windowElevation'.</p> <p>[2015-11-04 02:35:50 - android-support-v7-appcompat] </p> <p>PS: I have updated all my extras. SDK Tools, Android and Android Support Support Repository Library.</p>
9,816,909
0
<p>Use the following code:</p> <pre><code>protected void CashPayButton_Click(object sender, EventArgs e) { foreach(Gridviewrow gvr in Cash_GridView.Rows) { if(((CheckBox)gvr.findcontrol("MemberCheck")).Checked == true) { int uPrimaryid= gvr.cells["uPrimaryID"]; } } } </code></pre>
24,606,235
0
Issue inputing sas date as datalines <p>I've the following code. Though I've entered 30jun1983 it gets saved as 30/jun/2020. And it is reading only when there's two spaces between the date values in the cards and if there's only one space it reads the second value as missing.</p> <pre><code>DATA DIFFERENCE; infile cards dlm=',' dsd; INPUT DATE1 DATE9. Dt2 DATE9.; FORMAT DATE1 DDMMYY10. Dt2 DDMMYY10.; DIFFERENCE=YRDIF(DATE1,Dt2,'ACT/ACT'); DIFFERENCE=ROUND(DIFFERENCE); CARDS; 11MAY2009 30jun1983 ; RUN; </code></pre>
22,487,714
0
<p>Use <code>SqlFunctions.DatePart</code> static method. It will be transformed into <code>DATEPART</code> SQL function call in generated SQL query:</p> <blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/dd487171%28v=vs.110%29.aspx" rel="nofollow"><strong><code>SqlFunctions.DatePart</code> Method</strong></a></p> <p>Returns an integer that represents the specified datepart of the specified date.</p> <p>This function is translated to a corresponding function in the database. For information about the corresponding SQL Server function, see DATEPART (Transact-SQL).</p> </blockquote> <p>To get week number, use <code>"week"</code> as parameter.</p>
17,582,171
0
ServiceStack NUnit Test Debugging Connection Refused Issue <p>In this question: <a href="http://stackoverflow.com/q/16819463/149060">ServiceStack JsonServiceClient based test fails, but service works in browser</a> I'm looking for some clue as to why the test generates an exception, when an interactive browser test succeeds. Originally I could run tests and interact via the browser.</p> <p>Now I'm asking for some direction on how to debug this. Basically, if I step through my test case, I reach a line like this: <code>Tranactions response = client.Get(request);</code> and then it raises an exception. I'm thinking I should download the servicestack source and add the project to my solution, in order to step through that code and get further insight into what's going on. Any advice?</p>
11,129,015
0
Why KeyPoint "detector" and "extractor" are different operation? <p>Bascially you have first to do a:</p> <pre><code>SurfFeatureDetector surf(400); surf.detect(image1, keypoints1); </code></pre> <p>And then a:</p> <pre><code>surfDesc.compute(image1, keypoints1, descriptors1); </code></pre> <p>Why detect and comput are 2 different operation?<br> Doing the computing after the detect doesn't make redundance loops?</p> <p>I found myself that <code>.compute</code> is the most expensive in my application. </p> <pre><code>.detect </code></pre> <p>is done in <strong>0.2secs</strong></p> <pre><code>.compute </code></pre> <p>Takes <strong>~1sec</strong>. Is there any way to speed up <code>.compute</code> ?</p>
20,287,627
0
<p>Without seeing the import statement that you tried, I am not 100% sure about why is that happening... But perhaps the reason is that you are using the default delimiter for fields, which is precisely a comma, so if you want to keep it, you should use a different delimiter, like for example:</p> <pre><code>--fields-terminated-by \t </code></pre> <p>Another option would be to use <code>--enclosed-by '\"'</code>, and it would look like "sami, ramesh".</p> <p>Hope that helps! If it doesn't, please post your import statement to see where the problem is.</p>
37,484,666
0
Java JAXB binding issues : 1 counts of IllegalAnnotationExceptions <p>I m facing some problems with JAXB , I want to deserilize a <strong>config.xml</strong> file : </p> <pre><code>&lt;configuration&gt; &lt;connectors&gt; &lt;connector name = "cust1"&gt; &lt;entity&gt; &lt;prefix&gt;C_JDD&lt;/prefix&gt; &lt;filename&gt;jdd&lt;/filename&gt; &lt;/entity&gt; &lt;/connector&gt; &lt;connector name = "c2"&gt; &lt;entity&gt; &lt;prefix&gt;pref1&lt;/prefix&gt; &lt;filename&gt;cnt&lt;/filename&gt; &lt;/entity&gt; &lt;entity&gt; &lt;prefix&gt;DD&lt;/prefix&gt; &lt;filename&gt;vhl&lt;/filename&gt; &lt;/entity&gt; &lt;/connector&gt; &lt;/connectors&gt; &lt;/configuration&gt; </code></pre> <p>And here is my class ConnectorsXML (which contains list of connectors) : </p> <pre><code>@XmlAccessorType(XmlAccessType.FIELD) public class ConnectorsXML { @XmlElement(name = "connector") private List&lt;ConnectorXML&gt; connectorsXML = new ArrayList&lt;ConnectorXML&gt;(); } </code></pre> <p>the code of ConnectorXML (abstraction of one connector in the xml) : </p> <pre><code>@XmlAccessorType(XmlAccessType.FIELD) public class ConnectorXML { @XmlAttribute private String name; @XmlElement(name = "entity") private List&lt;EntityXML&gt; entities = new ArrayList&lt;EntityXML&gt;(); } </code></pre> <p>And finally , the class EntityXML , a connector may have a list of entities : </p> <pre><code>@XmlAccessorType(XmlAccessType.FIELD) public class EntityXML { private String prefix ; private String filename; } </code></pre> <p>PS : i ve already generated all getters and setters and also constructors , ( i didnt copy theme here ) .</p> <p>I can't understand why my code throw the exception : 1 counts of IllegalAnnotationExceptions</p>
21,302,600
0
<p><strong>Neither are safe</strong>. Please avoid flashy <code>max</code> macro implementations that rely on non-standard C extensions like <em>expression statements</em> which will give you all sort of headaches if you ever have to port your code to a different platform. Doing my best to present this answer from becoming a rant, the <code>max</code> macro is, in my opinion, one of the worst things in C standard libraries due to its potential side-effects. In times past, I've #<code>undef</code>ed <code>max</code> just to be on the safe side.</p> <p>Your're better off coding the second macro <code>maxint</code> as a function as it has all the drawbacks of macros (e.g. can't debug easily, instantiated variables clashing with locals) but none of the benefits (e.g. genericisation).</p> <p><strong>Alternatives</strong>:</p> <p>My favourite: use the ternary inline: <code>a &gt; b ? a : b</code> where you can drop the parentheses to taste since you know exactly what is going on. It will also be faster than macros that try to be safe by taking value copies.</p> <p>Build your own functions. Consider defining <code>max</code> for integral types and <code>fmax</code> for floating point. There is already a precedent here with <code>abs</code> and <code>fabs</code>.</p>
34,463,290
0
Get unseen messages via IMAP <p>I need to extract some data from new (unseen) messages; I'm trying to make range of that data:</p> <pre><code>c, _ = imap.Dial("someserverr") defer c.Logout(30 * time.Second) fmt.Println("Server says hello:", c.Data[0].Info) c.Data = nil if c.State() == imap.Login { c.Login("somedata", "somedata") } c.Select("INBOX", false) set, _ := imap.NewSeqSet("") fmt.Println("unseen", c.Mailbox.Unseen) fmt.Println(c.Mailbox) if c.Mailbox.Unseen &gt;= 1 { set.AddRange(1, c.Mailbox.Unseen) } else { set.Add("0:0") } </code></pre> <p>The main problem here is command <code>c.Mailbox</code> showing wrong number of unseen messages.</p> <p>For example, if I have 5 unread messages in INBOX it shows 1. If I mark that one as read, it will show 4, and so on.</p>
26,668,770
0
<p>Try this:</p> <pre><code> String filename = "example_filename"; Multipart _multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); _multipart.addBodyPart(messageBodyPart); message.setContent(_multipart); </code></pre> <p><strong>EDIT:</strong></p> <p>When you include <code>aFileChooser</code> library, you should create two buttons in your layout of the activity ("Send an email" and "Choose a file"), then in your activity:</p> <pre><code>private Button sendEmail; private Button chooseFileButton; private String filename; private static final int REQUEST_CHOOSER = 1234; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sendEmail = (Button) findViewById(R.id.send_email_button_id); sendEmail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { try { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication( username, password); } }); // TODO Auto-generated method stub Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]")); message.setSubject("email"); message.setText("HI," + "\n\n great"); if (!"".equals(filename)) { Multipart _multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); _multipart.addBodyPart(messageBodyPart); message.setContent(_multipart); } Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }).start(); } }); chooseFileButton = (Button) findViewById(R.id.choose_file_button_id); chooseFileButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Create the ACTION_GET_CONTENT Intent Intent getContentIntent = FileUtils.createGetContentIntent(); Intent intent = Intent.createChooser(getContentIntent, "Select a file"); startActivityForResult(intent, REQUEST_CHOOSER); } }); } </code></pre> <p>After that add <code>onActivityResult</code> method, where you can get selected filename:</p> <pre><code>@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_CHOOSER: if (resultCode == RESULT_OK) { final Uri uri = data.getData(); // Get the File path from the Uri filename = FileUtils.getPath(this, uri); } break; } } </code></pre> <p>Don't forget to add FileChooserActivity to your <code>AndroidManifest.xml</code>:</p> <pre><code>&lt;activity android:name="com.ipaulpro.afilechooser.FileChooserActivity" android:icon="@drawable/ic_launcher" android:enabled="true" android:exported="true" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.GET_CONTENT" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;category android:name="android.intent.category.OPENABLE" /&gt; &lt;data android:mimeType="*/*" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; </code></pre> <p>After that you can send an email, by click on the "Send" button;</p>
19,014,834
0
Is it possible to associate an instance of an object with one file while it's being mapped by a map-only mapred Job? <p>I want to use a HashSet that exists/works against one file while it's being mapped, and then is reset/recreated when the next file is being mapped. I have modified TextInputFormat to override isSplitable to return false, so that the file is not split up and is processed as a whole by Mappers. Is it possible to do something like this? Or is there another way to do fewer writes to the Accumulo table?</p> <p>Let me start out with I do not believe I want a global variable. I just want to ensure uniqueness and thus write fewer mutations to my Accumulo table.</p> <p>My project is to convert the functionality of the Index.java file from the shard example from a linear accumulo client program to one that uses mapreduce functionality, while still creating the same table in Accumulo. It needs to be mapreduce because that's the buzzword, and in essence it would run faster than a linear program against terabytes of data.</p> <p>Here is the Index code for reference: <a href="http://grepcode.com/file/repo1.maven.org/maven2/org.apache.accumulo/examples-simple/1.4.0/org/apache/accumulo/examples/simple/shard/Index.java" rel="nofollow">http://grepcode.com/file/repo1.maven.org/maven2/org.apache.accumulo/examples-simple/1.4.0/org/apache/accumulo/examples/simple/shard/Index.java</a></p> <p>This program uses a BatchWriter to write Mutations to Accumulo and does it on a per file basis. To ensure it doesn't write more mutations than necessary and to ensure uniqueness (though I do believe Accumulo eventually merges same keys through compaction), Index.java has a HashSet that is used to determine if a word has been run across before. This is all relatively simple to understand.</p> <p>Moving to a map-only mapreduce job is more complex.</p> <p>This was my attempt at mapping, which seems to kinda work from the partial output I've seen the Accumulo table, but runs really really slow compared to the linear program Index.java</p> <pre><code>public static class MapClass extends Mapper&lt;LongWritable,Text,Text,Mutation&gt; { private HashSet&lt;String&gt; tokensSeen = new HashSet&lt;String&gt;(); @Override public void map(LongWritable key, Text value, Context output) throws IOException { FileSplit fileSplit = (FileSplit)output.getInputSplit(); System.out.println("FilePath " + fileSplit.getPath().toString()); String filePath = fileSplit.getPath().toString(); filePath = filePath.replace("unprocessed", "processed"); String[] words = value.toString().split("\\W+"); for (String word : words) { Mutation mutation = new Mutation(genPartition(filePath.hashCode() % 10)); word = word.toLowerCase(); if(!tokensSeen.contains(word)) { tokensSeen.add(word); mutation.put(new Text(word), new Text(filePath), new Value(new byte[0])); } try { output.write(null, mutation); } catch (InterruptedException e) { e.printStackTrace(); } } } } </code></pre> <p><strong>And the slow problem might be the fact that I'm running all of this on a test instance, a single-node instance of Hadoop with ZooKeeper and Accumulo on top.</strong> If that's the case, I just need to find a solution for uniqueness.</p> <p>Any help or advice provided is greatly appreciated.</p>
15,633,605
0
How to use certificate in https Apache server with client Java <p>I'm using an Apache server to provide a https access to some files in this server. The client use Java program to access these files via a proxy.</p> <p>In my apache configuration:</p> <pre><code>SSLCertificateFile /etc/apache2/ssl/apache.pem </code></pre> <p>The structure of the file <code>apache.pem</code>: </p> <pre><code>-----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- -----END CERTIFICATE----- </code></pre> <p>The client code is:</p> <pre><code>public static void main(String[] args) throws IOException { URL website = new URL("https://mywebsite.com/file.zip"); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream("test.zip"); fos.getChannel().transferFrom(rbc, 0, 1 &lt;&lt; 24); } </code></pre> <p>The error is </p> <pre><code>Exception in thread "main" javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching website.com found at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1697) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:257) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:251) at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1165) at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:154) at sun.security.ssl.Handshaker.processLoop(Handshaker.java:609) at sun.security.ssl.Handshaker.process_record(Handshaker.java:545) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:945) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1190) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1217) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1201) at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:440) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1139) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254) at java.net.URL.openStream(URL.java:1031) at HelloWorld.main(HelloWorld.java:38) </code></pre> <p>What I need to do to get Java understand my certificate? Do I need to regenerate the certificate with apache tool or java keytool? Thanks</p>
14,850,241
0
How to Identify the gps is turned off phonegap android <p>I want to figure out the gps is turned on in android device using phonegap. </p> <p>I tried like </p> <pre><code>navigator.geolocation.getCurrentPosition(function onSuccess(position){ console.log("The gps is availabile"); }, function geolocationError(error){ console.log("The geo error : " + error.code +"code : " + PositionError.PERMISSION_DENIED); if( error.code == PositionError.PERMISSION_DENIED ){ alert("Please turn on your gps to start the trip"); }else{ console.log("Gps is turned on. but not availabile"); } },{enableHighAccuracy: true , timeout:10000 }); </code></pre> <p>But when gps is turned off i never gets the <code>PositionError.PERMISSION_DENIED</code> error. Always it shows the <code>PositionError.POSITION_UNAVAILABLE</code> . How i can identify the gps is turned on /off ?.(not the gps availabile or not)</p>
1,984,966
0
<p>A lot of people underestimate the performance of java. I was once curious about this as well and wrote a simple program in java and then an equivalent in c (not much more than doing some operation with a for loop and a massive array). I don't recall exact figures, but I do know that java beat out c when the c program was not compiled with any optimization flags (under gcc). As expected, c pulled ahead when I finally compiled it with aggressive optimization. To be honest, it wasn't a scientific experiment by any means, but it did give me a baseline of knowing just where java stood.</p> <p>Of course, java probably falls further behind when you start doing things that require system calls. Though, I have seen 100MB/s read performance with disks and network with java programs running on modest hardware. Not sure what that says exactly, but it does indicate to me that it's good enough for pretty much anything I'll need it for.</p> <p>As for threads, if your java program creates 2 threads, then you have 2 <em>real</em> threads.</p>
30,509,148
0
<p>Found a workaround: retrieve text with jQuery object instead of WebElement.</p> <pre><code>$("g.highcharts-axis").find("tspan").jquery.text() == "Total fruit consumption" </code></pre>
15,109,040
0
Open application without tapping on icon <p>Is there any way by which we can launch the app by the external volume button or by any other gestures made on the iPhone instead of launching by the default way?</p> <p>OR</p> <p>Can our app recognise the users interaction with the volume button when app is in the background?</p>
22,143,615
0
<p>Add CSS</p> <pre><code> .test{ position:absolute;} .wrapper{ position:relative} </code></pre> <p>HTML</p> <pre><code>&lt;div class="wrapper"&gt; &lt;div id="1" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="2" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="3" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="4" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="5" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="6" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="7" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="8" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="9" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="10" class="full-circle"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>add new wrapper div</p> <p>SCRIPT</p> <pre><code>var gCurrentDot = 1; $('.full-circle').click(function() { var pos = $('#'+ gCurrentDot +'').position(); var posLeft = pos.left; var posTop = pos.top; $('body').append('&lt;div class="full-circle-green test"&gt;&lt;/div&gt;'); $('.test').css('left',posLeft).css('top',posTop).animate({height: "30px", width:"30px"}, {duration: 200, complete:function() { $(this).animate({height: "10px", width:"10px"}, {duration: 500}); }}); setTimeout(function () { $('.test').remove(); $('#'+ gCurrentDot +'').addClass('full-circle-green'); gCurrentDot++; }, 500); }); </code></pre>
15,733,849
0
assignment switch case c ++ <p>Requirements</p> <ol> <li>VULTURE IS V, OWL IS O, EAGLE IS E...</li> <li>A <code>for</code> loop to input the data each bird watcher has collected.</li> <li>inside the <code>for</code> loop, a <code>do ... while</code> loop to input and process the data collected by one bird watcher.</li> <li>inside the <code>do ... while</code> loop a <code>switch</code> statement is used to calculate the number of eggs for each type of bird. the default option, which does nothing, is used when an <code>x</code> is entered.</li> <li>the <code>do ... while</code> loop is exited when an X is entered for the type of bird.</li> <li>The totals part is fine as per code below</li> </ol> <p>ok, now my problem is I can't seem to get through my switch case. It prompts me for the first watcher's info, when I enter it, it never moves over to the next watcher.</p> <p>The input data given is</p> <pre><code>3 E2 O1 V2 E1 O3 X0 V2 V1 O1 E3 O2 E1 X0 V2 E1 X </code></pre> <p>And here is the code that I got so far:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; using namespace std; int main() { int totNrVultureEggs, totNrEagleEggs, totNrOwlEggs, nrEggs, nrVultureEggs, nrEagleEggs, nrOwlEggs, nrBirdWatchers, nrEggsEntered; char bird; // initialize grand totals for number of eggs for each type of bird cout &lt;&lt; "How many bird watchers took part in the study?"; cin &gt;&gt; nrBirdWatchers; // loop over number of bird watchers for (int i = 0; i &lt; nrBirdWatchers ;i++ ) { // initialize totals for number of eggs for each type of bird // this bird watcher saw nrVultureEggs = 0; nrEagleEggs = 0; nrOwlEggs = 0; cout &lt;&lt; "\nEnter data for bird watcher " &lt;&lt; i + 1 &lt;&lt; ":" &lt;&lt; endl; //loop over bird watchers do{ cin &gt;&gt; bird &gt;&gt; nrEggs; switch (bird) { case 'E': case 'e': nrEagleEggs = nrEagleEggs + nrEggs; case 'O': case 'o': nrOwlEggs = nrOwlEggs + nrEggs; case 'V': case 'v': nrVultureEggs = nrVultureEggs + nrEggs; default : nrBirdWatchers++; break; } }while (i &lt; nrBirdWatchers ) ; cout &lt;&lt; "Bird watcher " &lt;&lt; i + 1 &lt;&lt; " saw " &lt;&lt; nrVultureEggs; cout &lt;&lt; " vulture eggs, " &lt;&lt; nrEagleEggs &lt;&lt; " eagle eggs and "; cout &lt;&lt; nrOwlEggs &lt;&lt; " owl eggs " &lt;&lt; endl; // increment grand totals for eggs } // display results cout &lt;&lt; "\nTotal number of vulture eggs: " &lt;&lt; totNrVultureEggs; cout &lt;&lt; "\nTotal number of eagle eggs: " &lt;&lt; totNrEagleEggs; cout &lt;&lt; "\nTotal number of owl eggs: " &lt;&lt; totNrOwlEggs; return 0; } </code></pre>
22,981,385
0
<p>This is will match a string containing only 0 and 1's.</p> <pre><code>theString.matches("^[01]+$") </code></pre> <ol> <li>The character class [01] matches 0's or 1's</li> <li>The + says match 1 or more of the proceeding character class (so 0 or more 0's or 1's)</li> <li>The ^ and $ says that the entire string must match</li> </ol>
22,729,937
0
<p>Apparently, you're not missing anything else. Just try to do the following:</p> <ol> <li>Ensure that the necessary jars exist in the "lib" project folder;</li> <li>Do clean &amp; build;</li> </ol> <p>In the end, you should find those included jars, available within the "build" project folder.</p>
7,273,371
0
How do I edit and save a nib file at runtime? <p>Imagine an application that has a number of buttons it is displaying to the user. This application wants to allow the user to move the buttons around on the screen, customizing the display, and then save this configuration for later use. That is, when the app is closed and relaunched, it will come back up with the same configuration.</p> <p>I would like to create a nib file with the "factory default" button layout, but then create a new nib file storing the new UI after the user has configured it just the way they like it. How does one do this?</p> <p>Thanks!</p>
15,525,656
0
<p>The plugin's 'destroy' method removes the dialog functionality completely. This will return the element <strong>back to its pre-init state</strong>.</p> <pre><code>$( "#yourdiv" ).dialog( "destroy" ); </code></pre>
15,757,875
0
<blockquote> <p>Right click on Project--> Properties, Java Build Path.</p> </blockquote> <p><img src="https://i.stack.imgur.com/U06f6.png" alt="enter image description here"></p> <p>Check whether you have JRE installed. If installed click on EDIT and check whether its pointing to correct location</p> <p><img src="https://i.stack.imgur.com/eWXh7.png" alt="enter image description here"></p>
33,905,084
0
Share Session Variables between projects c# asp.net <p>Is there any way to share Session or any type of variables with their own data between projects? </p> <p>I have a solution wich has 2+ projects in wich I have an object called <code>Users</code>, you login on the first project and I place the whole Users object with all the data in a <code>Session["User"]</code> variable, and I'll like to later access on a different project but having the same stored data.</p> <p>As if in my first project a variable has a value = 1 the second project can read it in the second project in the same solution and still have the same value.</p> <p>EDIT: Found a solution to this within the next link:</p> <p><a href="http://stackoverflow.com/questions/2868316/sharing-sessions-across-applications-using-the-asp-net-session-state-service/3151315#3151315">Sharing sessions across applications using the ASP.NET Session State Service</a></p>
6,959,481
0
Rails Trying to submit a form onchange of dropdown <p>I have my Ajax working, builtin Rails javascript, with the submit button. However, I would like it to submit when I change the value of the dropdown box and eliminate the button. In my research I found what looks like the correct solution but I get no request to the server. Here is my dropdown form code, note it still has the submit button that worked before I added :onchange:</p> <pre><code> &lt;% form_tag('switch_car', :method =&gt; :put, :remote =&gt; true) do %&gt; &lt;div class="field"&gt; &lt;label&gt;Car Name:&lt;/label&gt; &lt;%= select_tag(:id, options_from_collection_for_select(active_cars, "id", "name"), :onchange =&gt; ("$('switch_car').submit()"))%&gt;&lt;%= submit_tag "Switch Car" %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>Here is the HTML generated:</p> <pre><code>&lt;form accept-charset="UTF-8" action="switch_car" data-remote="true" method="post"&gt;&lt;div style="margin:0;padding:0;display:inline"&gt;&lt;input name="utf8" type="hidden" value="&amp;#x2713;" /&gt;&lt;input name="_method" type="hidden" value="put" /&gt;&lt;input name="authenticity_token" type="hidden" value="PEbdqAoiik37lcoP4+v+dakpYxdpMkSm7Ub8eZpdF9I=" /&gt;&lt;/div&gt;&lt;div class="field"&gt; &lt;label&gt;Car Name:&lt;/label&gt; &lt;select id="id" name="id" onchange="$('switch_car').submit()"&gt;&lt;option value="9"&gt;Truck&lt;/option&gt; &lt;option value="10"&gt;Car&lt;/option&gt;&lt;/select&gt;&lt;input name="commit" type="submit" value="Switch Car" /&gt; &lt;/div&gt; </code></pre> <p>Thanks in advance for any help. </p>
36,964,796
0
OPENCART 2.0 IMAGE MANAGER NOT WORKING <p><strong>IF NOT WORKING THEN CHANGE THE CODE IN FOLLOWING : Admin /conroller / common / filemanager.php</strong></p> <p>BY VINAY SINGH [ [email protected]] skype : vinaysingh43</p> <p>or Chagne the Code in line no GLOBAL_BRACE </p> <p>CONSTANT this contstant not wroking wth some server ... </p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?php class ControllerCommonFileManager extends Controller { public function index() { $this-&gt;load-&gt;language('common/filemanager'); if (isset($this-&gt;request-&gt;get['filter_name'])) { $filter_name = rtrim(str_replace(array('../', '..\\', '..', '*'), '', $this-&gt;request-&gt;get['filter_name']), '/'); } else { $filter_name = null; } // Make sure we have the correct directory if (isset($this-&gt;request-&gt;get['directory'])) { $directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this-&gt;request-&gt;get['directory']), '/'); } else { $directory = DIR_IMAGE . 'catalog'; } if (isset($this-&gt;request-&gt;get['page'])) { $page = $this-&gt;request-&gt;get['page']; } else { $page = 1; } $data['images'] = array(); $this-&gt;load-&gt;model('tool/image'); // Get directories $directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR); if (!$directories) { $directories = array(); } // Get files // $files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE); $files1 = glob($directory . '/' . $filter_name . '*.jpg'); if (!$files1) { $files1 = array(); } $files2 = glob($directory . '/' . $filter_name . '*.jpeg'); if (!$files2) { $files2 = array(); } $files3 = glob($directory . '/' . $filter_name . '*.JPG'); if (!$files3) { $files3 = array(); } $files4 = glob($directory . '/' . $filter_name . '*.png'); if (!$files4) { $files4 = array(); } $files5 = glob($directory . '/' . $filter_name . '*.JPEG'); if (!$files5) { $files5 = array(); } $files6 = glob($directory . '/' . $filter_name . '*.PNG'); if (!$files6) { $files6 = array(); } $files7 = glob($directory . '/' . $filter_name . '*.GIF'); if (!$files7) { $files7 = array(); } $files8 = glob($directory . '/' . $filter_name . '*.gif'); if (!$files8) { $files8 = array(); } $files = array_merge($files1, $files2,$files3,$files4,$files5,$files6,$files7,$files8); // Merge directories and files $images = array_merge($directories, $files); // Get total number of files and directories $image_total = count($images); // Split the array based on current page number and max number of items per page of 10 $images = array_splice($images, ($page - 1) * 16, 16); foreach ($images as $image) { $name = str_split(basename($image), 14); if (is_dir($image)) { $url = ''; if (isset($this-&gt;request-&gt;get['target'])) { $url .= '&amp;target=' . $this-&gt;request-&gt;get['target']; } if (isset($this-&gt;request-&gt;get['thumb'])) { $url .= '&amp;thumb=' . $this-&gt;request-&gt;get['thumb']; } $data['images'][] = array( 'thumb' =&gt; '', 'name' =&gt; implode(' ', $name), 'type' =&gt; 'directory', 'path' =&gt; utf8_substr($image, utf8_strlen(DIR_IMAGE)), 'href' =&gt; $this-&gt;url-&gt;link('common/filemanager', 'token=' . $this-&gt;session-&gt;data['token'] . '&amp;directory=' . urlencode(utf8_substr($image, utf8_strlen(DIR_IMAGE . 'catalog/'))) . $url, true) ); } elseif (is_file($image)) { // Find which protocol to use to pass the full image link back if ($this-&gt;request-&gt;server['HTTPS']) { $server = HTTPS_CATALOG; } else { $server = HTTP_CATALOG; } $data['images'][] = array( 'thumb' =&gt; $this-&gt;model_tool_image-&gt;resize(utf8_substr($image, utf8_strlen(DIR_IMAGE)), 100, 100), 'name' =&gt; implode(' ', $name), 'type' =&gt; 'image', 'path' =&gt; utf8_substr($image, utf8_strlen(DIR_IMAGE)), 'href' =&gt; $server . 'image/' . utf8_substr($image, utf8_strlen(DIR_IMAGE)) ); } } $data['heading_title'] = $this-&gt;language-&gt;get('heading_title'); $data['text_no_results'] = $this-&gt;language-&gt;get('text_no_results'); $data['text_confirm'] = $this-&gt;language-&gt;get('text_confirm'); $data['entry_search'] = $this-&gt;language-&gt;get('entry_search'); $data['entry_folder'] = $this-&gt;language-&gt;get('entry_folder'); $data['button_parent'] = $this-&gt;language-&gt;get('button_parent'); $data['button_refresh'] = $this-&gt;language-&gt;get('button_refresh'); $data['button_upload'] = $this-&gt;language-&gt;get('button_upload'); $data['button_folder'] = $this-&gt;language-&gt;get('button_folder'); $data['button_delete'] = $this-&gt;language-&gt;get('button_delete'); $data['button_search'] = $this-&gt;language-&gt;get('button_search'); $data['token'] = $this-&gt;session-&gt;data['token']; if (isset($this-&gt;request-&gt;get['directory'])) { $data['directory'] = urlencode($this-&gt;request-&gt;get['directory']); } else { $data['directory'] = ''; } if (isset($this-&gt;request-&gt;get['filter_name'])) { $data['filter_name'] = $this-&gt;request-&gt;get['filter_name']; } else { $data['filter_name'] = ''; } // Return the target ID for the file manager to set the value if (isset($this-&gt;request-&gt;get['target'])) { $data['target'] = $this-&gt;request-&gt;get['target']; } else { $data['target'] = ''; } // Return the thumbnail for the file manager to show a thumbnail if (isset($this-&gt;request-&gt;get['thumb'])) { $data['thumb'] = $this-&gt;request-&gt;get['thumb']; } else { $data['thumb'] = ''; } // Parent $url = ''; if (isset($this-&gt;request-&gt;get['directory'])) { $pos = strrpos($this-&gt;request-&gt;get['directory'], '/'); if ($pos) { $url .= '&amp;directory=' . urlencode(substr($this-&gt;request-&gt;get['directory'], 0, $pos)); } } if (isset($this-&gt;request-&gt;get['target'])) { $url .= '&amp;target=' . $this-&gt;request-&gt;get['target']; } if (isset($this-&gt;request-&gt;get['thumb'])) { $url .= '&amp;thumb=' . $this-&gt;request-&gt;get['thumb']; } $data['parent'] = $this-&gt;url-&gt;link('common/filemanager', 'token=' . $this-&gt;session-&gt;data['token'] . $url, true); // Refresh $url = ''; if (isset($this-&gt;request-&gt;get['directory'])) { $url .= '&amp;directory=' . urlencode($this-&gt;request-&gt;get['directory']); } if (isset($this-&gt;request-&gt;get['target'])) { $url .= '&amp;target=' . $this-&gt;request-&gt;get['target']; } if (isset($this-&gt;request-&gt;get['thumb'])) { $url .= '&amp;thumb=' . $this-&gt;request-&gt;get['thumb']; } $data['refresh'] = $this-&gt;url-&gt;link('common/filemanager', 'token=' . $this-&gt;session-&gt;data['token'] . $url, true); $url = ''; if (isset($this-&gt;request-&gt;get['directory'])) { $url .= '&amp;directory=' . urlencode(html_entity_decode($this-&gt;request-&gt;get['directory'], ENT_QUOTES, 'UTF-8')); } if (isset($this-&gt;request-&gt;get['filter_name'])) { $url .= '&amp;filter_name=' . urlencode(html_entity_decode($this-&gt;request-&gt;get['filter_name'], ENT_QUOTES, 'UTF-8')); } if (isset($this-&gt;request-&gt;get['target'])) { $url .= '&amp;target=' . $this-&gt;request-&gt;get['target']; } if (isset($this-&gt;request-&gt;get['thumb'])) { $url .= '&amp;thumb=' . $this-&gt;request-&gt;get['thumb']; } $pagination = new Pagination(); $pagination-&gt;total = $image_total; $pagination-&gt;page = $page; $pagination-&gt;limit = 16; $pagination-&gt;url = $this-&gt;url-&gt;link('common/filemanager', 'token=' . $this-&gt;session-&gt;data['token'] . $url . '&amp;page={page}', true); $data['pagination'] = $pagination-&gt;render(); $this-&gt;response-&gt;setOutput($this-&gt;load-&gt;view('common/filemanager', $data)); } public function upload() { $this-&gt;load-&gt;language('common/filemanager'); $json = array(); // Check user has permission if (!$this-&gt;user-&gt;hasPermission('modify', 'common/filemanager')) { $json['error'] = $this-&gt;language-&gt;get('error_permission'); } // Make sure we have the correct directory if (isset($this-&gt;request-&gt;get['directory'])) { $directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this-&gt;request-&gt;get['directory']), '/'); } else { $directory = DIR_IMAGE . 'catalog'; } // Check its a directory if (!is_dir($directory)) { $json['error'] = $this-&gt;language-&gt;get('error_directory'); } if (!$json) { if (!empty($this-&gt;request-&gt;files['file']['name']) &amp;&amp; is_file($this-&gt;request-&gt;files['file']['tmp_name'])) { // Sanitize the filename $filename = basename(html_entity_decode($this-&gt;request-&gt;files['file']['name'], ENT_QUOTES, 'UTF-8')); // Validate the filename length if ((utf8_strlen($filename) &lt; 3) || (utf8_strlen($filename) &gt; 255)) { $json['error'] = $this-&gt;language-&gt;get('error_filename'); } // Allowed file extension types $allowed = array( 'jpg', 'jpeg', 'gif', 'png' ); if (!in_array(utf8_strtolower(utf8_substr(strrchr($filename, '.'), 1)), $allowed)) { $json['error'] = $this-&gt;language-&gt;get('error_filetype'); } // Allowed file mime types $allowed = array( 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png', 'image/gif' ); if (!in_array($this-&gt;request-&gt;files['file']['type'], $allowed)) { $json['error'] = $this-&gt;language-&gt;get('error_filetype'); } // Return any upload error if ($this-&gt;request-&gt;files['file']['error'] != UPLOAD_ERR_OK) { $json['error'] = $this-&gt;language-&gt;get('error_upload_' . $this-&gt;request-&gt;files['file']['error']); } } else { $json['error'] = $this-&gt;language-&gt;get('error_upload'); } } if (!$json) { move_uploaded_file($this-&gt;request-&gt;files['file']['tmp_name'], $directory . '/' . $filename); $json['success'] = $this-&gt;language-&gt;get('text_uploaded'); } $this-&gt;response-&gt;addHeader('Content-Type: application/json'); $this-&gt;response-&gt;setOutput(json_encode($json)); } public function folder() { $this-&gt;load-&gt;language('common/filemanager'); $json = array(); // Check user has permission if (!$this-&gt;user-&gt;hasPermission('modify', 'common/filemanager')) { $json['error'] = $this-&gt;language-&gt;get('error_permission'); } // Make sure we have the correct directory if (isset($this-&gt;request-&gt;get['directory'])) { $directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this-&gt;request-&gt;get['directory']), '/'); } else { $directory = DIR_IMAGE . 'catalog'; } // Check its a directory if (!is_dir($directory)) { $json['error'] = $this-&gt;language-&gt;get('error_directory'); } if (!$json) { // Sanitize the folder name $folder = str_replace(array('../', '..\\', '..'), '', basename(html_entity_decode($this-&gt;request-&gt;post['folder'], ENT_QUOTES, 'UTF-8'))); // Validate the filename length if ((utf8_strlen($folder) &lt; 3) || (utf8_strlen($folder) &gt; 128)) { $json['error'] = $this-&gt;language-&gt;get('error_folder'); } // Check if directory already exists or not if (is_dir($directory . '/' . $folder)) { $json['error'] = $this-&gt;language-&gt;get('error_exists'); } } if (!$json) { mkdir($directory . '/' . $folder, 0777); chmod($directory . '/' . $folder, 0777); $json['success'] = $this-&gt;language-&gt;get('text_directory'); } $this-&gt;response-&gt;addHeader('Content-Type: application/json'); $this-&gt;response-&gt;setOutput(json_encode($json)); } public function delete() { $this-&gt;load-&gt;language('common/filemanager'); $json = array(); // Check user has permission if (!$this-&gt;user-&gt;hasPermission('modify', 'common/filemanager')) { $json['error'] = $this-&gt;language-&gt;get('error_permission'); } if (isset($this-&gt;request-&gt;post['path'])) { $paths = $this-&gt;request-&gt;post['path']; } else { $paths = array(); } // Loop through each path to run validations foreach ($paths as $path) { $path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/'); // Check path exsists if ($path == DIR_IMAGE . 'catalog') { $json['error'] = $this-&gt;language-&gt;get('error_delete'); break; } } if (!$json) { // Loop through each path foreach ($paths as $path) { $path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/'); // If path is just a file delete it if (is_file($path)) { unlink($path); // If path is a directory beging deleting each file and sub folder } elseif (is_dir($path)) { $files = array(); // Make path into an array $path = array($path . '*'); // While the path array is still populated keep looping through while (count($path) != 0) { $next = array_shift($path); foreach (glob($next) as $file) { // If directory add to path array if (is_dir($file)) { $path[] = $file . '/*'; } // Add the file to the files to be deleted array $files[] = $file; } } // Reverse sort the file array rsort($files); foreach ($files as $file) { // If file just delete if (is_file($file)) { unlink($file); // If directory use the remove directory function } elseif (is_dir($file)) { rmdir($file); } } } } $json['success'] = $this-&gt;language-&gt;get('text_delete'); } $this-&gt;response-&gt;addHeader('Content-Type: application/json'); $this-&gt;response-&gt;setOutput(json_encode($json)); } }</code></pre> </div> </div> </p>
26,273,376
0
<p>You need to change window.location in a success callback since it may happen before the asynchronous POST request is finished.</p> <pre><code>$.ajax({ type: "POST", url: "/mobile.php", data: {values:"mobile"} success: function(){ window.location = "http://dekstopversionexample.lt"; } }); </code></pre>
27,377,344
0
ui-select angularjs bootstrap undefined is not a function error <p>I'm having some issues trying to work with the ui-select library. I'm trying to use the select dropdown features but it doesn't work properly.</p> <p>This is the library used: <a href="https://github.com/angular-ui/ui-select" rel="nofollow">https://github.com/angular-ui/ui-select</a></p> <p>Here's my html code:</p> <pre><code>&lt;h3&gt;Array of strings&lt;/h3&gt; &lt;ui-select multiple ng-model="selCountry.selLoc" theme="/resources/ui-select/bootstrap" ng-disabled="disabled" style="width: 300px;"&gt; &lt;ui-select-match placeholder="Select locations..."&gt;{{$selCountry.selLoc}}&lt;/ui-select-match&gt; &lt;ui-select-choices repeat="loc in selCountry.locations| filter:$select.search"&gt; {{loc}} &lt;/ui-select-choices&gt; &lt;/ui-select&gt; </code></pre> <p>The error it troughs is : undefined is not a function and it troughs this erro when I click on the ui-selext box.</p> <pre><code>TypeError: undefined is not a function at link (http://localhost:8090/resources/ui-select/select.js:1202:11) at H (http://localhost:8090/resources/js/angular-1.2.12.min.js:49:375) at f (http://localhost:8090/resources/js/angular-1.2.12.min.js:42:399) at H (http://localhost:8090/resources/js/angular-1.2.12.min.js:49:316) at f (http://localhost:8090/resources/js/angular-1.2.12.min.js:42:399) at http://localhost:8090/resources/js/angular-1.2.12.min.js:42:67 at http://localhost:8090/resources/js/angular-1.2.12.min.js:43:303 at A (http://localhost:8090/resources/js/angular-1.2.12.min.js:47:46) </code></pre> <p>Any advice on what could be the problem? </p> <p>Thank you</p> <p>PS</p> <p>When I click on the select.js error link it takes me to the following piece of code.</p> <pre><code> // Recreates old behavior of ng-transclude. Used internally. .directive('uisTranscludeAppend', function () { return { link: function (scope, element, attrs, ctrl, transclude) { transclude(scope, function (clone) { element.append(clone); }); } }; }) </code></pre> <p>Not sure what is causing that problem as the code is very similar to what the example code is.</p>
3,191,551
0
SQL Create table script from DBMS contains [ ] <p>If some one does right click on a given Table in a Database using SQL Server management Studio from Microsoft and create script table to query window, it displays the create table code in the window. I notice something like the following</p> <p>CREATE TABLE [dbo].[Login]( <br> [UserId] [int] NOT NULL,<br> [LoginName] nvarchar COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, <br> etc <br> )<br></p> <p>Is this how it appears in other DBMS too ? <br> Is this something specific to DBMS used ? <br> Is it just a fancy view only ?</p> <p>Why are "<b>[ ]</b>" used around column names and table names. Simple TSQL definition would look something like <br> CREATE TABLE table_name ( <br> Column#1 Datatype NOT NULL, <br> Column#2 Datatype NOT NULL UNIQUE, <br> -- etc... <br> ) <br></p> <p>Please dont mind my silly questions.</p> <p>Thanks in advance,<br> Balaji S</p>
10,288,141
0
<p>Well infinite data is theoretically possible while the practical implementation differ from process to process. </p> <ul> <li>Approach 1 - Generally many protocol do send size in the first few bytes ( 4 bytes ) and you can have a while loop </li> </ul> <p>{</p> <pre><code>int i = 0, ret = 1; unsigned char buffer[4]; while ( i&lt;4 &amp;&amp; ret == 0) socket.receive(buffer + i, 1 , ret); // have a while loop to read the amount of data you need. Malloc the buffer accordingly </code></pre> <p>}</p> <ul> <li>Approach 2 - Or in your case where you don't know the lenght ( infinite )</li> </ul> <p>{</p> <pre><code>char *buffer = (char *)malloc(TCP_MAX_BUF_SIZE); std::size_t total = 0, received = 0; while ( total &lt; TCP_MAX_BUF_SIZE &amp;&amp; return &gt;= 0) { socket.receive(buffer, sizeof(buffer), received); total += received; } //do something with your data </code></pre> <p>}</p> <p>You will have to break at somepoint and process your data Dispatch it to another thread of release the memory.</p>
18,623,731
0
<blockquote> <p>So my question is how can i set the response object to contain the processed list of the images</p> </blockquote> <p>Use a stylesheet rather than an XPath selector:</p> <pre><code> select * from xslt where url="http://www.mysite.com/page-path" and stylesheet="http://www.mysite.com/page-path.xsl" </code></pre> <p>Define the stylesheet as such:</p> <pre><code> &lt;xsl:template match="img[@alt]"&gt; &lt;xsl:for-each select="@alt"&gt; &lt;script&gt; alt.push(&lt;xsl:value-of select="."/&gt;); &lt;/script&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; &lt;xsl:template match="img[not(@alt)]"&gt; &lt;xsl:for-each select="@src"&gt; &lt;script&gt; noalt.push(&lt;xsl:value-of select="."/&gt;); &lt;/script&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; </code></pre>
21,724,486
0
Remove all numbers in brackets with the brackets from string <p>Trying to remove city code from string for my additional I have wrote the brackets removal with indexOf. how to do this with regex?</p> <p>Mr Smith (344) 455 66 44</p> <p>to </p> <p>Mr Smith 455 66 44</p>
10,888,707
0
<p>System.Data.Entity.dll is not bin deployable. If you have .NET Framework 4 installed on the target machine you should have this assembly. It should be in the GAC. When loading assemblies CLR first looks in GAC and ignores whatever you have in your bin directory. If you don't have the .NET Framework 4 on the target machine your program will not work - System.Data.Entity.dll is part of .NET Framework and depends on .NET Framework (in this case .NET Framework 4). Try removing and readding reference to System.Data.Entity.dll to clear all the changes you made in the project to copy it and then deploy your program to the target machine.</p>
21,670,606
0
MongoDB C driver does not return any results for aggregation query <p>I have following SQL query:</p> <p>SELECT SUM("PAYMENT_HISTORY"."AMOUNT_PAID") FROM "PAYMENT_HISTORY" WHERE (("PAYMENT_HISTORY".YEAR >= 2011) AND ("PAYMENT_HISTORY".YEAR &lt;= 2013) AND ("PAYMENT_HISTORY"."AMOUNT_PAID" >= 500.0))</p> <p>same SQL after conversion was ran from MongoDB shell and it returns value.</p> <p>db.PAYMENT_HISTORY.aggregate( { $match : {$and: [{YEAR: {$gte : 2011}}, {YEAR: {$lte : 2013}}, {AMOUNT_PAID: {$gte: 500.00}}]}}, { $group : {_id : "POLICY_ID", total:{$sum : "$AMOUNT_PAID"}}} )</p> <p>While i am trying to run through MongoDB C driver, it doesn't return any results.</p> <pre><code>int status = mongo_client( mNoSQLConnection, "127.0.0.1", 27017 ); if (status != MONGO_OK){ switch (mNoSQLConnection-&gt;err) { case MONGO_CONN_NO_SOCKET: printf( "no socket\n" ); case MONGO_CONN_FAIL: printf( "connection failed\n" ); case MONGO_CONN_NOT_MASTER: printf( "not master\n" ); } } else{ bson query[1], b_result[1]; mongo_cursor cursor[1]; bson_init( query ); bson_append_string(query, "aggregate", "PAYMENT_HISTORY"); bson_append_start_object(query, "$match"); bson_append_start_array(query, "$and"); bson_append_start_object(query, "$gte"); bson_append_int(query, "YEAR", 2011); bson_append_finish_object(query); bson_append_start_object(query, "$lte"); bson_append_int(query, "YEAR", 2013); bson_append_finish_object(query); bson_append_start_object(query, "$gte"); bson_append_double(query, "AMOUNT_PAID", 500.00); bson_append_finish_object(query); bson_append_finish_array(query); bson_append_finish_object(query); bson_append_start_object(query, "$group"); bson_append_string(query, "_id", "POLICY_ID"); bson_append_string(query, "total", "total"); bson_append_start_object(query, "$sum"); bson_append_start_object(query, "$AMOUNT_PAID"); bson_append_finish_object(query); bson_append_finish_object(query); bson_append_finish_object(query); bson_finish( query ); bson_print(query); int status1; status1 = mongo_run_command(mNoSQLConnection, "DB_NAME", query, b_result); if (MONGO_OK != status1 ) { } else { /*command results*/ bson_print(b_result); } bson_destroy( query ); mongo_cursor_destroy( cursor ); } </code></pre> <p>Can somebody help me in figuring out mistake/s in above code?</p> <p>Thanks</p>
36,581,419
0
deleting particular rows takes longer time to execute oracle. have to kill the session <p>I have 3 tables Attribute_type, Attribute, Attribute_assignment which is referencing one another. Attribute has Attribute_id + Attribute_type_id, Attribute_assignment has Assignment_id + Attribute_id + Attribute_type_id</p> <p>There are some stale data in Attribute_assignment, whose parents are deleted and its dangling. So i tried to delete those rows. Few got deleted very easily , but last 4 rows are not getting deleted at all. It just takes long time. Because of this I am not able to add constraints as well. </p> <p>Please suggest.</p>
23,129,870
0
How do I clean input buffer before using getch()? <p>So, I am using GetAsyncKeyState() to see when some key is pressed. But, after using it I need to use getch(). But it seems that getch() gets whatever GetAsyncKeyState() got before again. That is the version of my simplified code:</p> <pre><code>#include &lt;graphics.h&gt; int main() { initwindow(100, 100); while(true) { if (GetAsyncKeyState(VK_RETURN)) //wait for user to press "Enter" break; //do other stuff } getch(); //this is just skipped return 0; } </code></pre> <p>I think I need to clean the input buffer before using getch(). But how? PS: GetAsyncKeyState() is a must-use for me and I have not found any substitute for getch(), which could work with BGI window and which would fix the problem. Hoping for some advice and thank you.</p>
37,175,215
0
Error when trying to create a Timer in EJB <p>I'm having a problem with a timer in <strong>EJB</strong>.I don't have experience whit this type application, so I don't know What to do for resolve this problem.</p> <p>timer cod:</p> <pre><code> @Schedule(minute="*/2", second="0", dayOfMonth="*", month="*", year="*", hour="6-23", dayOfWeek="*", persistent = false) public void cargaC() { ....} @Schedule(minute="10", second="0", dayOfMonth="*", month="*", year="*", hour="1", dayOfWeek="*", persistent = false) public void limpaTabelaC(){ ....} </code></pre> <p>error: </p> <pre><code> 18:56:10,103 INFO [org.jboss.as.ejb3] (EJB default - 4) JBAS014121: Timer: [id=c7a5c2c9-2b6c-49d8-956a-f831ebab53c3 timedObjectId=PrjX_V2.PrjX_V2.CargaDados auto-timer?:true persistent?:false timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@35d07654 initialExpiration=Wed May 11 06:00:00 BRT 2016 intervalDuration(in milli sec)=0 nextExpiration=Wed May 11 18:58:00 BRT 2016 timerState=IN_TIMEOUT will be retried 18:56:10,103 INFO [org.jboss.as.ejb3] (EJB default - 4) JBAS014123: Retrying timeout for timer: [id=c7a5c2c9-2b6c-49d8-956a-f831ebab53c3 timedObjectId=PrjX_V2.PrjX_V2.CargaDados auto-timer?:true persistent?:false timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@35d07654 initialExpiration=Wed May 11 06:00:00 BRT 2016 intervalDuration(in milli sec)=0 nextExpiration=Wed May 11 18:58:00 BRT 2016 timerState=IN_TIMEOUT 18:56:14,813 ERROR [org.jboss.as.ejb3] (EJB default - 4) JBAS014122: Error during retrying timeout for timer: [id=c7a5c2c9-2b6c-49d8-956a-f831ebab53c3 timedObjectId=PrjX_V2.PrjX_V2.CargaDados auto-timer?:true persistent?:false timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@35d07654 initialExpiration=Wed May 11 06:00:00 BRT 2016 intervalDuration(in milli sec)=0 nextExpiration=Wed May 11 18:58:00 BRT 2016 timerState=RETRY_TIMEOUT: javax.ejb.EJBException: Unexpected Error </code></pre> <p>someone can help me?</p>
3,830,858
0
<p>I think you're confusing the properties which pluck() works on with HTML attributes. It's anyway easier to add the pseudo class of checked as part of the initial selector, like:</p> <pre><code>$$('li.litemd input:checked').each(function(s) { alert(s.next().innerHTML); }); </code></pre> <p><a href="http://jsfiddle.net/tXXwD/1/" rel="nofollow">Example</a></p>
33,846,868
0
<p>You can use <a href="https://github.com/prasmussen/chrome-cli" rel="nofollow">chrome-cli</a> for this case.</p>
13,398,665
0
Assigning variable names to an output graph in R <p>I am a new user of R statistics. I am having a huge <code>for</code> loop, of multiple massive files, the loop ends up giving me the result of a graph.</p> <p>Everything is working fine, except with the output file names. what do I want exactly to do? </p> <p>I am using </p> <pre><code>data1 &lt;- read.csv("filepath/filename", header=TRUE, sep=",") data2 &lt;- read.csv("filepath/filename", header=TRUE, sep=",") data3 &lt;- read.csv("filepath/filename", header=TRUE, sep=",") </code></pre> <p>and so on... to read my files.</p> <p>I want the output graph file name to contain the name of the data files and columns from which it was generated. For example:</p> <pre><code>graph1-data1-data3-columnE.pdf </code></pre> <p><strong>Important note:</strong> all the files I am reading have exactly the same column names and number.</p> <p>What command should I use to do this?</p>
7,794
0
<p>How about:</p> <pre><code>protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e) { e.Handled = !AreAllValidNumericChars(e.Text); base.OnPreviewTextInput(e); } private bool AreAllValidNumericChars(string str) { foreach(char c in str) { if(!Char.IsNumber(c)) return false; } return true; } </code></pre>
2,872,166
0
<p>Alternativaly you could try the standard actions <a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/StdActns_TSearchFind.html" rel="nofollow noreferrer">TSearchFind</a>/<a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/StdActns_TSearchFindNext.html" rel="nofollow noreferrer">TSearchFindNext</a>. However I haven't tried them myself, so I can't say how well they work in practice.</p>
2,872,920
0
<p>Full disclosure: I am a developer on the Visual Studio Profiler Team.</p> <p>Visual Studio Test Edition does not have a profiler, but the following editions do:</p> <ul> <li>Visual Studio 2005 Development Edition, Team Suite</li> <li>Visual Studio 2008 Development Edition, Team Suite</li> <li>Visual Studio 2010 Premium, Ultimate</li> </ul> <p>Currently, the VS Profiler is not capable of profiling across machines, but a new feature was introduced in VS2010: Tier Interaction Profiling. Essentially, it will show you timing data for any ADO.NET database calls you make.</p> <p>Additional resources:</p> <ul> <li><a href="http://blogs.msdn.com/habibh/archive/2009/06/30/walkthrough-using-the-tier-interaction-profiler-in-visual-studio-team-system-2010.aspx" rel="nofollow noreferrer">Walkthrough: Using the Tier Interaction Profiler in Visual Studio Team System 2010</a></li> <li><a href="http://blogs.msdn.com/profiler/archive/2009/12/28/multi-tier-performance-analysis.aspx" rel="nofollow noreferrer">Multi-Tier Performance Analysis</a></li> </ul>
23,986,330
0
<p><strong>Quick answer</strong> - both operating systems have features for safely unmounting the drive. An unmounted drive can be snapshotted without fear of corruption.</p> <p><strong>Long answer</strong> An EBS snapshot is point-in-time and differential (it does not "copy" your data per-se), so as long as your drive is in a consistent and restorable state when it begins, you'll avoid the corruption (since the snapshot is atomic).</p> <p>As you have implied, whatever state the whole drive is in when it starts, that's what your snapshot image will be when it is restored (if you snapshot while you are half-way done writing a file, then, by-golly, that file will be half-written when you restore).</p> <p>For both Linux and Windows, a consistent state can be this can be acheived by unmounting the drive. This will guarantee that your buffers are flushed to disk and no writes can occur. In both linux and windows there are commands to list which processes are using the drive; once you have stopped those processes or otherwise gotten them to stop marking the drive for use (different for each program/service), you can unmount. In windows, this is very easy by setting your drive as a "removable drive" and then using the "safely remove hardware" feature to unmount. In linux, you can unmount with the "umount" command.</p> <p>There are other sneakier ways, but the above is pretty universal.</p> <p>So assuming you get to a restorable state before you begin, you can resume using your drive as soon as the snapshot starts (you do not need to wait for the snapshot completes before you unlock (or remount) and resume use). At that point you can remount the volume.</p> <p><strong>How AWS snapshot works:</strong></p> <p>Your volume and the snapshot is just a set of pointers, when you take a snapshot, you just diverge any blocks that you write to from that point forward; they are effectively new blocks associated with the volume, and the old blocks at that logical place in the volume are left alone so that the snapshot stays the same logically.</p> <p>This is also why subsequent snapshots will tend to go faster (they are differential).</p> <p><a href="http://harish11g.blogspot.com/2013/04/understanding-Amazon-Elastic-block-store-EBS-snapshots.html" rel="nofollow">http://harish11g.blogspot.com/2013/04/understanding-Amazon-Elastic-block-store-EBS-snapshots.html</a></p>
24,392,492
0
VMWare vs Azure virtual machines <p>I searched the internet but couldnt find an answer. I know that VMWare gives you a true full virtual machine with a assigned NIC card where Azure virtual machine which is connected through Remote Desktop does not do full virtual. Is full virtual the correct terminology used to describe this or am I wrong?</p> <p>The reason this came up is because I have both environments to play with at work and have multiple customers with different vpn setup. I've noticed that if split tunneling disabled, I cannot use Azure virtual machine and would have to setup on VMWare unless I use something like TeamViewer to connect into the Azure virtual machine.</p> <p>One of my customer (customer A), blocks all traffic after the VPN is established. This includes RDP and HTTP, the only way for this to work is to install a virtual machine on VMware and use vSphere to connect in. </p> <p>My last question, is it possible to get this one customer A working on Azure? My management team wants the IT shop to be all Microsoft so that means they dont want to use VMware anymore. I've tried using TeamViewer but after connecting to VPN (Cisco Anyconect) the connection to TeamViewer gets disconnected because it runs on 80 HTTP and 443 HTTPS. Any work around on Azure that anyone would like to share? Thanks!</p>
32,701,824
0
Swift: Comparing Implicitly Unwrapped Optionals results in "unexpectedly found nil while unwrapping an Optional values" <p>If got this class and would like to compare instances of it based on the value </p> <pre><code>class LocationOption: NSObject { var name:String! var radius:Int! var value:String! override func isEqual(object: AnyObject?) -&gt; Bool { if let otherOption = object as? LocationOption { return (self.name == otherOption.name) &amp;&amp; (self.radius == otherOption.radius) &amp;&amp; (self.value == otherOption.value) } return false } } </code></pre> <p>When executing this: </p> <pre><code>var a = LocationOption() var b = LocationOption() a.name = "test" b.name = "test" if a == b { // Crashes here!! print("a and b are the same"); } </code></pre> <p>This crashes with "unexpectedly found nil while unwrapping an Optional value"? You can copy all this into a Playground to reproduce.</p> <p>It seems to be due to the <code>Implicitly Unwrapped Optionals</code>. If I declare all fields as Optionals it works as expected.</p> <p>But in my case, I would like to have these properties as <code>Implicitly Unwrapped Optionals</code>. How should I write the isEqual?</p> <p>===</p> <p>UPDATE: @matt is right and as I didn't want to change to "regular" Optionals I ended up with this:</p> <pre><code>class LocationOption: Equatable { var name:String! var requireGps:Bool! var radius:Int! var value:String! } func ==(lhs: LocationOption, rhs: LocationOption) -&gt; Bool { let ln:String? = lhs.name as String?, rn = rhs.name as String? let lr = lhs.radius as Int?, rr = rhs.radius as Int? return ln == rn &amp;&amp; lr == rr } </code></pre>
27,847,647
0
<p>use a normalize.css to avoid this issue, if not set none style to an element, he inherit the user agent style.</p> <p><a href="http://necolas.github.io/normalize.css/" rel="nofollow">http://necolas.github.io/normalize.css/</a></p>
18,443,350
0
<p>The denormalization is in the dimension tables in a star schema: E. g. in a product table, you explicitly have many columns like several levels of product category in this one table, instead of having one table for each level, and using foreign keys referencing those values.</p> <p>This means you have normalization with regard to facts, but stop normalizing on the dimension tables.</p> <p>Furthermore, you often do not even completely denormalize the facts. A typical example would be this: in a completely normalized table, you would use only two columns 'number of units sold' and 'price per unit', but in an OLAP database, it may make sense to redundantly have another column for the 'sales value' which could easily be calculated by multiplying units sold and the price per unit.</p>
3,109,912
0
<p>The "correct" way according to the Java EE architecture would be to have a JCA connector to do inbound/outbound connection with the SMTP server. </p> <p>The JCA connector can do whatever you want, including threading and connection to external systems with sockets. Actually JMS is just a special kind of JCA connector that connects to JMS broker and delivers message to "regular" MDB. A JCA connector can then poll the SMTP server and delivers the message to a custom MDB. </p> <p>The best document about JCA is <a href="http://developers.sun.com/appserver/reference/techart/resource_adapters.pdf" rel="nofollow noreferrer">Creating Resource Adapters with J2EE Connector Architecture 1.5</a>, and it does actually use the example of email delivery. Luck you :) I suggest you have a look at it. The code can be found as part of the Java EE samples and uses JavaMail, but I don't know if it's production ready. </p> <p>Related: </p> <ul> <li><a href="http://stackoverflow.com/questions/2998926/new-to-jee-architecture-suggestions-for-a-service-daemon">Java EE architecture suggestions for a service/daemon?</a></li> <li><a href="http://stackoverflow.com/questions/2154490/an-ear-jee-application-which-listen-to-a-socket-request">Java EE application which listen to a socket request.</a></li> </ul>
23,469,361
0
<p>The issue is created by the logo image. Images are inline elements so they have a white-space after them. To remove the white-space, you can display the image as a block element by adding this CSS :</p> <pre><code>header &gt; img{ display: block; } </code></pre>
10,548,375
0
Call to function 'CFURLCreateStringByAddingPercentEscapes' returns a Core Foundation object with a +1 retain count <p>I am converting my project to ARC and Xcode thinks there is a memory leak here, does anyone see anything wrong with this? I didn't write this code so I am not familiar with C calls.</p> <pre><code>- (NSString*) URLEscaped { NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes( NULL, (CFStringRef)self, NULL, (CFStringRef)@"!*'();:@&amp;=+$,/?%#[]", kCFStringEncodingUTF8); return encodedString; } </code></pre>
13,001,227
0
<p>You got the parameters in the wrong order (from the <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html#matches%28java.lang.String,%20java.lang.CharSequence%29">documentation</a>)</p> <pre><code>Pattern.matches(String regex, CharSequence input) </code></pre>
9,128,382
0
<p>You can do this in <a href="http://noda-time.googlecode.com">Noda Time</a> fairly easily:</p> <pre><code>using System; using NodaTime; class Test { static void Main() { ShowAge(1988, 9, 6); ShowAge(1991, 3, 31); ShowAge(1991, 2, 25); } private static readonly PeriodType YearMonth = PeriodType.YearMonthDay.WithDaysRemoved(); static void ShowAge(int year, int month, int day) { var birthday = new LocalDate(year, month, day); // For consistency for future readers :) var today = new LocalDate(2012, 2, 3); Period period = Period.Between(birthday, today, YearMonth); Console.WriteLine("Birthday: {0}; Age: {1} years, {2} months", birthday, period.Years, period.Months); } } </code></pre> <p>Doing it with <em>just</em> .NET's <code>DateTime</code> support would be possible, but you'd have to do the arithmetic yourself, basically. And it almost certainly wouldn't be as clear. Not that I'm biased or anything :)</p>
38,012,493
0
<p>Try this editablegrid framework <a href="http://www.editablegrid.net/en/" rel="nofollow">http://www.editablegrid.net/en/</a></p>
39,571,599
0
<p>It looks like you want to identify if some places belong to specific chains or franchises.</p> <p>This is not possible in Places API, other than by detecting <em>likely</em> relation to chains based on the <code>"name"</code> and <code>"website"</code> fields. But if you'd like to reliable detect this kind of relation, consider <a href="http://code.google.com/p/gmaps-api-issues/issues/entry?template=Places%20API%20-%20Feature%20Request" rel="nofollow">filing a feature request for Places API</a> (I couldn't find one).</p>
5,453,814
0
Making part of the regex optional <p>Here is my regex:</p> <pre><code>/On.* \d{1,2}\/\d{1,2}\/\d{1,4} \d{1,2}:\d{1,2} (?:AM|PM),.*wrote:/ </code></pre> <p>to match:</p> <pre><code>On 3/14/11 2:55 PM, XXXXX XXXXXX wrote: </code></pre> <p>I need this Regex to also match:</p> <pre><code>On 25/03/2011, at 2:19 AM, XXXXX XXXXXXXX wrote: </code></pre> <p>So I tried this:</p> <pre><code>/On.* \d{1,2}\/\d{1,2}\/\d{1,4}(, at)? \d{1,2}:\d{1,2} (?:AM|PM),.*wrote:/ </code></pre> <p>But that breaks the other matches</p> <p>Am I making the (, at)? optional set right?</p> <p>Thanks</p>
5,976,853
0
how can I know if user is logged in <p>Im using simple mechanizm in which after login in my database there is new row inserted with userId and expiresDate columns. Everything would be ok but how can I know if user leaves website, closes browser and so on ?</p> <p>Secondly how can I make his sessionlonger if he is viewing different pages on the site. Should I all the time make updates on the database ?</p> <p>what are common aptterns ?</p> <p>It is im,portant for me because on the liveChat I need to know which users are online so that client can chat with them</p>
23,034,970
0
How to calculate False Accept and Reject Rates in pattern recognition <p>I am working on a vein pattern recognition project based on SURF algorithm and euclidean distance. I have completed my program to find the maximum and minimum distance between vein features and find a match exactly when there is an identical image. i.e max and min distance between two images is zero. In this case, how would I find my FAR and FRR. Will it be 0% or am I missing a big concept here?</p> <p>Even if there is a slight variation it wouldn't match in which case, I guess I need to have a threshold value to compare to. I have calculate the max and min distance between all combination of images with the same hand, with different hands. In this case, how do I computer the FAR and FRR. This is my first biometrics project and it would be helpful if I am directed to any resource that would help me in this. Thank you.</p> <p>Kindly help me out.</p>
32,280,137
0
<p>The parameters to <code>glfwOpenWindow</code> are specifying the desired values. However, it's entirely possible that your driver doesn't support the exact format you're asking for (24 bit color, 24 bit depth, no alpha, no stencil). GLFW will attempt to find the best match while meeting your minimums.</p> <p>In this case it's probably giving you the most standard format of RGBA color (32 bit) and a 24/8 bit depth/stencil buffer, or it could be creating a 32 bit depth buffer. You'd actually need to call <code>glfwGetWindowParam</code> to query the depth and stencil bits for the default framebuffer, and then build your renderbuffers to match that. </p>
16,231,007
0
<p>Use <a href="http://msdn.microsoft.com/en-us/library/system.string.trimend.aspx">string.TrimEnd</a> on your TextBox Text. </p> <pre><code>Participant.Text = participants.TrimEnd(','); </code></pre>
15,177,129
0
<p>you can use the passed View object in <strong>onCreateContextMenu</strong> to determine the owner of the menu and populate a menu accordingly.</p> <p>Your code should look something like this :</p> <pre><code>public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); switch (v.getId()) { case R.id.imageIconId: menu.setHeaderTitle(getString(R.string.option1)); menu.add(0, v.getId(), 0, getString(R.string.option2)); menu.add(0, v.getId(), 0, getString(R.string.options3)); break; case R.id.textViewid: // do whatever you want with the menu object. break; } } </code></pre>
40,579,363
0
<p>You can use <code>list = sorted(list, key=...)</code> or <code>list.sort(key=...)</code>. </p> <p>First method lets you use slicing to get/set only part of list - without changing first row.</p> <pre><code>import datetime table_of_list = [['name', 'email', 'address', 'details', 'date_last_contacted'], [u'Jane Doe', u'[email protected]', u'sillybilly', u'dodo', datetime.date(2016,11,1) ], [u'John Doe', u'[email protected]', u'123 house',u'random', datetime.date(2016,10,1) ] ] table_of_list[1:] = sorted(table_of_list[1:], key=lambda x: x[4]) print(table_of_list) </code></pre>
7,209,234
0
<p>Any object within a serialised object also has to be serialised, if you see what I mean?</p>
16,326,855
0
Rails / Kaminari - How to order a paginated array? <p>I'm having a problem <strong>ordering</strong> an array that I've successfully paginated with Kaminari.</p> <p>In my controller I have:</p> <pre><code>@things = @friend_things + @user_things @results = Kaminari.paginate_array(@things).page(params[:page]).per(20) </code></pre> <p>I want to have the final <code>@results</code> array ordered by <code>:created_at</code>, but have had no luck getting ordering to work with the generic array wrapper that Kaminari provides. Is there a way to set the order in the Kaminari wrapper? Otherwise what would be the best way? Thanks.</p>
34,738,226
0
asp.net 5 deploy to iis got a TaskAwait.ThrowForNonSuccess exception <p>When I run my application on vs,everything is ok ,but when i deploy my application to iis(when the application try to access data from database by entityframework7 ,it throw an TaskAwait.ThrowForNonSuccess exception.Is anyone can help me?</p>
27,891,575
0
Generating all lexicographical permutations without comparisons of elements <p>I came into the problem when I have a given sequence s=(a,b,c,d,e...) - sorted in non-decreasing order. My job is to develop an algorithm that is going to generate all possible permutations in lexicographical order - ending on the reversed s (highest in order).</p> <p>The trick is: I cannot compare any 2 element to each other. All operations must be done "automatically", regardless of elements values.</p>
9,277,937
0
<p>I think there is an error in your first document.ready</p> <pre><code>here : $(function() { </code></pre> <p>So the second document.ready </p> <pre><code>this one : $(document).ready(function() { </code></pre>
16,173,593
0
Where should Exceptions be put that are used by multiple projects? <p>I need to refactor a project with two data models into two separate projects. Both projects use the same Exceptions. Should I create a 3rd project only for these exceptions? Cloning sounds like a no-go.</p>
11,991,881
0
<p>Running the following command as documented in the <a href="http://code.google.com/p/dbdeploy/wiki/UsingTheMavenPlugin" rel="nofollow">Using Maven Plugin</a> page...</p> <pre><code>mvn help:describe -Dplugin=com.dbdeploy:maven-dbdeploy-plugin -Ddetail </code></pre> <p>we see the following goal, which helps generate the changelog</p> <pre><code>dbdeploy:change-script Description: Maven goal for creating a new timestamped dbdeploy change script. Implementation: com.dbdeploy.mojo.CreateChangeScriptMojo Language: java Available parameters: name (Default: new_change_script) Expression: ${dbdeploy.script.name} Name suffix for the file that will be created (e.g. add_email_to_user_table). scriptdirectory (Default: ${project.src.directory}/main/sql) Expression: ${dbdeploy.scriptdirectory} Directory where change scripts reside. </code></pre> <p>So I guess we would run this prior to the other goals like <code>db-scripts</code> and <code>update</code>.</p>
4,736,248
0
<p>Sluama - Your suggestion fixed it! Such an obvious answer. The " was terminating the Where clause string. I could have sworn I tried that, but I guess not. Becuase, I just happened to come back to this question and saw your answer and it works!</p> <pre><code>&lt;asp:EntityDataSource ID="EDSParts" runat="server" ConnectionString="name=TTEntities" DefaultContainerName="TTEntities" EnableFlattening="False" EntitySetName="Parts" OrderBy="it.ID DESC" Where ="(CASE WHEN (@PartNumber IS NOT NULL) THEN it.[Number] LIKE REPLACE(@PartNumber, '*', '%') ELSE it.[ID] IS NOT NULL END)"&gt; &lt;WhereParameters&gt; &lt;asp:ControlParameter Name="PartNumber" Type="String" ControlID="txtPartNumberQuery" PropertyName="Text" /&gt; &lt;/WhereParameters&gt; &lt;/asp:EntityDataSource&gt; </code></pre>
35,034,841
0
How to measure time with Matlab while led diodes is on using Arduino? <p>I need measure time while led diodes is on for each one with Matlab guide. In Arduino code its sending data to Matlab if diodes are on:</p> <p>if(digitalRead(ledC1)==HIGH) { Serial.println("a"); } </p> <p>if(digitalRead(ledC2)==HIGH) { Serial.println("b"); } </p> <p>With my Matlab code, it works only if one diode is on, but it is not working if two diodes are on in the same time and not measure for each one. How measure for both diodes?</p> <p>Matlab code:</p> <p>function pushbutton1_Callback(hObject, eventdata, handles)</p> <p>s=serial('COM7','BaudRate',9600);</p> <p>fopen(s);</p> <p>try</p> <pre><code> while true pause(1); </code></pre> <p>A = fscanf(s,'%s');</p> <p>B = fscanf(s,'%s');</p> <p>if strcmp(A,'a')==0 % frist led dioda</p> <pre><code> tic; </code></pre> <p>end</p> <pre><code> seconds1=toc; </code></pre> <p>elapsedTime1 = fix(mod(seconds1, [0, 3600, 60]) ./ [3600, 60, 1]);</p> <p>set(handles.text8,'String',elapsedTime1);</p> <p>if strcmp(B,'b')==0 % second led dioda</p> <pre><code> tic; </code></pre> <p>end</p> <pre><code> seconds2=toc; </code></pre> <p>elapsedTime2 = fix(mod(seconds2, [0, 3600, 60]) ./ [3600, 60, 1]);</p> <p>set(handles.text9,'String',elapsedTime2);</p> <p>end</p> <p>end</p> <p>catch err</p> <p>fclose(s);</p> <pre><code>clear all return; </code></pre> <p>end</p>
8,200,901
0
Design for long running ASP.net MVC web request <p>I'm aware of the model that involves a scheduled task runninng in the back ground which runs jobs registered with a web request but how about this for an idea that keeps everything within ASP.net...</p> <ol> <li><p>User uploads a CSV file with, perhaps, several thousand rows. The rows are persisted to the database. I think this would take maybe a minute or so which would be an acceptable wait.</p></li> <li><p>Request returns to the browser and then an automatic Ajax request would go back to the server and request, say, ten rows at a time and process them. (Each row requires a number of web service requests.)</p></li> <li><p>Ajax call returns, display is updated and then another automatic Ajax request goes back for more rows. This repeats until all rows are completed.</p></li> <li><p>If user leaves the web page, then they could return and restart the job.</p></li> </ol> <p>Any thoughts?</p> <p>Cheers, Ian.</p>
21,972,293
0
Data Type for Currency in Entity Framework <p>What data type should I use to hold currency values in Entity Framework 6 and what data type should I map it in SQL Server 2012?</p> <p>Thank You, Miguel</p>
27,520,469
0
iOS UITextField value without tapping on RETURN button <p>Is it possible to take UITextField value without tapping <em>RETURN</em> button?. If I type something in <strong><em>LOGIN UITextField</em></strong> and then tap on <strong><em>PASSWORD UITextField</em></strong>, it looks like LOGIN value is empty, however if I type something in LOGIN, and then tap RETURN everything's fine.</p> <p>Without tapping on RETURN <a href="http://gyazo.com/2ca0f263275fd65ae674233f34d90280" rel="nofollow">http://gyazo.com/2ca0f263275fd65ae674233f34d90280</a></p> <p>With tapping on RETURN <a href="http://gyazo.com/9ccc39ba7080b6b6344454ec757d3c0f" rel="nofollow">http://gyazo.com/9ccc39ba7080b6b6344454ec757d3c0f</a></p> <p>Here's my code:</p> <p><strong>TextInputTableViewCell.m</strong></p> <pre><code>@implementation TextInputTableViewCell -(void)configureWithDictionary:(NSMutableDictionary *)dictionary { self.cellInfoDictionary = dictionary; NSString *title = [dictionary objectForKey:@"title"]; NSString *imageName = [dictionary objectForKey:@"imageName"]; UIColor *color = [dictionary objectForKey:@"bgColor"]; BOOL secureTextEntry = [dictionary objectForKey:@"secure"]; self.myTextField.placeholder = title; self.myImageView.image = [UIImage imageNamed:imageName]; self.contentView.backgroundColor = color; self.myTextField.secureTextEntry = secureTextEntry; self.myTextField.delegate = self; } -(BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; if (textField.text) { [self.cellInfoDictionary setObject:textField.text forKey:@"value"]; } return NO; } @end </code></pre> <p><strong>LoginViewController.m</strong></p> <pre><code>@interface LoginViewController () &lt;UITableViewDataSource, UITableViewDelegate, NewRestHandlerDelegate&gt; @property (strong, nonatomic) IBOutlet UITableView *tableView; @property (strong, nonatomic) NSArray *datasource; @end static NSString *textInputCellIdentifier = @"textInputCellIdentifier"; static NSString *buttonCellIdentifier = @"buttonCellIdentifier"; @implementation LoginViewController { NSString *email; NSString *password; NewRestHandler *restHandler; } - (void)viewDidLoad { [super viewDidLoad]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; if ([defaults boolForKey:@"logged"]) [self performSegueWithIdentifier:@"Logged" sender:self]; [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TextInputTableViewCell class]) bundle:nil] forCellReuseIdentifier:textInputCellIdentifier]; [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ButtonTableViewCell class]) bundle:nil] forCellReuseIdentifier:buttonCellIdentifier]; restHandler = [[NewRestHandler alloc] init]; restHandler.delegate = self; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSDictionary *dictionary = [self.datasource objectAtIndex:indexPath.row]; NSString *cellIdentifier = [dictionary objectForKey:@"cellIdentifier"]; UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if ([cell respondsToSelector:@selector(configureWithDictionary:)]) { [cell performSelector:@selector(configureWithDictionary:) withObject:dictionary]; } return cell; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.datasource.count; } ... - (NSArray *)datasource { if (!_datasource) { NSMutableArray* datasource = [NSMutableArray arrayWithCapacity:5]; NSMutableDictionary* loginDictionary = @{@"cellIdentifier": textInputCellIdentifier, @"title": @"Login", @"imageName": @"edycja02.png", @"bgColor": [UIColor whiteColor], }.mutableCopy; NSMutableDictionary* passwordDictionary = @{@"cellIdentifier": textInputCellIdentifier, @"title": @"Password", @"imageName": @"edycja03.png", @"bgColor": [UIColor whiteColor], @"secure": @YES, }.mutableCopy; NSMutableDictionary* loginButtonDictionary = @{@"cellIdentifier": buttonCellIdentifier, @"title": @"Login", @"imageName": @"logowanie01.png", @"bgColor": [UIColor colorWithRed:88/255.0 green:88/255.0 blue:90/255.0 alpha:1], @"textColor": [UIColor whiteColor], }.mutableCopy; NSMutableDictionary* facebookLoginButtonDictionary = @{@"cellIdentifier": buttonCellIdentifier, @"title": @"Login with Facebook", @"imageName": @"logowanie02.png", @"bgColor": [UIColor colorWithRed:145/255.0 green:157/255.0 blue:190/255.0 alpha:1], @"textColor": [UIColor whiteColor], }.mutableCopy; NSMutableDictionary* signUpButtonDictionary = @{@"cellIdentifier": buttonCellIdentifier, @"title": @"Sign up", @"imageName": @"logowanie03.png", @"bgColor": [UIColor colorWithRed:209/255.0 green:210/255.0 blue:212/255.0 alpha:1], @"textColor": [UIColor whiteColor], }.mutableCopy; [datasource addObject:loginDictionary]; [datasource addObject:passwordDictionary]; [datasource addObject:loginButtonDictionary]; [datasource addObject:facebookLoginButtonDictionary]; [datasource addObject:signUpButtonDictionary]; _datasource = datasource; } return _datasource; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row == 2) { email = [self.datasource[0] valueForKey:@"value"]; password = [self.datasource[1] valueForKey:@"value"]; NSLog(@"Email: %@", email); NSLog(@"Password: %@", password); ... </code></pre>
37,573,829
0
<p>Easiest solution is</p> <pre><code>/%{DATA:col1}/%{DATA:col2}/%{DATA:index}/%{DATA:server}\.%{GREEDYDATA:end} </code></pre> <p>you can remove the names <code>col1</code>, <code>col2</code>, and <code>end</code> to drop those captures.</p> <p>This pattern relies on there always being the same number of parts in your URI. If there are a variable number you could use something like this.</p> <pre><code>(?:/%{USER})*/%{DATA:index}/%{DATA:server}\.%{GREEDYDATA:end} </code></pre> <p>I made and tested these using <a href="http://grokconstructor.appspot.com/do/match" rel="nofollow">the grok constructor</a></p> <hr> <p>Using this pattern:</p> <pre><code>filter { grok { match =&gt; { "message" =&gt; &lt;message-pattern&gt; } } grok { match =&gt; { "log_path" =&gt; "(?:/%{USER})*/%{DATA:index}/%{DATA:server}\.%{GREEDYDATA}" } } } </code></pre> <p>Where <code>"log_path"</code> is the name of the field containing the log path after you do your normal message parsing.</p>
1,715,943
0
workaround: site is www.site.com code incl. document.domain='site.com' <p>A customer site that I cannot change has the line 'document.domain = "site.com"; while the site is at www.site.com.</p> <p>The effect is that FB connect window login gets stuck after submitting username+password.</p> <p>Firebug shows its in infinite loop inside dispatchmessage function, which gives perpetual exception:</p> <pre><code>Error: Permission denied for &lt;http://www.site.com&gt; to get propertyl Window.FB from &lt;http://site.com&gt; </code></pre> <p>Any idea how to work around this? I prefer not to ask the customer to remove the document.domain='site.com'</p>
25,708,029
0
Laravel 4: How to protect group routes admins and users? <p>Good day! Please tell me how to split the routes users and administrators? To authorize the user got to your home page and could move only to the right routes and the admin came on your web page and could see only their routes. My file routes.php</p> <pre><code>Route::get('/', array( 'as' =&gt; 'home', 'uses' =&gt; 'HomeController@home' )); Route::group(array('before' =&gt; 'auth'), function(){ Route::group(array('before' =&gt; 'csrf'), function(){ Route::post('/account/change-password', array( 'as' =&gt; 'account-change-password-post', 'uses' =&gt; 'AccountController@postChangePassword' )); }); Route::get('/account/change-password', array( 'as' =&gt; 'account-change-password', 'uses' =&gt; 'AccountController@getChangePassword' )); Route::get('/user/{username}', array( 'as' =&gt; 'profile-user', 'uses' =&gt; 'ProfileController@user' )); Route::get('/account/sign-out', array( 'as' =&gt; 'account-sign-out', 'uses' =&gt; 'AccountController@getSignOut' )); }); Route::group(array('before' =&gt; 'admin'), function(){ Route::get('/dashboard', array( 'as' =&gt; 'dashboard', 'uses' =&gt; 'TiketsController@dashboard' )); Route::get('/tiket-new', array( 'as' =&gt; 'tiket-new', 'uses' =&gt; 'TiketsController@tiketNew' )); Route::get('/tiket-work', array( 'as' =&gt; 'tiket-work', 'uses' =&gt; 'TiketsController@tiketWork' )); Route::get('/tiket-complete', array( 'as' =&gt; 'tiket-complete', 'uses' =&gt; 'TiketsController@tiketComplete' )); Route::get('/tiket-arhive', array( 'as' =&gt; 'tiket-arhive', 'uses' =&gt; 'TiketsController@tiketArhive' )); }); Route::group(array('before' =&gt; 'user'), function(){ Route::get('/user-dashboard', array( 'as' =&gt; 'user-dashboard', 'uses' =&gt; 'TiketsController@userDashboard' )); }); </code></pre> <p>My AccountController.php</p> <pre><code>public function postSignIn(){ $validator = Validator::make(Input::all(), array( 'email' =&gt; 'required|email', 'password' =&gt; 'required' )); if($validator-&gt;fails()){ return Redirect::route('account-sign-in') -&gt;withErrors($validator) -&gt;withInput(); } else { $remember = (Input::has('remember')) ? true : false; $auth = Auth::attempt(array( 'email' =&gt; Input::get('email'), 'password' =&gt; Input::get('password'), 'active' =&gt; 1 ), $remember); if($auth){ if (Auth::user()-&gt;role==5) { return Redirect::intended('/dashboard'); } if (Auth::user()-&gt;role==1) { return Redirect::intended('/user-dashboard'); } } else { return Redirect::route('account-sign-in') -&gt;with('global', 'Error'); } } </code></pre> <p>Unfortunately, when such routes admins and users can see the pages of each other. Please tell me as much detail as possible, how to distinguish between different groups of users?</p>
15,523,470
0
<p>This depends on how your <code>struct</code> is defined, whether or not you want your output to be human-readable, and whether or not the output file is meant to be read on a different architecture. </p> <p>The <code>fwrite</code> solution that others have given will write the <em>binary representation</em> of the struct to the output file. For example, given the code below:</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { struct foo { int x; char name1[10]; char name2[10]; } items[] = {{1,"one","ONE"}, {2,"two","TWO"}}; FILE *output = fopen("binio.dat", "w"); fwrite( items, sizeof items, 1, output ); fclose( output ); return 0; } </code></pre> <p>if I display the contents of <code>binio.dat</code> to the console, I get the following:</p> <pre> john@marvin:~/Development/Prototypes/C/binio$ cat binio.dat oneONEtwoTWOjohn@marvin:~/Development/Prototypes/C/binio$ john@marvin:~/Development/Prototypes/C/binio$ od -c binio.dat 0000000 001 \0 \0 \0 o n e \0 \0 \0 \0 \0 \0 \0 O N 0000020 E \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 0000040 \0 \0 \0 \0 002 \0 \0 \0 t w o \0 \0 \0 \0 \0 0000060 \0 \0 T W O \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 0000100 \0 \0 \0 \0 \0 \0 \0 \0 0000110 </pre> <p>The integer values show up as garbage (not reproduced above) because they've been stored as the byte sequences 01, 00, 00, 00 and 02, 00, 00, 00 (x86 is little-endian), which are not printable characters. Also note that all 10 characters of <code>name1</code> and all 20 characters of <code>name2</code> are written to the file, which may or may not be what you want.</p> <p>The situation gets even more complicated if your struct contains pointers, because what gets stored to the file is the pointer value, not the thing being pointed to:</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { struct foo { int x; char *name1; char *name2; } items[] = {{1,"one","ONE"}, {2,"two","TWO"}}; FILE *output = fopen("binio.dat", "w"); fwrite( items, sizeof items, 1, output ); fclose( output ); return 0; } </code></pre> <p>This time I get</p> <pre> john@marvin:~/Development/Prototypes/C/binio$ cat binio.dat οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½john@marvin:~/Development/Prototypes/C/binio$ john@marvin:~/Development/Prototypes/C/binio$ od -c binio.dat 0000000 001 \0 \0 \0 260 205 004 \b 264 205 004 \b 002 \0 \0 \0 0000020 270 205 004 \b 274 205 004 \b 0000030 </pre> <p>Note that none of the strings appear in the file at all; if you read this file in with a different program, all it will see are (most likely) invalid addresses. </p> <p>If you want your output to be human-readable <em>and</em> you want to be able to read those values in on a different architecture, you almost have to go with formatted output, meaning you have to write each member separately:</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { struct foo { int x; char *name1; char *name2; } items[] = {{1,"one","ONE"}, {2,"two","TWO"}}; FILE *output = fopen("binio.dat", "w"); int i; for (i = 0; i &lt; sizeof items / sizeof items[0]; i++) { fprintf(output, "%d %s %s\n", items[i].x, items[i].name1, items[i].name2); } fclose( output ); return 0; } </code></pre> <pre> john@marvin:~/Development/Prototypes/C/binio$ cat binio.dat 1 one ONE 2 two TWO </pre> <p>You can certainly wrap that operation in a function of your own, something like</p> <pre><code>int printFoo( FILE *output, const struct foo item ) { return fprintf( output, "%d %s %s\n", item.x, item.name1, item.name2); } </code></pre> <p>but in the end, that's about as simple as it gets.</p> <p>The <code>fwrite</code> solution works great if you're not concerned about readability and portability, but you still have to be careful if you have any pointer members within the struct. </p>
33,714,636
0
<p>Editing the raven context is currently quite hard as the error reporters are not registered anywhere, so you cannot say "hey give me the error reporters" and look for the Sentry one in that list.</p> <p>Currently the only way is to register an <code>after_config</code> hook, gather the Raven Client during the configuration process and store it somewhere accessible. </p> <p>Changing backlash middlewares to store the reporters somewhere accessible should be fairly easy (e.g. the environ) but currently it's not available.</p> <p>By the way here is a short example of the <code>after_config</code> solution that should make the client available as <code>tg.app_globals.sentry_clients</code>, copy it in your <code>app_cfg.py</code> and it should do what you expect (didn't have time to try it, sorry if you find errors), then you can get the context from the client whenever is needed:</p> <pre><code>def gather_sentry_client(app): from backlash import TraceErrorsMiddleware, TraceSlowRequestsMiddleware try: trace_errors_app = app.app.application except: return app if not isinstance(trace_errors_app, TraceErrorsMiddleware): return app trace_errors_client = None for reporter in trace_errors_app.reporters: if hasattr(reporter, 'client'): trace_errors_client = reporter.client slow_reqs_app = trace_errors_app.app slow_reqs_client = None if isinstance(slow_reqs_app, TraceSlowRequestsMiddleware): for reporter in slow_reqs_app.reporters: if hasattr(reporter, 'client'): slow_reqs_client = reporter.client from tg import config app_globals = config['tg.app_globals'] app_globals.sentry_clients = { 'errors': trace_errors_client, 'slowreqs': slow_reqs_client } return app from tg import hooks hooks.register('after_config', gather_sentry_client) </code></pre>
20,193,399
0
<p>Silly me! As i was told by user seutje in the #jquery irc.freenode channel, I should attach the jquery-ui methods <code>onRender</code> instead of initialization</p> <pre><code> initialize: function(){ this.setCssStyle(); }, onRender: function(){ this.$el.draggable({ containment: 'parent' }); this.$el.resizable(); } </code></pre> <p>Everything works now, but I would like feedback whether this is optimal. Considering that I'm attaching methods <code>onRender</code>, during resize the <code>ItemView</code> gets re-rendered, therefore while <code>onRender</code> gets called whenever I resize the item and as a result re-attaches .draggable and .resizable?</p>
39,402,942
0
To print prime numbers between m and n when m and n are quite large in the range 10^10 using sieve of eratosthenes <p>My code is:</p> <pre><code>#include &lt;bits/stdc++.h&gt; #define s 100001 using namespace std; int main() { long long arr[s],i,j,t,m,n; for(i=0;i&lt;s;i++) arr[i] = 1; arr[0] = 0; arr[1] = 0; for(i=2;i&lt;sqrt(s);i++) { if(arr[i] == 1) { for(j=2;i*j&lt;s;j++) arr[i*j] = 0; } } cin &gt;&gt; t; while(t--) { cin &gt;&gt; m &gt;&gt; n; if(n&lt;s) { for(i=m;i&lt;=n;i++) { if(arr[i] == 1) cout &lt;&lt; i &lt;&lt; endl; } } } return 0; } </code></pre> <p>This code is showing run time error for larger input of m and n as the array size is just 10^5 long. When I was making the array of 10^10 there was a compilation error and it is showing this much bigger array is not possible.</p>
15,099,949
0
<p>Something to get you stared, adapt to your own needs:</p> <p>Lets create some files:</p> <pre><code>$ touch a-b-2013-02-12-16-38-54-{a..f}.png $ ls a-b-2013-02-12-16-38-54-a.png a-b-2013-02-12-16-38-54-c.png a-b-2013-02-12-16-38-54-e.png f.py a-b-2013-02-12-16-38-54-b.png a-b-2013-02-12-16-38-54-d.png a-b-2013-02-12-16-38-54-f.png </code></pre> <p>Some python</p> <pre><code>#!/usr/bin/env python import glob, os files = glob.glob('*.png') for f in files: # get the character before the dot d = f.split('-')[-1][0] #create directory try: os.mkdir(d) except OSError as e: print 'unable to creade dir', d, e #move file try: os.rename(f, os.path.join(d, f)) except OSError as e: print 'unable to move file', f, e </code></pre> <p>Lets run it</p> <pre><code>$ ./f.py $ ls -R .: a b c d e f f.py ./a: a-b-2013-02-12-16-38-54-a.png ./b: a-b-2013-02-12-16-38-54-b.png ./c: a-b-2013-02-12-16-38-54-c.png ./d: a-b-2013-02-12-16-38-54-d.png ./e: a-b-2013-02-12-16-38-54-e.png ./f: a-b-2013-02-12-16-38-54-f.png </code></pre>
4,282,486
0
How to track more than one remote with a given branch using Git? <p>The situation is this:</p> <p>I have more than one remote repository - for reference, lets say that one is the "alpha" repository, and we have recently set up a new "beta" repository, which some users have migrated to.</p> <p>Both repositories have a "master" branch.</p> <p>How do I set up my local master such that it will attempt to automatically push and pull to and from <em>both</em> the alpha <em>and</em> beta repositories, without manually specifying the remote I want to use each time?</p> <p>I should elaborate that I don't want to set up two local branches 'master-alpha' and 'master-beta', I want the <em>same</em> local branch to track both remotes.</p>
33,082,074
0
<p>Your code is neat but the time complexity is O(n^2), which can be reduced to O(n).</p> <pre><code>data = {(1,2,1,5),(1,2,7,2),(1,5,4,7),(4,7,7,5)} result = dict() for item in data: key = (item[0],item[1]) value = result.setdefault(key,[]) value.append((item[2],item[3])) result[key] = value print result </code></pre> <p>In my opinion, using a for loop can make codes more comprehensive</p>
31,539,680
0
<p>instead of </p> <pre><code>if (currentSlide == 5) </code></pre> <p>you can add an incremented class on each of your slides, and check what is inside in this if. the html will looks like this: </p> <pre><code> &lt;div class="slide1"&gt;&lt;img src="http://placehold.it/900x500"&gt;&lt;/div&gt; &lt;div class="slide2"&gt;&lt;img src="http://placehold.it/900x500"&gt;&lt;/div&gt; &lt;div class="slide3"&gt;&lt;img src="http://placehold.it/900x500"&gt;&lt;/div&gt; &lt;div class="slide4"&gt;&lt;img src="http://placehold.it/900x500"&gt;&lt;/div&gt; &lt;div class="slide5"&gt;&lt;img src="http://placehold.it/900x500"&gt;&lt;/div&gt; &lt;div class="slide6" id="slide-video"&gt; &lt;video width="900px" height="500px" class="theVideo"&gt; &lt;source src="http://vjs.zencdn.net/v/oceans.mp4" /&gt; &lt;/video&gt; </code></pre> <p>for example you ll do :</p> <pre><code> $('.sliderMain').on('afterChange', function(event, slick, currentSlide){ if ($('.slide'+currentSlide+ ' video').length != 0){ $('.sliderMain').slick('slickPause'); theVideo.play(); } }); </code></pre> <p>You ll probably then know if you have a node video in your current slide.</p> <p>hope this will help</p>
37,300,137
0
Spring: Testing view-controllers created with ViewControllerRegistry.addViewController() <p>This is my first time carrying out junit testing so forgive me if this is a stupid question. The class from my Spring web application which I wish to test is below. The class extends WebMcvConfigurerAdapter to add view controllers.</p> <p>I just want to test if each of the view controllers maps to the correct view. In every tutorial I've looked at, the test is carried out for a controller which has it's own separate class. it wouldn't make sense for the controllers below to have their own class as there is no logic involved in them. Can anyone direct me for the way i should approach this or give sample code? Do controllers like these which only link to a view even require testing?</p> <pre><code>@Configuration public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("greeting"); registry.addViewController("/portal").setViewName("portal"); registry.addViewController("/login").setViewName("login"); } </code></pre> <p>}</p>
34,462,089
1
Instagram API docs invalid JSON error <p>I keep getting this error when I tried the examples in the <a href="https://github.com/Instagram/python-instagram#using-an-access-token" rel="nofollow">python-instagram</a> documentation:</p> <pre><code>from instagram.client import InstagramAPI access_token = "YOUR_ACCESS_TOKEN" client_secret = "YOUR_CLIENT_SECRET" api = InstagramAPI(access_token=access_token, client_secret=client_secret) recent_media, next_ = api.user_recent_media(user_id="userid", count=10) for media in recent_media: print media.caption.text </code></pre> <p>Error:</p> <pre><code>Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/Users/bli1/Development/Django/CL/cherngloong/cherngloong/lib/python2.7/site-packages/instagram/bind.py", line 197, in _call return method.execute() File "/Users/bli1/Development/Django/CL/cherngloong/cherngloong/lib/python2.7/site-packages/instagram/bind.py", line 189, in execute content, next = self._do_api_request(url, method, body, headers) File "/Users/bli1/Development/Django/CL/cherngloong/cherngloong/lib/python2.7/site-packages/instagram/bind.py", line 131, in _do_api_request raise InstagramClientError('Unable to parse response, not valid JSON.', status_code=response['status']) InstagramClientError: (404) Unable to parse response, not valid JSON. </code></pre> <p>I'm not sure what is causing this error. I got my <code>access_token</code> and filled in all the parameters</p> <p>I get the same error when I try other parts of the documentation:</p> <pre><code>api = InstagramAPI(client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET') popular_media = api.media_popular(count=20) for media in popular_media: print media.images['standard_resolution'].url </code></pre>
38,510,303
0
Applying velocity to a SKSpriteNode subclass & trouble with Expected Declaration Error <p>I'm currently working on my first iPhone game and I have a SKSpriteNode subclass <code>Alien</code> (which is also an abstract class) that will later be inherited by a class <code>normAlien</code>. Even with Apple's docs, I've been having a lot of trouble figuring out class initialization and inheritance in Swift. Here is the code for both classes:</p> <pre><code>//Generic alien type: a blue-print of sorts class Alien:SKSpriteNode{ static func normalizeVector(vector:CGVector) -&gt; CGVector{ let len = sqrt(vector.dx * vector.dx + vector.dy * vector.dy) return CGVector(dx:vector.dx / len, dy:vector.dy / len) } func motion(velocity:CGVector, multiplier:CGFloat){ //Alien.physicsBody?.velocity.dx = velocity.dx * multiplier //Why no work? self.physicsBody?.velocity.dx = velocity.dx * multiplier self.physicsBody?.velocity.dy = velocity.dy * multiplier } let velocityVector:CGVector let startPos:CGPoint init(texture:SKTexture, startPosition startPos:CGPoint,moveSpeed: CGFloat,velocityVector:CGVector){ self.velocityVector = Alien.normalizeVector(velocityVector) self.startPos = startPos //Makes sure the SKSpriteNode is initialized before modifying its properties super.init(texture: texture, color: UIColor.clearColor(), size: texture.size()) //PhysicsBody is a property of super so super.init must be called first (init SKSpriteNode) self.physicsBody? = SKPhysicsBody(circleOfRadius: self.size.width/2) self.physicsBody?.dynamic = true self.physicsBody?.categoryBitMask = PhysicsCategory.Alien //physicsBody?. is optional chaining? self.physicsBody?.collisionBitMask = 0 //Do I need this? or jsut use in laser class self.physicsBody?.contactTestBitMask = PhysicsCategory.Laser self.physicsBody?.usesPreciseCollisionDetection = true //Motion self.physicsBody?.velocity.dx = velocityVector.dx * moveSpeed self.physicsBody?.velocity.dy = velocityVector.dy * moveSpeed //self.velocityVector = normalizeVector(velocityVector) self.position = startPos } //Alien.motion(self.velocityVector, moveSpeed) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } </code></pre> <p>As well as:</p> <pre><code>class normAlien:Alien{ static let alienImage = SKTexture(imageNamed:"Sprites/alien.png") //alienImage.setScale(0.2) init(startPos:CGPoint,speed: CGFloat){ super.init(texture:normAlien.alienImage, startPosition: startPos, moveSpeed:speed,velocityVector:CGVector(dx: 1,dy: 0)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } </code></pre> <p>I have a function: </p> <pre><code>func buildAlien(){ let aAlien = normAlien(startPos:CGPoint(x:0,y:size.height/2), speed:100) addChild(aAlien) } </code></pre> <p>that that instantiates <code>normAlien</code> within <code>didMoveToView</code> (This function is just called within a <code>SKAction.repeatActionForever</code>). For some reason each sprite created fails to move. I'm confused because they do move if I use a <code>SKAction.moveTo</code> so I must not understand something about applying velocity. </p> <p>On top of this, I'm confused as to why I receive the error: <code>Expected declaration</code>when I attempt to manipulate the <code>normAliens</code> texture with <code>alienImage.setScale(0.2)</code> and also when I try to call an internal method on the class: <code>Alien.motion(self.velocityVector, moveSpeed)</code>? I would think that calling this method inside the class would cause every instance I make to have it called- making them potentially move. </p> <p>Any help would be really appreciated.</p>
19,645,106
0
<p>For "6 choose 3, with replacement", you can use <a href="http://www.jsoftware.com/docs/help701/dictionary/d520.htm" rel="nofollow">catalog <code>{</code></a>:</p> <pre><code>{3#&lt;i.6 β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚0 0 0β”‚0 0 1β”‚0 0 2β”‚0 0 3β”‚0 0 4β”‚0 0 5β”‚ β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ β”‚0 1 0β”‚0 1 1β”‚0 1 2β”‚0 1 3β”‚0 1 4β”‚0 1 5β”‚ β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ ... </code></pre> <p>You can take the reverse as the index of the above matrix (unraveled), feg:</p> <pre><code>(0 0 0) I.~ &gt;,{3#&lt;i.6 0 (0 1 0) I.~ &gt;,{3#&lt;i.6 6 (5 5 5) I.~ &gt;,{3#&lt;i.6 215 (4 5 1) I.~ &gt;,{3#&lt;i.6 175 175 { &gt;,{3#&lt;i.6 4 5 1 </code></pre> <p>There are some relevant essays on combinations on jsoftware.com: <a href="http://www.jsoftware.com/jwiki/Essays/Combination%20Index" rel="nofollow">Combination Index</a>, <a href="http://www.jsoftware.com/jwiki/Essays/Combinations" rel="nofollow">Combinations</a> and others.</p>
7,870,094
0
Change color scheme on komodo edit <p>Hi this is a very noob question but i am trying to change the color scheme on komodo edit, version 6. I am running windows 7. I put the .ksf file in the /schemes folder, now what?</p>
18,051,290
0
Method Hibernate.createBlob() is deprecated from Hibernate 4.0.1 and moved to Hibernate.getLobCreator(Session session).createBlob() <p>Method <code>Hibernate.createBlob()</code> is deprecated from <strong>Hibernate 4.0.1</strong> and moved to <code>Hibernate.getLobCreator(Session session).createBlob()</code>. Any solution what should I pass inside method <code>getLobCreator(Session session)</code>, i.e in place of Session, Or any other solution showing how to retrieve and save an image into DB using Spring and Hibernate.</p>
27,472,769
0
Generating a Unique ID by using Rand() <p>Trying to create a ajax private chat. But can't seem to generate a unique ID that hasn't been used by another user.</p> <pre><code> $genid = rand(1,999999999999); foreach($genid as &amp;$rand){ $q = mysql_query("SELECT ".$q_pchat." FROM users WHERE pchat_id1='".$rand."'"); $r = mysql_num_rows($q); if($r == 0){ $chatid = $rand; break; } } </code></pre> <p>Get an internal server error 500. I think it's cause its an infinite loop.</p>
28,872,472
0
<p>What you need to do inside your stored procedure is split the comma delimited list of numbers into a list of single values in rows. Once you have this you can use <code>WHERE myCol IN(SELECT v FROM @r)</code>, or use an INNER JOIN instead of IN. One point you might have to watch for is that you have leading zeros - if you want to keep those you will need to use strings instead of integers.</p> <p>There are lots of articles around on the subject of splitting delimited values into rows, you could start <a href="http://stackoverflow.com/questions/2647/how-do-i-split-a-string-so-i-can-access-item-x">here</a>.</p>
38,396,949
0
<p>You can see there are comments in aapt_rules.txt. Beside each kept class there are corresponding layout files that referenced this class. Like that:</p> <pre><code># view res/layout/abc_list_menu_item_layout.xml #generated:17 # view res/layout/abc_popup_menu_item_layout.xml #generated:17 -keep class android.support.v7.internal.view.menu.ListMenuItemView { &lt;init&gt;(...); } </code></pre> <p>If you remove the layout file from build process this line will desappear and class will not be kept. The class will be shrinked if it's not actually used somewhere.</p> <p>So how can we remove layout file from appcompat library? I can see few options, none of them is perfect but they work. </p> <ol> <li><p>You can just remove file from sdk\extras\android\m2repository\com\android\support\appcompat-v7\version\appcompat-v7-version.aar. Enough for testing, bad for production because the same file may be used in some other projects. I tried and it works.</p></li> <li><p>Put fake file with the same name into your project. Name conflict will happen. Build process will prefer your fake file because project files have higher priority. This way file from appcompat will be ignored. I tried and it works.</p></li> <li><p>Probably you can make some fancy gradle script that removes unwanted files during the build process. I haven't tried that.</p></li> </ol> <p>(shrinkResources option doesn't help because aapt_rules.txt is generated BEFORE shrinkResources is actually involved.)</p> <p>I hope somebody will suggest a better way to do that</p> <p>After doing that all unwanted lines were gone from aapt_rules.txt. But it saved me about 100 KB from the final apk size. So not big deal for me. But in your case results may be different.</p>
20,296,286
0
<p>I don't claim to fully understand the <em>why</em> here, but as best I can tell, this is what's going on.</p> <p><code>summary.default</code> actually calls <code>oldClass</code> rather than <code>class</code>. <em>Why</em> I'm not sure, although I'm sure there's a good reason. </p> <p>Somewhat cryptically in <code>?class</code> we find the following passages:</p> <blockquote> <p>Many R objects have a class attribute, a character vector giving the names of the classes from which the object inherits. <strong>If the object does not have a class attribute, it has an implicit class, "matrix", "array" or the result of mode(x) (except that integer vectors have implicit class "integer").</strong> (Functions oldClass and oldClass&lt;- get and set the attribute, which can also be done directly.)</p> </blockquote> <p>So what's going on here is that <code>class</code> returns the <em>implicit</em> class (numeric). Note that <code>attr(a$alpha,"class")</code> returns <code>NULL</code>. Since the attribute doesn't exists, <code>oldClass</code> faithfully returns <code>NULL</code>.</p> <p>As for the differences between mode, type and class, the first two are related, the third is sort of a separate idea. Mode and type are (I think) actually fairly well explained in the documentation. <code>mode</code> tells you the storage mode of an object, but it is relying on the result of <code>typeof</code>, so they are (mostly) the same. Or connected, at least. But the different values that <code>typeof</code> returns are simply collapsed down to a smaller subset.</p>
20,710,984
0
<p>You need to also specify the locations that can use it. For example, in /etc/httpd/conf/httpd.conf you should see something like:</p> <pre><code>&lt;Directory "/var/www/html"&gt; ...lots of text... &lt;/Directory&gt; </code></pre> <p>Make sure is has:</p> <pre><code>&lt;Directory "/var/www/html"&gt; AllowOverride All &lt;/Directory&gt; </code></pre>
4,134,999
0
<p>Typing six file names, or using the declarative style with #pragma comment(lib, "foo.lib") is small potatoes compared to the work you'll have to do to turn this into a DLL or COM server.</p> <p>The distribution is heavily biased towards using this as a static link library. There are only spotty declarations available to turn this into a DLL with __declspec(dllexport). They exist only in the 3rd party dependencies. All using different #defines of course, you'll by typing a bunch of names in the preprocessor definitions for the projects. </p> <p>Furthermore, you'll have a hard time actually getting this DLL loaded at runtime since you are using it in a COM server. The search path for DLLs will be the client app's when COM creates your control instance, not likely to be anywhere near close to the place you deployed the DLL.</p> <p>Making it a COM server is a <em>lot</em> of work, you'll have to write all the interface glue yourself. Again, nothing already in the source code that helps with this at all.</p>
17,879,030
0
<p>Your JSON is invalid or your server responding with invalid JSON.</p> <p>It should be like this</p> <pre><code>{ "name":"rezepte", "id":"1", "name":null, "alter":"Ab 6.Monat", "kategorie":null, "tageszeit":"Mittags", "portionen":"1 baby- und 1 Erwachsenenportion", "bild":"\u0000\u0000\u0000\u0000\u0000", "vorrat":"2", "zubereitungszeit":"45", "zubereitung0":null, "zubereitung1":null, "zubereitung2":null, "info":null } </code></pre>