pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
13,305,111 | 0 | <p>Try to include the JQuery js before your custom Js file on html: </p> <pre><code><script src="../../Scripts/jquery-1.8.2.min.js" type="text/javascript" ></script> <script src="../../Scripts/___your js___ .js" type="text/javascript"></script> </code></pre> |
35,019,825 | 0 | error while converting svg to jpg file in eclipse using java <p>I am trying to convert an svg string into jpg file using batik in JAVA. I am able to do that successfully in netbeans IDE 8.0.2. But when I use the same code in eclipse Mars Release (4.5.0), it throws error and creates jpg file with 0byte size. Can someone please help what's the problem here.</p> <p>I have stored this SVG string in image.txt file. And I am reading this file and storing it in string in the code.</p> <p>The input svg string is:</p> <pre><code><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="v-2" width="1200px" height="1200px"><g id="v-3" class="viewport" transform="scale(1,1)"><g id="j_1" model-id="202c3451-5c59-4543-81a9-0fdbedebc2ca" class="element basic Rect" fill="#ffffff" stroke="none" transform="translate(186,36)"><g class="rotatable" id="v-5" transform="rotate(0,60,15)"><g class="scalable" id="v-6" transform="scale(1.2,0.5)"><rect id="v-7" fill="#00FFFF" stroke="#000000" width="100" height="60"/></g><text id="v-8" y="0.8em" display="null" xml:space="preserve" fill="#000000" font-size="14" text-anchor="middle" font-family="Arial, helvetica, sans-serif" transform="translate(60,7)"><tspan dy="0em" x="0" id="v-10" class="v-line">e1</tspan></text></g></g><g id="j_2" model-id="1f786afb-0a69-4a84-a737-cec94aede7c2" class="element basic Ellipse" fill="#ffffff" stroke="none" transform="translate(381,207)"><g class="rotatable" id="v-11" transform="rotate(0,60,15)"><g class="scalable" id="v-12" transform="scale(2,0.75)"><ellipse id="v-13" fill="#FFC299" stroke="#000000" rx="30" ry="20" cx="30" cy="20"/></g><text id="v-14" y="0.8em" display="null" xml:space="preserve" font-size="14" text-anchor="middle" fill="#000000" font-family="Arial, helvetica, sans-serif" transform="translate(60,7)"><tspan dy="0em" x="0" id="v-16" class="v-line">c1</tspan></text></g></g><g id="j_3" model-id="cf6f4dfa-a4ed-4f65-911b-83de353c6755" class="link"><path class="connection" stroke="black" id="v-17" d="M 416 200 263 66"/><path class="marker-source" fill="black" stroke="black" id="v-18" d="M 10 0 L 0 5 L 10 10 z" transform="translate(420.70581560773115,210.7614383498162) scale(1,1) rotate(-138.7888946533203)"/><path class="marker-target" fill="black" stroke="black" id="v-19" transform="translate(263,66) scale(1,1) rotate(41.21112060546878)"/><path class="connection-wrap" id="v-20" d="M 416 200 263 66"/><g class="labels" id="v-21"><g class="label" id="v-29" label-idx="0" transform="translate(339.5, 133)"><rect fill="white" rx="3" ry="3" x="-42.21875" y="-8.796875" width="84.4375" height="16"/><text text-anchor="middle" font-size="14" id="v-30" y="0.8em" display="null" xml:space="preserve" transform="translate(0,-8)"><tspan dy="0em" x="0" id="v-31" class="v-line">hasConstraint</tspan></text></g></g><g class="marker-vertices" id="v-22"/><g class="marker-arrowheads" id="v-23"><g class="marker-arrowhead-group marker-arrowhead-group-source" id="v-26" transform="translate(415.4351510976791,216.77972750249086) scale(1,1) rotate(-138.7888946533203)"><path class="marker-arrowhead" end="source" d="M 26 0 L 0 13 L 26 26 z"/></g><g class="marker-arrowhead-group marker-arrowhead-group-target" id="v-27" transform="translate(271.56485378778143,56.22026454457441) scale(1,1) rotate(41.21112060546878)"><path class="marker-arrowhead" end="target" d="M 26 0 L 0 13 L 26 26 z"/></g></g><g class="link-tools" id="v-24"><g class="link-tool" id="v-25" transform="translate(385.90911865234375, 173.64590454101562) "><g class="tool-remove" event="remove"><circle r="11"/><path transform="scale(.8) translate(-16, -16)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z"/><title>Remove link.</title></g><g class="tool-options" event="link:options"><circle r="11" transform="translate(25)"/><path fill="white" transform="scale(.55) translate(29, -16)" d="M31.229,17.736c0.064-0.571,0.104-1.148,0.104-1.736s-0.04-1.166-0.104-1.737l-4.377-1.557c-0.218-0.716-0.504-1.401-0.851-2.05l1.993-4.192c-0.725-0.91-1.549-1.734-2.458-2.459l-4.193,1.994c-0.647-0.347-1.334-0.632-2.049-0.849l-1.558-4.378C17.165,0.708,16.588,0.667,16,0.667s-1.166,0.041-1.737,0.105L12.707,5.15c-0.716,0.217-1.401,0.502-2.05,0.849L6.464,4.005C5.554,4.73,4.73,5.554,4.005,6.464l1.994,4.192c-0.347,0.648-0.632,1.334-0.849,2.05l-4.378,1.557C0.708,14.834,0.667,15.412,0.667,16s0.041,1.165,0.105,1.736l4.378,1.558c0.217,0.715,0.502,1.401,0.849,2.049l-1.994,4.193c0.725,0.909,1.549,1.733,2.459,2.458l4.192-1.993c0.648,0.347,1.334,0.633,2.05,0.851l1.557,4.377c0.571,0.064,1.148,0.104,1.737,0.104c0.588,0,1.165-0.04,1.736-0.104l1.558-4.377c0.715-0.218,1.399-0.504,2.049-0.851l4.193,1.993c0.909-0.725,1.733-1.549,2.458-2.458l-1.993-4.193c0.347-0.647,0.633-1.334,0.851-2.049L31.229,17.736zM16,20.871c-2.69,0-4.872-2.182-4.872-4.871c0-2.69,2.182-4.872,4.872-4.872c2.689,0,4.871,2.182,4.871,4.872C20.871,18.689,18.689,20.871,16,20.871z"/><title>Link options.</title></g></g></g></g></g><defs id="v-4"/></svg> </code></pre> <p>The code used in both the IDEs:</p> <pre><code>public static void main(String[] args) { OutputStream ostream = null; for(int i=0; i<1; i++){ try { // Create a JPEG transcoder String svgStr = getImageString(); File svgFile = File.createTempFile("tempImage", ".svg"); FileOutputStream fop = new FileOutputStream(svgFile); byte[] contentInBytes = svgStr.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); JPEGTranscoder t = new JPEGTranscoder(); // Set the transcoding hints. // Create the transcoder input. FileInputStream in = new FileInputStream(svgFile); TranscoderInput input = new TranscoderInput(in); // Create the transcoder output. ostream = new FileOutputStream("D://tempImage.jpg"); TranscoderOutput output = new TranscoderOutput(ostream); // Save the image. t.transcode(input, output); // Flush and close the stream. ostream.flush(); ostream.close(); } catch (FileNotFoundException ex) { Logger.getLogger(Class1.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Class1.class.getName()).log(Level.SEVERE, null, ex); } catch (TranscoderException ex) { Logger.getLogger(Class1.class.getName()).log(Level.SEVERE, null, ex); } finally { try { ostream.close(); } catch (IOException ex) { Logger.getLogger(Class1.class.getName()).log(Level.SEVERE, null, ex); } } } } private static String getImageString(){ String svgString = new String(); try { BufferedReader br = new BufferedReader(new FileReader("D://image.txt")); svgString = br.readLine(); br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return svgString; } </code></pre> <p>The error message that I get in eclipse is:</p> <pre><code>Original message: The "null" identifier is not a valid value for the "display" property. org.apache.batik.transcoder.TranscoderException: null Enclosed Exception: null at org.apache.batik.transcoder.image.ImageTranscoder.transcode(ImageTranscoder.java:132) at org.apache.batik.transcoder.XMLAbstractTranscoder.transcode(XMLAbstractTranscoder.java:142) at org.apache.batik.transcoder.SVGAbstractTranscoder.transcode(SVGAbstractTranscoder.java:156) at org.infosys.kbe.restapi.resources.ModelsResource.getPngFile(ModelsResource.java:866) at org.infosys.kbe.restapi.resources.ModelsResource.addPageforEachDiagram(ModelsResource.java:818) at org.infosys.kbe.restapi.resources.ModelsResource.lambda$0(ModelsResource.java:719) at java.util.ArrayList.forEach(Unknown Source) at org.infosys.kbe.restapi.resources.ModelsResource.createPDFusingPDFBox(ModelsResource.java:715) at org.infosys.kbe.restapi.resources.ModelsResource.generatePDFforModelWithId(ModelsResource.java:586) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161) at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$VoidOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:143) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99) at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102) at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:309) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) at org.glassfish.jersey.internal.Errors.process(Errors.java:315) at org.glassfish.jersey.internal.Errors.process(Errors.java:297) at org.glassfish.jersey.internal.Errors.process(Errors.java:267) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:292) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1139) at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:460) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.infosys.kbe.restapi.CORSFilter.doFilter(CORSFilter.java:27) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source) </code></pre> |
39,150,757 | 0 | How to show data by id in laravel 5.2 <p>I want to show data by id. If id=1 its need to show only id=1 data and if id 2 its should show only id=2 all data. My controller method:</p> <pre><code>->with('classroom',classroomModel::find($id)->first()); </code></pre> <p>Here is my view:</p> <pre><code><li>Class code-->{{$classroom->class_code}}</li> <li>Subject-->{{$classroom->subject_name}}</li> <li>Section-->{{$classroom->section}}</li> </code></pre> <p>now it is only show id=1 data. If i view id=2 data then it's show id=1 data. What should to do in my controller?</p> |
37,074,286 | 0 | <p>Try this if only 'ABC' an 'XYZ' types exist in the table:</p> <pre><code>SELECT number as id, MAX(CASE WHEN Type = 'ABC' THEN Date ELSE NULL END) as T1, MAX('ABC') as Type_1, MAX(CASE WHEN Type = 'XYZ' THEN Date ELSE NULL END) as T2, MAX('XYZ') as Type_2 FROM T GROUP BY Number </code></pre> |
13,214,694 | 0 | Setting up git branches <p>Hi I have setup git on my local machine.</p> <p>So I can now fully develop locally and push my files to master origin.</p> <p>but I'd like to be able to commit my files from local to a stage folder on remote, and then from there create a branch with all the files that goes to production. any ideas on how i can establish this ? I am very new to git. (just learned hot to commit, that new lol)</p> |
6,289,547 | 0 | <p>Sorry I did not replay earlier. Quickly, I'll would like to present one way of catching this for your consideration. For simplicity, I'll just concentrate on caching your outputs using Output frontend. </p> <p>In you application.ini you can setup your catching as follows: </p> <pre><code>resources.cachemanager.myviewcache.frontend.name = Output resources.cachemanager.myviewcache.frontend.customFrontendNaming = false resources.cachemanager.myviewcache.frontend.options.lifetime = 7200 resources.cachemanager.myviewcache.frontend.options.caching = true resources.cachemanager.myviewcache.frontend.options.automatic_serialization = true resources.cachemanager.myviewcache.backend.name = Apc </code></pre> <p>Note, that I use Apc as a backend. You may use file backend if you don't have or don't want Apc.</p> <p>With this, I would cache your posts and comments separately. For example, in <code>_posts.phtml</code> you could do something similar to the following:</p> <pre><code>// first cache an output related to the body of your post with key being associated // with your post. if (!($this->viewCache()->start('post_' . (string) $this->object->post_id))) { echo $this->object->title; echo $this->object->text; } // now I cache an output of a comments associated with a give post if (!($this->viewCache()->start('post_comments_' . (string) $this->object->post_id))) { echo $this->partialLoop('_comments.phtml',$this->object->getComments()); } </code></pre> <p>In this example, viewCache() view helper is as follows:</p> <pre><code>class My_View_Helper_ViewCache extends Zend_View_Helper_Abstract { /** * * @return Zend_Cache_Frontend_Output */ public function viewCache() { return Zend_Registry::get('outputCache'); } } </code></pre> <p>Whereas I set <code>outputCache</code> into registry in the Bootstrap.php:</p> <pre><code>protected function _initPutChachesIntoRegistry() { $this->bootstrap('cachemanager'); $cacheManager = $this->getResource('cachemanager'); Zend_Registry::set('outputCache', $cacheManager->getCache('myviewcache')); } </code></pre> <p>Notice that caches are associated with keys which in turn relate to a given post and its comments. With this, when you get a new comment, you just reset a cache related to the given post. For example, in an action, you can remove comment cache for a post with $post_id=5 as follows:</p> <pre><code>$this->view->viewCache()->remove('post_comments_' . $post_id); </code></pre> <p>Hope that this will help you or at least give you some ideas how to make it. </p> |
16,691,937 | 0 | How to insert on-fly query data to HBase using Hive <p>I am new in Hbase and Hive. Can someone please explain me how to insert data into Hbase using Hive?</p> <p>I found a lot of information regarding to this, but all of them are talking about exactly the same thing. In other words, they are inserting into Hbase table from another already existing table.</p> <p>In my case it is different. I have an application which reads some data from users and sends to the server and incoming data needs to be written in Hbase table. How can I do that?</p> <p>Here is my table:</p> <pre><code>CREATE TABLE hive_table (key INT, username STRING, password STRING, address STRING) STORED BY 'org.apache.hadoop.hive.hbase.HBaseStorageHandler' WITH SERDEPROPERTIES('hbase.columns.mapping'=':key, user:val') TBLPROPERTIES('hbase.table.name'='hbase_table'); </code></pre> <p>How can I insert following record to my Hbase table which is hbase_table using Hive:</p> <p><code>key=123, username='something', password='pass', address='somewhere';</code></p> <p>Thanks a lot!</p> |
3,177,373 | 0 | ASP.NET MVC2, How to Add Metadata Attributes and Control the order of properties displayed in the View <p>In ASP.NET MVC2, I have two ViewModels with Parent-Child relationship as below.</p> <p>Parent ViewModel:</p> <pre><code>public class PersonViewModel { [Required] public int ID{get;set;} [Required] [StringLength(50)] public string Name{get;set;} } </code></pre> <p>Child ViewModel:</p> <pre><code>public class EmployeeViewModel:PersonViewModel { [Required] [StringLength(50)] public string Title{get;set;} } </code></pre> <p>I have two questions with this setting.</p> <ol> <li><p>How can I add Metadata Attributes to the properties in the parent ViewModel from the child ViewModel?</p></li> <li><p>When displayed in the View using Html.DisplayForModel(), It seems the properties in the parent ViewModel always display after those of the child ViewModel. how can I control the order of properties displayed? </p></li> </ol> |
20,065,155 | 0 | <p>In setcookie function you can only set the cookie name. If you want to get that cookie value then you can take it via the <code>$_COOKIE['name']</code></p> <p>Be sure that when you create cookie you need to set domain name in setcookie function as well.</p> |
27,946,612 | 0 | <p>Try</p> <pre><code><Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source ="StyleTemplates.xaml"> </ResourceDictionary> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </code></pre> |
5,455,456 | 0 | <p>Yes. By using the attr method.</p> <pre><code>$('.NotSoRoundedCorners').attr('class', 'RoundedCorners'); </code></pre> |
28,844,201 | 0 | <p>Try this immediately under <code>{block:Posts}</code>, or before <code>{/block:Posts}</code> depending on where you want the signifier to be.</p> <pre><code>{block:HasTags} {block:Tags} <script type='text/javascript'> var {Tag} = '{Tag}'; if ({Tag} == 'movies') {document.write('Movies blah blah');} </script> {/block:Tags} {/block:HasTags} </code></pre> <p>This should display the text "Movies blah blah" wherever you put the code on posts you tag with the tag "movies" (case sensitive).</p> <p>Simply repeat for other tags.</p> |
10,403,767 | 0 | <p>Other than a <a href="http://www.ampsoft.net/webdesign-l/WindowsMacFonts.html" rel="nofollow">very short list</a>, you should not rely on everyone having the various font families on their computers.</p> <p>Instead, try out <a href="https://www.google.com/fonts/" rel="nofollow">Google WebFonts</a>. In fact, use the search box on the left to find their Garamond equivalent. Works in all browsers (including older IE!) and looks great everywhere.</p> <p>EDIT</p> <p>Regarding your additional question, yes, the browser will look for the fonts in the order that you specify them, so putting "Garamond" before "EB Garamond" will show Garamond if available in the user's computer.</p> |
22,816,514 | 1 | Openshift build script not setting environment variables <p>I'm attempting to deploy some app using openshift, but I need to configure a proxy to allow the cartridge to download some libraries from pip.</p> <p>However, attempting to export the environment variables needed in the pre-build hook (or any other hook in action_hooks) just doesn't stick.</p> <p>How can I set arbitrary environment variables in an openshift cartridge?</p> |
21,958,721 | 0 | <p>You could probably use punctuation or word boundry. </p> <p><strong><em>note</em> -</strong> Have to be carefull when specifying something like this <code>\byes\.\b</code><br> on the left hand side is <code>\.</code> a non-word, therefore to match on the right hand side <code>\b</code><br> there needs to be a word <code>\w</code> or it won't match. </p> <p>So, don't do that. </p> <p>This might work. </p> <p><code>\b(yes(?:\p{Punct}|\b))</code> </p> <p>And with a slight modification, you can exclude certain punctuation like this.<br> This captures all non-quote punctuation, that will be deleted as part of the replacement, or just matches a word boundry. </p> <p><code>\b(yes(?:[^\P{Punct}'"]|\b))</code> </p> <p>Another alternative is to include just the punctuation you want. </p> <p><code>\b(yes(?:[.,+*?-]|\b))</code> </p> |
27,322,515 | 0 | Write a C Program to extract a portion of a string from a character string using for loop <pre><code>#include<stdio.h> #include<string.h> void main() { char str1[50],str2[50]; int i,j,n,m,l; clrscr(); printf("Enter the string\n"); gets(str1); //scanf ("%s",str1); printf("Enter the position of the required character: "); scanf("%d",&n); printf("Enter the required number of characters to be extracted: "); scanf("%d",&m); l=strlen(str1); if(m+n-1<l) { for(i=n-1;i<m+n-1;i++) { for(j=0;j<i;j++) { str2[j]=str1[i]; str2[j]='\0'; } } printf ("The extracted string is: %s",str2); } else printf ("string extraction is not possible"); } </code></pre> <p>Expected Output </p> <pre><code>Enter the string : UNIVERSITY IN BANGALORE Enter the position of the required character: 6 Enter the required number of characters to be extracted: 4 The extracted string is: SITY </code></pre> |
2,281,951 | 0 | <p>Store the Thread results in a list after they were spawned and iterate the list - during iteration call join then. You still join linearly, but it should do what you want.</p> |
35,859,741 | 0 | Comparing two string failing assertion <p>This is really weird, im trying to assert two strings are equal and it's failing even though it looks to be the same.</p> <pre><code> Assert.assertSame("Extra Spicy", type, "type is not extra spicy"); </code></pre> <p>I get this error:</p> <blockquote> <p>java.lang.AssertionError: type is not extra spicy expected [Extra Spicy] but found [Extra Spicy] <br> Expected :Extra Spicy <br> Actual :Extra Spicy</p> </blockquote> <p>Everything matches, why is it failing?</p> |
29,368,582 | 0 | Integrate stateful C computations with Modelica <p>I have integrated a machine learning algorithm implemented in C with a Modelica model running in OpenModelica.</p> <p>The machine learning algorithm is in close-loop, taking as input the deviation from the target state and providing as output a control signal.</p> <p>I have set a sampling period so that the C algorithm is only called every X millisecs. However, I am seeing that the algorithm is being called several times for the same clock values.</p> <p>This makes me suspect that in order to solve the model, OpenModelica needs to invoke it several times per simulation iteration.</p> <p>This is affecting the way the algorithm is learning, as it keeps state regarding its experience.</p> <p>Why is OpenModelica invoking my algorithm several times per clock tick? How can I address this to not lead the learning to get confused by the multiple invocations for the same time?</p> |
5,062,222 | 0 | Changing the value of a variable that is a parameter in the parent scope <p>Is there any way to change the value of a parameter in the parent scope without passing it by reference to the child scope? I'd like to do something like this:</p> <pre><code>function foo($x = 5) { bar(); echo $x; // Ideally should output 6 } function bar() { $x = 6; } foo(); </code></pre> <p>In the scope of bar, I can get the value of $x by using debug_backtrace() or ReflectionFunction::getParameters, but I can't get a reference to $x!! Can this be done? I don't care if the solution is kind of a hack.</p> <p>(To reiterate, I KNOW that I could just pass $x by reference to bar.)</p> |
16,130,586 | 0 | Is there a way to connect Intellij IDEA to Sublime Text on Mac OS X? <p>I would like to find a way to open a file in Sublime Text 2 from Intellij IDEA (on Mac OS X), as to use its advanced text editing features on those occasions where writing "normal text" is not enough!</p> |
5,572,951 | 0 | <p>If I understand correctly, you can hook into the Form Closing event.</p> <p>So in your main form you can do something like:</p> <pre><code>Form2 form2 = new Form2(); form2.Show(); form2.FormClosing += new FormClosingEventHandler(form2_FormClosing); void form2_FormClosing(object sender, FormClosingEventArgs e) { this.Show(); } </code></pre> |
39,777,750 | 0 | <p>If you just want to set the value of the combobox input after the combobox is created, you can set the value of the select and then...</p> <pre><code>$(".ui-combobox-input").val($("#select option:selected").text()); </code></pre> |
3,506,700 | 0 | <p>Maybe pyCrust plus the Python debugger?</p> |
15,867,840 | 0 | Mouse Hower on TextBlock <p>The idea is when mouse howler above <code>TextBlock</code>, new <code>Image</code> is appear and it possible to click on it. When mouse leave the <code>TextBlock</code> - <code>Image</code> should disappear. </p> <p>Meanwhile I came to this, but still unable to continue:</p> <pre><code><Style x:Key="HoverHighlightTextStyle" TargetType="TextBlock"> <Setter Property="FontSize" Value="16"/> <Setter Property="FontWeight" Value="Normal"/> <Setter Property="Margin" Value="3,0,3,0"/> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> </Trigger> </Style.Triggers> </Style> </code></pre> <p><code>Expected result</code></p> <p><img src="https://i.stack.imgur.com/4oRHb.png" alt="enter image description here"></p> |
6,644,091 | 0 | Java Date determine if DAY is greater <p>I have time stamps as string format Sun Jul 10 17:47:55 EDT 2011</p> <p>I need to determine if the current DAY is greater than the stored day.</p> <p>I will get the current day with <code>Date currentDate = new Date();</code></p> <p>and I will parse my string into a <code>Date</code> object with <code>SimpleDateFormat dateParser = new SimpleDateParser("E MMM d HH:mm:ss z y");</code></p> <p>but using the "currentDate.after()" function, or the <code>currentDate.compare()</code> function will only tell me if ANY date is greater or less than, which includes by the hour,minute or second.</p> <p>So My next hunch would be to convert the date into the day of the year, and compare the new integers, if integer1>integer2, then.. but how would I do that?</p> <p>I also considered breaking the string up to a substring consisting of only the first half of the stored string date. <code>Sun Jul 10</code> to <code>Sun Jul 10</code> but the problem here is that the day value is sometimes 1 digit and othertimes 2 digits.</p> <p>Also I think the <code>Calendar</code> abstract class is the best way to go about this, but I am unsure, and currently in a fog about how to convert the Date objects into the Calendar object for comparison!</p> <p>Insight appreciated</p> |
4,077,369 | 0 | concatenate boost::mpl::string <p>How I can concatenate boost::mpl::string? The following code produce errors:</p> <pre><code>#include <iostream> #include <boost/mpl/vector.hpp> #include <boost/mpl/string.hpp> #include <boost/mpl/fold.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/push_back.hpp> typedef boost::mpl::vector< boost::mpl::string<'ab'>, boost::mpl::string<'cd'>, boost::mpl::string<'ef'> > slist; typedef boost::mpl::fold< slist, boost::mpl::string<>, boost::mpl::push_back<boost::mpl::_1, boost::mpl::_2> >::type string; int main() { std::cout << boost::mpl::c_str<string>::value << std::endl; } </code></pre> <p>full source here: <a href="http://liveworkspace.org/code/31902a4b1b0831d054119bc0b8923cb6" rel="nofollow">http://liveworkspace.org/code/31902a4b1b0831d054119bc0b8923cb6</a> errors:</p> <blockquote> <p>In file included from source.cpp:3:0: string.hpp: In instantiation of 'boost::mpl::push_back_impl< boost::mpl::string_tag</p> <blockquote> <p>::apply, boost::mpl::string<24930> >': boost/mpl/push_back.hpp:32:1:<br> instantiated from 'boost::mpl::push_back< boost::mpl::string<>, boost::mpl::string<24930> ' boost/mpl/aux_/has_type.hpp:20:1:<br> instantiated from 'const bool boost::mpl::aux::has_type< boost::mpl::push_back, boost::mpl::string<24930> >, mpl_::bool_ ::value' boost/mpl/aux_/has_type.hpp:20:1:<br> instantiated from 'boost::mpl::aux::has_type< boost::mpl::push_back, boost::mpl::string<24930> >, mpl_::bool_ ' boost/mpl/aux_/preprocessed/gcc/quote.hpp:56:5: instantiated from 'boost::mpl::quote2< boost::mpl::push_back ::apply, boost::mpl::string<24930> >' boost/mpl/aux_/preprocessed/gcc/apply_wrap.hpp:49:1: instantiated from 'boost::mpl::apply_wrap2< boost::mpl::quote2, boost::mpl::string<>, boost::mpl::string<24930> ' boost/mpl/aux_/preprocessed/gcc/bind.hpp:207:21: instantiated from 'boost::mpl::bind2< boost::mpl::quote2, mpl_::arg<1>, mpl_::arg<2> ::apply, boost::mpl::string<24930> >' boost/mpl/aux_/preprocessed/gcc/apply_wrap.hpp:49:1: instantiated from 'boost::mpl::apply_wrap2< boost::mpl::protect< boost::mpl::bind2, mpl_::arg<1>, mpl_::arg<2> >, 0 , boost::mpl::string<>, boost::mpl::string<24930> ' boost/mpl/aux_/preprocessed/gcc/apply.hpp:73:1: instantiated from 'boost::mpl::apply2< boost::mpl::push_back, mpl_::arg<2> >, boost::mpl::string<>, boost::mpl::string<24930> ' boost/mpl/aux_/preprocessed/gcc/fold_impl.hpp:87:85: instantiated from 'boost::mpl::aux::fold_impl< 3, boost::mpl::v_iter< boost::mpl::vector, boost::mpl::string<25444>, boost::mpl::string<25958> >, 0l , boost::mpl::v_iter< boost::mpl::vector, boost::mpl::string<25444>, boost::mpl::string<25958> >, 3l , boost::mpl::string<>, boost::mpl::push_back, mpl_::arg<2> > ' boost/mpl/fold.hpp:39:18: instantiated from 'boost::mpl::fold< boost::mpl::vector, boost::mpl::string<25444>, boost::mpl::string<25958> > , boost::mpl::string<>, boost::mpl::push_back, mpl_::arg<2> > ' source.cpp:18:2: instantiated from here string.hpp:207:53: error: 'value' is not a member of 'boost::mpl::string<24930>' In file included from boost/mpl/back_inserter.hpp:18:0, from boost/mpl/aux_/inserter_algorithm.hpp:18, from boost/mpl/copy.hpp:20, from string.hpp:26, from source.cpp:3: boost/mpl/push_back.hpp: In instantiation of 'boost::mpl::push_back< boost::mpl::push_back, boost::mpl::string<24930> >, boost::mpl::string<25444> ': boost/mpl/aux_/has_type.hpp:20:1:<br> instantiated from 'const bool boost::mpl::aux::has_type< boost::mpl::push_back< boost::mpl::push_back, boost::mpl::string<24930> >, boost::mpl::string<25444> , mpl_::bool_ ::value' boost/mpl/aux_/has_type.hpp:20:1:<br> instantiated from 'boost::mpl::aux::has_type< boost::mpl::push_back< boost::mpl::push_back, boost::mpl::string<24930> >, boost::mpl::string<25444> , mpl_::bool_ ' boost/mpl/aux_/preprocessed/gcc/quote.hpp:56:5: instantiated from 'boost::mpl::quote2< boost::mpl::push_back</p> </blockquote> </blockquote> |
30,117,338 | 0 | <pre><code>Private Sub Workbook_Open() '// Disable Accelerators keys in Excel 2007-2013 Dim Ctl As CommandBarControl For Each Ctl In Application.CommandBars("&Legacy Keyboard Support").Controls Ctl.Tag = Ctl.Caption Ctl.Caption = Replace(Ctl.Caption, "&", "") Next Dim StartKeyCombination As Variant Dim KeysArray As Variant Dim Key As Variant Dim I As Long On Error Resume Next '// Shift key = "+" (plus sign) '// Ctrl key = "^" (caret) '// Alt key = "%" (percent sign '// We fill the array with this keys and the key combinations '// Shift-Ctrl, Shift- Alt, Ctrl-Alt, Shift-Ctrl-Alt For Each StartKeyCombination In Array("+", "^", "%", "+^", "+%", "^%", "+^%") KeysArray = Array("{BS}", "{BREAK}", "{CAPSLOCK}", "{CLEAR}", "{DEL}", _ "{DOWN}", "{END}", "{ENTER}", "~", "{ESC}", "{HELP}", "{HOME}", _ "{INSERT}", "{LEFT}", "{NUMLOCK}", "{PGDN}", "{PGUP}", _ "{RETURN}", "{RIGHT}", "{SCROLLLOCK}", "{TAB}", "{UP}") '// Disable the StartKeyCombination For Each Key In KeysArray Application.OnKey StartKeyCombination & Key, "" Next Key '// Disable the StartKeyCombination key(s) with every other key For I = 0 To 255 Application.OnKey StartKeyCombination & Chr$(I), "" Next I '// Disable the F1 - F15 keys in combination with the Shift, Ctrl or Alt key For I = 1 To 15 Application.OnKey StartKeyCombination & "{F" & I & "}", "" Next I Next StartKeyCombination '// Disable the F1 - F15 keys For I = 1 To 15 Application.OnKey "{F" & I & "}", "" Next I '// Disable the PGDN and PGUP keys Application.OnKey "{PGDN}", "" Application.OnKey "{PGUP}", "" End Sub </code></pre> <p>Reference below links</p> <p><a href="http://www.rondebruin.nl/win/s5/win005.htm" rel="nofollow">Excel Automation</a></p> <p><a href="https://msdn.microsoft.com/en-us/library/ms724947(v=vs.85).aspx" rel="nofollow">SystemParametersInfo Function</a></p> |
15,595,120 | 0 | <p>You shouldn't use the dyno filesystem for persistent file storage (like databases). The dyno filesystems are ephemeral and changes are not reflected in the git repository associated with you app. Use one of the data storage add-ons instead: <a href="https://addons.heroku.com" rel="nofollow">https://addons.heroku.com</a></p> |
25,032,376 | 0 | <p>As ZZ Coder has already mentioned load balancer is a good solution especially for big deployments. For my own project I use reverse http proxy functionality of nginx web server. It redirects all http packets from a specified web context (seen from the Internet) to a server inside my network. Configuration is really easy:</p> <p><code> location /best-app-ever/ { proxy_pass host-address:8080/some-app-1.1 root /home/www/some-app-1.1 } </code></p> <p>Switching version should be smooth as well. Assuming that you have already deployed new version of application just change nginx configuration file and apply changes:</p> <p><code> location /best-app-ever/ { proxy_pass host-address:8080/some-app-1.2 root /home/www/some-app-1.2 } </code></p> <p><code>sudo nginx -t</code> <br/> <code>sudo service nginx restart</code></p> <p>Be warned that in case your web application is stateful and/or contains some running or scheduled processes, the deployment and undeployment might not be as smooth.</p> |
37,966,360 | 0 | <p>You can use Exists for this </p> <pre><code>Select * from (select Barcode from ITList union select Barcode from Equipment_list) as t where exists (select Barcode from Scanneditem where Scanneditem.Barcode = t.Barcode) </code></pre> |
27,981,621 | 0 | Generate Timestamp in IST Timezone java <p>I am trying to generate current timestamp in GMT timezone but it is still getting generated in IST as my machine is set to IST. I am using this code. Please help!!</p> <pre><code>{ String timeZone = "GMT"; Calendar gmtCalendar = Calendar.getInstance(TimeZone.getTimeZone(timeZone)); Date date = gmtCalendar.getTime(); endTime = new Timestamp(date.getTime()); String eTime = NLSUtil.getFormattedDate(AdfUtil.getClientLocale(), new java.sql.Date(endTime.getTime())); } </code></pre> |
34,467,431 | 0 | <p>Generally: yes, the bias weights should be updated and included in training just as any other weight in the NN (also in backpropagation).</p> <p>In the example you've posted, the bias <code>b1</code> is added to both neurons the hidden layer, and bias <code>b2</code> to both neutrons in the output layer</p> <pre><code>Hidden layer: h1 = i1*w1 + i2*w2 + 1*b1 h2 = i1*w3 + i2*w4 + 1*b1 Output layer: o1 = h1*w5 + h2*w6 + 1*b2 o2 = i2*w7 + h2*w8 + 1*b2 </code></pre> <p>With initial, and in this example, fixed, biases</p> <pre><code>b1 = 0.35 b2 = 0.60 </code></pre> <p>This means that the biases for hidden neutrons is always exactly 0.35, and for output neutrons exactly 0.60. This, however, is not usual practice, as you want to train your NN to find "good" biases just as much you want it to train to find good weights.</p> <p>Note also, in the comments of the link you provided, that another user has asked why biases are not changed, and the author has replied, quote:</p> <blockquote> <p>"Hey, in the tutorials I went through they didn’t update the bias which is why I didn’t include it here."</p> </blockquote> <p>This lack of a specific "why" possibly implies that the author of this example/tutorial is, however well-versed, no expert at the subject of NN, so you shouldn't out to much weight (no pun intended...) into the fast that the biases are not changed in this specific example.</p> <hr> <p>If you really want to dig into a sound and thorough covering of NN in the context of back propagation, I would rather recommend you Michael Nielsen excellent book on NN and deep learning, specifically for this subject, Chapter 2. Note that the bias weights, here, are treated just as weights for neuron-neuron data transfer.</p> <ul> <li><a href="http://neuralnetworksanddeeplearning.com/chap2.html" rel="nofollow">http://neuralnetworksanddeeplearning.com/chap2.html</a></li> </ul> <p>Michael is a Google Researcher with numerous publicised articles in the subject of advanced NN and deep learning.</p> <blockquote> <p>At the heart of backpropagation is an expression for the partial derivative ∂C/∂w of the cost function C with respect to any weight w (or bias b) in the network. The expression tells us <strong>how quickly the cost changes when we change the weights and biases.</strong></p> </blockquote> |
23,645,666 | 0 | <p>You can give an alignment suggestion to the layout manager by using:</p> <pre><code>label.setAlignmentY(JLabel.CENTER_ALIGNMENT); </code></pre> <p>If this doesn't help then post a proper <a href="http://www.sscce.org/" rel="nofollow">SSCCE</a> that demonstrates the problem.</p> |
25,712,668 | 0 | <p>Assuming the input array is <code>(n,m,3)</code>, then it can be expanded to <code>(n,m,4)</code> by simply concatenating a <code>(n,m,1)</code> array.</p> <pre><code>X = np.ones((n,m,3), dtype='byte') F = np.zeros((n,m,1), dtype='byte') X1 = np.concatenate([X,F], axis=2) </code></pre> <p>Strides for these are <code>(3*m,3,1)</code>, <code>(m,1,1)</code> and <code>(4*m,4,1)</code>.</p> <p>The same data could put in</p> <pre><code>In [72]: dt0 = np.dtype([('R','u1'), ('G','u1'), ('B','u1')]) In [73]: X=np.ones((n,m),dtype=dt0) In [74]: X.strides Out[74]: (150, 3) In [75]: X.shape Out[75]: (30, 50) </code></pre> <p>With the target having <code>dt = np.dtype([('R','u1'), ('G','u1'), ('B','u1'), ('A','u1')])</code> <a href="http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html</a></p> <h2>Mapping RGB fields to RGBA</h2> <p>But to do concatenation with these dtypes, we'd do some sort of casting to the <code>(n,m,3)</code> shape. Looks like reassigning the <code>data</code> attribute will do the trick.</p> <pre><code>n, m = 2, 4 dt1 = np.dtype([('R','u1'), ('G','u1'), ('B','u1'), ('A','u1')]) dt0 = np.dtype([('R','u1'), ('G','u1'), ('B','u1')]) X = np.arange(n*m*3,dtype='u1').reshape(n,m,3) print repr(X) X0 = np.zeros((n,m), dtype=dt0) X0.data = X.data print repr(X0) X0.strides # (12, 3) X1 = np.zeros((n,m), dtype=dt1) F = np.zeros((n,m,1), dtype='u1') X01 = np.concatenate([X, F], axis=2) X1.data = X01.data print repr(X1) X1.strides # (12, 4) </code></pre> <p>producing:</p> <pre><code>array([[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)], [(12, 13, 14), (15, 16, 17), (18, 19, 20), (21, 22, 23)]], dtype=[('R', 'u1'), ('G', 'u1'), ('B', 'u1')]) array([[(0, 1, 2, 0), (3, 4, 5, 0), (6, 7, 8, 0), (9, 10, 11, 0)], [(12, 13, 14, 0), (15, 16, 17, 0), (18, 19, 20, 0), (21, 22, 23, 0)]], dtype=[('R', 'u1'), ('G', 'u1'), ('B', 'u1'), ('A', 'u1')]) </code></pre> <h2>Using overlapping dtypes</h2> <p>Here's a way of doing it with overlapping dtypes rather than concatenation:</p> <pre><code>dt0 = np.dtype([('R','u1'), ('G','u1'), ('B','u1')]) dt1 = np.dtype([('R','u1'), ('G','u1'), ('B','u1'), ('A','u1')]) dtb = np.dtype({'names':['rgb','rgba'], 'offsets':[0,0], 'formats':[dt0, dt1]}) X0 = np.zeros((n,m), dtype=dt0) X0.data = X.data X1 = np.zeros((n,m), dtype=dtb) X1['rgb'][:] = X0 print repr(X1['rgba']) </code></pre> <p>Or without the individual named byte fields it's even simpler:</p> <pre><code>dt0 = np.dtype(('u1',(3,))) dt1 = np.dtype(('u1',(4,))) dtb = np.dtype({'names':['rgb','rgba'], 'offsets':[0,0], 'formats':[dt0, dt1]}) X = np.arange(n*m*3,dtype='u1').reshape(n,m,3) X1 = np.zeros((n,m), dtype=dtb) X1['rgb'][:] = X </code></pre> <p><code>X1['rgba']</code> is <code>(n,m,4)</code>, with strides <code>(m*4, 4, 1)</code>.</p> <p><code>X1['rgb']</code> is <code>(n,m,3)</code>, but with the same strides <code>(m*4, 4, 1)</code>.</p> <h2>Using <code>as_strided</code></h2> <p>That difference in shape, but similarity in strides, suggest's using <code>as_strided</code>. Create the empty target array, and use <code>as_strided</code> to select a subset of elements to receive values from <code>X</code>:</p> <pre><code>X1 = np.zeros((n,m,4),dtype='u1') np.lib.stride_tricks.as_strided(X1, shape=X.shape, strides=X1.strides)[:] = X print X1 </code></pre> |
14,598,137 | 0 | <p>The question is a little bit poor specified. </p> <blockquote> <p>order the result in asc or desc depending upon a column value.</p> </blockquote> <p>A column takes many values (as there are multiple rows).</p> <p>Now, <code>order by</code> clause use an expression and order rows upon it. That expression should be morphotropic(;))</p> <p>So, assuming stardard oracle's employee schema, managers are:</p> <pre><code>select * from emp e where exists (select emp_id from emp where e.id=emp.mgr_id) </code></pre> <p>An workaround query may be:</p> <pre><code>Select e.id, e.name, e.birth_date, case when (select count(*) from emp e where exists (select emp_id from emp where e.id=emp.mgr_id) ) --existence of manager > 0 then birth_date - to_date('1-Jan-1000','dd-mon-yyyy') else to_date('1-Jan-1000','dd-mon-yyyy') - birth_date end as tricky_expression from emp A order by 4; </code></pre> <p>That exexpresion is the <code>case</code>; Using a constant(subquery that decides there are managers) it changes values from positive to negative, that is, change the order direction.</p> <p><strong>UPDATE:</strong> with the details in the comments:</p> <pre><code>select id, name, birth_date emp_type from ( Select id, name, birth_date, emp_type, case when cnt_mgr > 0 then birth_date - to_date('1-Jan-1000','dd-mon-yyyy') else to_date('1-Jan-1000','dd-mon-yyyy') - birth_date end as tricky_expression from( Select e.id, e.name, e.birth_date, emp_type, count(case when emp_type='M' then 1 else 0 end) over() as mgr_count from emp A where your_conditions ) order by tricky_expression ) where rownum=1; </code></pre> |
17,048,090 | 0 | <p>No the richtext component does not provide such functionality. But it is possible to create ordered and unordered lists and to intend or outend the single list items.</p> |
37,486,328 | 0 | SQL query to rows to columns <p>I have a table like this</p> <pre><code>CREATE TABLE #CurrencyRate ( [Base] nvarchar(10), [Quote] nvarchar(10), [Amount] nvarchar(10) ) </code></pre> <p>and it has data like this</p> <pre><code>Base Quote Amount --------------------- R1C1 R1C2 R1C3 R2C1 R2C2 R2C3 </code></pre> <p><strong>Note</strong>: <code>R1C1</code> => Row 1, Column 1</p> <p>I want output like </p> <pre><code>Row Column Attribute Value ----------------------------------------- 1 1 Base R1C1 1 2 Quote R1C2 1 3 Amount R1C3 2 1 Quote R2C1 2 2 Amount R2C2 2 3 Base R2C3 </code></pre> <p>Is it possible to get output like this with some SQL?</p> <p>Thanks in advance</p> |
28,526,565 | 0 | <p>Please consider the following <em>"test guide"</em> more as comment than an answer, because it just contains some <code>console.log</code> statements instead of an actual answer for your problem.</p> <p>Anyway below are some issues I'd try to checkout:</p> <ol> <li>do you receive an answer from the server following <code>query.find</code> </li> <li>check is data fetched (inner query) from the server</li> <li>check if category data is received successfully following fetch query </li> <li>check if element with category id is found</li> <li>error handling added for fetch and query </li> </ol> <p>Also I noticed that you are using <a href="http://api.jquery.com/text/" rel="nofollow">.text()</a> method for setting the value. I think it'll work fine as long as the element in question is not a form input element. If that's the case, you probably have to you use <a href="http://api.jquery.com/val/" rel="nofollow">.val()</a> method.</p> <p>The <code>console.log</code> test print outs that I added can be found at this <a href="http://jsfiddle.net/jyrkim/usdgvx85/1/" rel="nofollow">Fiddle</a> for <code>updateBudgets()</code> function. (Fiddle updated) I hope this helps :-)</p> |
24,083,219 | 0 | <p>Threre are other <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html" rel="nofollow">threadpools available</a>, for example the fixed threadpool (<code>newFixedThreadPool</code>), which seems to behave just as the one you use, only without the sceduling.</p> |
29,203,494 | 0 | <p>you need to provide the failure message while asserting only then it will take up in the report. Consider below code snippet:</p> <pre><code>import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; public class SoftAsert { @Test public void test() { SoftAssert asert=new SoftAssert(); asert.assertEquals(false, true,"failed"); asert.assertEquals(0, 1,"brokedown"); asert.assertAll(); } } </code></pre> <p>Output:</p> <pre><code>FAILED: test java.lang.AssertionError: The following asserts failed: failed, brokedown </code></pre> <p>That is how the softassertions are suppose to work. The intent is to display the error message in case of failure. Let me know if this helps.</p> |
20,627,067 | 0 | <p>Your code isn't compilable. Here is the reasons:</p> <ol> <li>The conditions must be placed into some method</li> <li>The declaration of event handler must be moved out from the condition scope</li> </ol> <p>Here is the workable code:</p> <pre><code>namespace WindowsFormsApplication1 { public partial class Form1 : Form { private int flag; FileSystemWatcher watcher = new FileSystemWatcher(); public Form1() { InitializeComponent(); watcher.Path = @"C:\"; watcher.Filter = "test.txt"; watcher.Changed += watcher_Changed; watcher.EnableRaisingEvents = true; } private void SetFlag() { FileInfo info = new FileInfo("c:\\test.txt"); if (info.Length > 0) flag= 1; } private void CheckFlag() { if(flag==1) { button1.PerformClick(); } } private void button1_Click(object sender, EventArgs e) { //Code for Redirection to New Form } void watcher_Changed(object sender, FileSystemEventArgs e) { SetFlag(); CheckFlag(); } } } </code></pre> <p>And now you can call method <code>SetFlag()</code> to set flag. And use method <code>CheckFlag()</code> to check flag. In this example I use <code>FileSystemWatcher</code> to catch all file changes and call <code>SetFlag()</code> and <code>CheckFlag()</code> inside the handler of event <code>Changed</code></p> <p>Instead of <code>button1.PerformClick()</code> you can use <code>button1_Click(this, EventArgs.Empty)</code></p> |
10,946,596 | 0 | How to create image in php <p>I am creating image with php</p> <p>code</p> <pre><code>$src = array ("22.jpg","33.jpg","44.jpg","55.jpg","66.jpg","77.jpg"); $imgBuf = array (); foreach ($src as $link) { switch(substr ($link,strrpos ($link,".")+1)) { case 'png': $iTmp = imagecreatefrompng($link); break; case 'gif': $iTmp = imagecreatefromgif($link); break; case 'jpeg': case 'jpg': $iTmp = imagecreatefromjpeg($link); break; } array_push ($imgBuf,$iTmp); } $iOut = imagecreatetruecolor ("35","210") ; imagecopy ($iOut,$imgBuf[0],0,0,0,0,imagesx($imgBuf[0]),imagesy($imgBuf[0])); imagedestroy ($imgBuf[0]); imagecopy ($iOut,$imgBuf[1],0,35,0,0,imagesx($imgBuf[1]),imagesy($imgBuf[1])); imagedestroy ($imgBuf[1]); imagecopy ($iOut,$imgBuf[2],0,70,0,0,imagesx($imgBuf[2]),imagesy($imgBuf[2])); imagedestroy ($imgBuf[2]); imagecopy ($iOut,$imgBuf[3],0,105,0,0,imagesx($imgBuf[3]),imagesy($imgBuf[3])); imagedestroy ($imgBuf[3]); imagecopy ($iOut,$imgBuf[4],0,140,0,0,imagesx($imgBuf[4]),imagesy($imgBuf[4])); imagedestroy ($imgBuf[4]); imagecopy ($iOut,$imgBuf[5],0,175,0,0,imagesx($imgBuf[5]),imagesy($imgBuf[5])); imagedestroy ($imgBuf[5]); imagepng($iOut); //header ( 'Content-type:image/png' ); // save the img to directory $char='0123456789'; $length=10; $max_i=strlen($char)-1; $value=''; for($j=0;$j<$length;$j++) { $value.=$char{mt_rand(0,$max_i)}; } $imageid=$value; </code></pre> <p>it giving error on page like </p> <blockquote> <p>‰PNG IHDR#ÒOuî² CIDATxœíÖ]ŒdÇUðÿ9§êÞþ˜™]ïìÇlbc‚ÀІ(@dQž @"$ƒ”<°E‚XX<code>Y~ E D¼€"!ÂI’;Q$£°M¼ïzw½_3ÓÓÝ÷Ö×9<ô̬óÄRê§V«Õ·»ÿU]uÏ)JÙ ‚Ì€˜7€wâÕ½«¯^»Óçþå™åfȹ-š© *6›çŸù¹÷ðêðÌ[í‰%üÈ]؆0‡8@@ÙL3¼Än‘×ãÞ«·žxôñ»×69àôú©e?ÊóÙÊx™’W+Ü”˜C1Vö4Üîowq÷zwë?ýI·u§,É~@½™@PF¼Ž'>ô»ÇýÚ‘áÊòêÒh8HëᬠŒ,eïÄ9îK ¡Lº½4ëºÙüÖ7Óä¿ø—Ø–€‡(™€b’ »øØ¹ß\K÷o¾ãÌúI&*‚lÙÁR4P£ÄEÕ‰P¢ó!Î}ë:ëEdÄ-gX_.߸òòök¯ûŸúöߣMp~1'ç($àßo½-ÿÀÛï][Z/1Ëlo‡PaÕa#¥›{4Óɘ4—\Š9í%©FË'7ÓÕñÝîƒÅ_h¹@øNþÄû}ðØ?6NsLªêü0ö¡q%ö#fÖ2²Óbð’´¨ªjS¸,¾GE.ì\x~÷ùO>ûØ x</code>°"*¶ñ±|äÄÚ™ñʱÉv§Á4X‰¶·Óõ†S‹½€½Ž£QFècÅcŒ¡OH ˆ²ÝˤϷws›ë›'è$þûòþ:931þkû¸-Z;1Ÿv%ôÐ’c ߸&Lûaëgq:Ó>Í•àÃñ`¼:;EŠÉHBL¸ºv<š¤É€†§†Ç¿õ¥¯ŸýÉì');¾ó·7ëÜ' 9ö¥ˆH\C–Çäß¼ùæ%Ýž #µs¦áéptU–}±lST°F:£#úãÏ}ù«g?HÊ Q<÷¥=5>–»b¢M¹uV †½8»<»úûŸ{ooa€xmïÓ|üÈÚÀ›Ï}/</p> </blockquote> <p>how i can solve this </p> |
40,362,894 | 0 | PHP LDAPS unable to connect to server <pre><code> $username = $_POST['username']; $password = $_POST['password']; $ldaphost = "ldaps://corpldap.xxx.net"; $ldapUsername = "cn=$username,ou=people,dc=xxx,dc=net"; $ldapPassword = "$password"; $ds = ldap_connect($ldaphost,636) or die("\r\nCould not connect to LDAP server\r\n"); echo $ds; //this output 'Resource id #21' ldap_set_option($ds, LDAP_OPT_REFERRALS, 0); if (!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) { print "Could not set LDAPv3\r\n"; } else { // now we need to bind to the ldap server echo 'success'; //echo success output $bth = ldap_bind($ds) or die("\r\nCould not connect to LDAP server\r\n"); } </code></pre> <p>I get 'Resource id #21 success Could not connect to LDAP server'</p> <p>so ldap_bind is failing</p> <p>stack trace on error log: PHP Warning: ldap_bind(): Unable to bind to server: Can't contact LDAP server</p> <p>How can i fix this? Please help.</p> <p>Please note: i also tried $ldaphost = "ldaps://corpldap.xxx.net:636";</p> <p>I also tried echoing php_info() which shows ldap enabled.</p> |
11,952,033 | 0 | <p>I suppose <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow">Singleton</a> should help you managing it better, so you dont have to pass the pointer around. Practically, <code>mpi_glob</code> does the same, <code>Singleton</code> is just more accustomed way.</p> <p>Alternatively, you can still resort to global variables - they are not bad as such. If you want to emphasize one-time assignment you can declare them <code>const</code> and set them via static initializer like this:</p> <pre><code>const int number_of_tasks = get_preconfigured_number_of_tasks(); </code></pre> <p>If your global variables are used to hold compile time constants, then it is perfectly fine to replace them with <code>enum</code> members or preprocessor defines. Doing so will ease up on compiler, because it can use immediate value in-place without memory access.</p> <hr> <p>Credit goes to Pete Becker for pointing Singleton issues in his comment. If those issues bother you too, then totally different approach can be taken.</p> <p>Remember how Java programs are implemented? There is main class with main method and all program's work runs from inside that main method. Main is still member function, i.e. it can exclusively access some private fields of the main class (they have to be static in case of Java, but this is not the main point here).</p> <p>We can further extend the concept to <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="nofollow">Command</a>-like implementation. The difference with conventional Java is that your main method equivalent is not static and your global variables with values specific to contained program are non-static member variables. All functions that need access to global state data are to be converted into member functions. This is possible, because main method is also member function.</p> <p>This way, I think, you can achieve better encapsulation and data safety.</p> |
1,964,450 | 0 | <p>Here's a more idiomatic and generic approach:</p> <pre><code>template<typename K, typename T> class AVLTree { ... template <typename Comparer> void foo(Comparer cmp) { ... int res = cmp(key1, key2); ... } ... }; </code></pre> <p>Comparer should not be a type that defines a static <code>Compare</code> method. It should be a type which can be called with function call syntax. That allows you to use function pointers of function objects, and it allows you to reuse the comparers already defined in the standard library, or in pretty much any other nontrivial C++ application. It allows you to use lambdas when they're added in C++0x.</p> <p>As for forcing <code>Comparer</code> to behave as expected? The line <code>int res = cmp(key1, key2);</code> already ensures that. If you try to pass a type that can't be called in this way, you get a compile error.</p> <p>The same was the case in your original code. If you passed a type that didn't have a static <code>Compare</code> method, you'd get a compile error. So your original code already solved the problem.</p> |
24,745,209 | 0 | <p>First of all, I would set the interval to something like 500, then step it back to 400, 300, 200, 100, etc. until you get the desired speed you want.</p> <p>Secondly, assuming <strong>Label2</strong> is your <em>max</em> value and <strong>Label3</strong> is your <em>min</em> value and that you want your progress bar control to simply <em>bounce</em> back and forth between the min and max values, I would do something like this:</p> <pre><code>Const MAX_VALUE = 100 Const MIN_VALUE = 0 Dim currentValue = 0 Dim isIncrementing = True Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick If currentValue = MAX_VALUE Then isIncrementing = False If currentValue = MIN_VALUE Then isIncrementing = True If isIncrementing Then currentValue += 1 Else currentValue -= 1 ProgressBar1.Value = currentValue ProgressBar1.Update() End Sub </code></pre> <p><em>Since I'm assuming your <strong>Label2</strong> and <strong>Label3</strong> are your min/max values, I'm also assuming they should stay static and never change, which is why I don't change their values in the <code>Tick</code> event. If you wanted a <strong>Current Value</strong> label, that would be easy enough to add and that would be changed at the same time the <code>ProgressBar1.Value</code> is.</em></p> |
2,421,385 | 0 | <p>Regex has a thing called a "non capturing negative lookahead assertion" which basically says "don't match the following". It looks like this: </p> <pre><code>^people/(?!People_Search)([A-Za-z0-9\-\_]+)/?$ </code></pre> <p>Whether you can use this depends on the rewrite engine you use, and the level of regex support that's included in it. I'd expect that most common rewriters support this. </p> <p>FYI: There are also negative lookbehind assertions(?<!), and also postive versions of the lookahead (?=) and lookbehind (?<=) assertions. </p> <p>Tutorial: <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow noreferrer">http://www.regular-expressions.info/lookaround.html</a></p> |
1,569,866 | 0 | <p>Either use:</p> <pre><code><Directory /path/to/root> Options +ExecCGI </Directory> </code></pre> <p>or</p> <pre><code><Location /> Options +ExecCGI </Location> </code></pre> <p>See <a href="http://httpd.apache.org/docs/2.2/mod/core.html#directory" rel="nofollow noreferrer">Directory</a> and <a href="http://httpd.apache.org/docs/2.2/mod/core.html#location" rel="nofollow noreferrer">Location</a> in Apache docs.</p> |
40,223,949 | 0 | <p>The semantics of a value being missing are exactly why <a href="http://en.cppreference.com/w/cpp/utility/optional" rel="nofollow"><code>std::optional</code></a> was introduced to the C++ language specification.</p> <pre><code>std::optional<unsigned int> value; // by default, the value is missing if(value) { // executed if the value is present, it is not } else { // this code is executed } value = 1; if(value) { // This code would now be executed std::cout << "the value: " << *value << std::endl; } </code></pre> <p>This requires a change in thinking regarding the meaning of the variable, but it forces you to think at all times regarding whether or not the variable would be present.</p> <p>So for example, if you had your own class type <code>MyClass</code> and you wanted to retain a, potentially missing, instance of it, you would do so as follows:</p> <pre><code>std::optional<MyClass> obj; // Initially missing obj = MyClass(); // Assigns a newly-created instance of MyClass obj->foo(); // Calls the 'MyClass::foo' method obj.reset(); // clears the 'obj' optional </code></pre> |
33,646,950 | 0 | How to increment and keep previous increments when values are the same in emacs <p>I have two columns with values, the second column starts at particular value, I want the second column to start with one, and increment only whenever a value changes, otherwise keep the previous increment. I can use macro to set the start count, but how to make sure that same values remains the same as shown ?, </p> <p>Problem: </p> <pre><code>0,39 1,39 2,39 3,39 4,40 5,40 6,40 7,41 </code></pre> <p>I want this: </p> <pre><code>0, 1 1, 1 2, 1 3, 1 4, 2 5, 2 6, 2 7, 3 </code></pre> |
32,050,200 | 0 | Flickr API - Get Image ID and pass to second request <p>I'm using Angular JS. My goal is to get a list of flickr images based on location and take the image IDs returned from the request and pass them into another request to get more information for each photo to be displayed in the results. Here is what I have but I can't seem to get the correct value returned from my second search function. Although this seems like a long question, I really just want to know how to get the correct value in my second function so I can assign it to my results. </p> <p>This is in my services.js</p> <pre><code>//flickr location search APIRequest.fkrSearch = function(lat, lon, rad){ fkrAPI = $resource('https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=5956ffe850b325e0b121525800af5b31&lat='+lat+'&lon='+lon+'&radius=5km&format=json&nojsoncallback=1', { dataType: 'jsonp', jsonp: 'jsoncallback' }); return fkrAPI.get().$promise.then(function (data){ console.log(data); return data; }); }; </code></pre> <p>Here is my request within my controller.</p> <pre><code>$scope.resultPosts = []; //global variable to hold results if ($scope.locationSearch.dataSource.fkr){ $scope.fkrLoading = true; console.log('search Flickr'); OSINTAPIRequest.fkrSearch($scope.lat, $scope.lng, $scope.radius).then(function(data){ if (data.error){ toastr.error(data.error.error_msg, 'Flickr Error['+data.error.error_code+']'); } else { if (data.photos.photo.length > 0){ var fkrAppend = 0; for(var i=0; i < data.photos.photo.length; i++){ fkrAppend++; var fkrImageId = data.photos.photo[i].id; $scope.resultPosts.push({ SourcePostID: data.photos.photo[i].id, Timestamp: '', PostLatitude: $scope.fkrGetLatLng(data.photos.photo[i].id), PostLongitude: $scope.fkrGetLatLng(data.photos.photo[i].id), PostMedia: 'https://farm'+data.photos.photo[i].farm+'.staticflickr.com/'+data.photos.photo[i].server+'/'+data.photos.photo[i].id+'_'+data.photos.photo[i].secret+'.jpg', PostType: 'image', PostAvatar: 'https://pingendo.github.io/pingendo-bootstrap/assets/user_placeholder.png', PostMarker: 'assets/img/fkrMarker.png', DataSource: 'flickr', Display:$scope.resultFilter.fkr }); } </code></pre> <p>This function returns a list of the image Ids for the photos geotagged in the give lat/long, but does not return the actual location data in the results for me to pass to the results and plot the point on the map. So you'll see that in my resultsPosts.push I'm trying to pass the returned image Id to the fkrGetLatLng function with this line <code>(PostLatitude: $scope.fkrGetLatLng(data.photos.photo[i].id))</code>... the function looks like this. </p> <pre><code>$scope.fkrGetLatLng = function (fkrImageId){ OSINTAPIRequest.fkrGetLatLong(fkrImageId).then(function(data){ var fkrLat = data.photo.location.latitude; var fkrLng = data.photo.location.latitude; //console.log (fkrLat+','+fkrLng); return fkrLat; }); } </code></pre> <p>And this is the request in the services JS. I'm getting the correct data back for each request, but it's not assigning the PostLatitude the correct value (or any value at all).</p> <pre><code> //flickr location search - get lat long APIRequest.fkrGetLatLong = function(fkrImageId){ fkrAPI = $resource('https://api.flickr.com/services/rest/?method=flickr.photos.geo.getLocation&api_key=5956ffe850b325e0b121525800af5b31&photo_id='+fkrImageId+'&format=json&nojsoncallback=1', { dataType: 'jsonp', jsonp: 'jsoncallback' }); return fkrAPI.get().$promise.then(function (data){ //console.log(data); return data; }); }; </code></pre> |
14,620,400 | 0 | <p>I just wanted to put that up on SO, but this pull request should be helpful and remove the need for a separate function for numpy.dot <a href="https://github.com/numpy/numpy/pull/2730" rel="nofollow">https://github.com/numpy/numpy/pull/2730</a> This should be available in numpy 1.7</p> <p>In the meantime, I used the example above to write a function that can replace numpy dot, whatever the order of your arrays are, and make the right call to fblas.dgemm. <a href="http://pastebin.com/M8TfbURi" rel="nofollow">http://pastebin.com/M8TfbURi</a></p> <p>Hope this helps,</p> |
37,226,493 | 0 | C# how to make image move on Y axis like in slots (WPF) <p>How can i make image move on Y axis from top to bottom like in slots ? I have i my WPF this:</p> <pre><code><Border BorderBrush="Black" Margin="62,97,398,128.6" BorderThickness="2" Name="border" > <Grid> <Image Name="obrazekAutomat1" Source="cisla/2.png"/> </Grid> </Border> </code></pre> <p>I would prefer it in CodeBehind. But i think if you give me XAML i would be able to rewrite it in C#.</p> <p>Thanks :)</p> |
21,194,126 | 0 | <p>How about this? <code>window["yourfunctionname"]();</code></p> <pre><code> var FunctionName = func[before]; if (typeof(window[FunctionName]) === "function") { window[FunctionName](); } </code></pre> <p>OR </p> <pre><code> function myFunc(obj) { var func = $.parseJSON(obj); if (func[before] === "myBefore") { before();} // do some stuff if (func[after] === "myAfter") { after(); } } </code></pre> |
13,158,290 | 0 | <p>Use this code to remove the white space:</p> <pre><code>NSString *str = @"this string contains blank spaces"; NSString *newStr = [str stringByReplacingOccurrencesOfString:@" " withString:@""]; </code></pre> |
38,083,634 | 0 | Android sign in with Google APIs expires very early <p>I followed these guidelines to integrate Google sign-in into my android app: <a href="https://developers.google.com/identity/sign-in/android/sign-in#start_the_sign-in_flow" rel="nofollow">https://developers.google.com/identity/sign-in/android/sign-in#start_the_sign-in_flow</a></p> <p>When activity's <code>onStart</code> is called, it tries to sign-in again, if required information is cached and present on device, without any Internet connection. </p> <p>The problem is that it expires at almost 5 hours. And Google APIs requires Internet connection to sign in again. </p> <p>How can I increase offline persistence of sign-in information? </p> |
25,781,107 | 0 | <p>Which flume version are you using? It is fixed in V1.5.0 </p> <p>Refer : <a href="https://issues.apache.org/jira/browse/FLUME-2052" rel="nofollow">https://issues.apache.org/jira/browse/FLUME-2052</a></p> |
6,052,881 | 0 | Archiving large amounts of old data in SQL Server <p>Pretty simple question.</p> <p>I have a large 70gb database that has four of five tables that contain about 50 million rows each. These tables contain about 6 years worth of data. We are limited to amount of space in our database to 80gb, and we are going to be quickly approaching that in the next 6 months or so.</p> <p>We only need to keep about two years worth of data in the live database. What is the best approach to archiving the older data WITHOUT taking the live database offline (it's 24/7 database)?</p> <p>We are running SQL Server 2008 R2 Standard in a clustered environment using active-passive setup using shared storage.</p> <p>Thanks.</p> |
18,210,837 | 0 | <p>Where arrList is the list returned by the GetSubnetLocations function in the format above (alphabetized) </p> <pre><code>Dim arrMenu : ReDim arrMenu(-1) Dim arrLocs : ReDim arrLocs(UBound(arrList),1) i = 0 For Each x In arrList 'Also building option list here intCount = Len(x) - Len(Replace(x,"/","")) arrLocs(i,0) = x arrLocs(i,1) = intCount i = i + 1 Next Result.InnerHTML = "" ReDim Preserve arrMenu(UBound(arrMenu)+1) arrMenu(UBound(arrMenu)) = "<ul id=""menu"">" For x = 1 To UBound(arrLocs,1) Step 1 ReDim Preserve arrMenu(UBound(arrMenu)+1) arrMenu(UBound(arrMenu)) = "<li><a>" & " " & arrLocs(x,0) & "</a></li>" Next For j = 1 To UBound(arrMenu) If arrLocs(j,1) > arrLocs(j-1,1) Then arrMenu(j-1) = Replace(arrMenu(j-1),"</li>","<ul style=""display:none"">") End If If arrLocs(j,1) < arrLocs(j-1,1) Then For x = 1 To arrLocs(j-1,1) - arrLocs(j,1) arrMenu(j-1) = arrMenu(j-1) & "</li>" Next End If Next ReDim Preserve arrMenu(UBound(arrMenu)+1) arrMenu(UBound(arrMenu)) = "</ul>" strMenu = "" For Each n In arrMenu strMenu = strMenu & n Next Result.InnerHTML = strMenu </code></pre> |
15,372,328 | 0 | <p>Someone from FB says it's an expected exception, according to this bug report:</p> <p><a href="https://developers.facebook.com/bugs/122268321247958" rel="nofollow">https://developers.facebook.com/bugs/122268321247958</a></p> |
19,249,576 | 0 | <p>What about implementing a OnLayoutChangeListener that gets called when a View is moved due to Layout Change</p> <pre><code>new View().addOnLayoutChangeListener(new OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { // TODO Auto-generated method stub } }); </code></pre> <p>Excerpt from Android API:</p> <blockquote> <p>Add a listener that will be called when the bounds of the view change due to layout processing.</p> </blockquote> |
14,541,020 | 0 | <p>Maybe Uploadify is your friend here... have a read of this for more info <a href="http://markp3rry.wordpress.com/?s=uploadify&submit=Search" rel="nofollow">http://markp3rry.wordpress.com/?s=uploadify&submit=Search</a></p> |
31,631,685 | 0 | <p>You can either move/copy the Content folder under www root folder or use grunt file.js to process,combine,minify, and then copy to a folder under wwwroot. But ~/ now means wwwroot</p> |
20,727,067 | 0 | <p>I know it's so late but I had the same problem, so here's the solution below: </p> <p>To create web.xml: </p> <ol> <li>Right click on your project</li> <li>Choose New</li> <li>Choose Other </li> <li>Box New file is opened, in Filter search web.xml</li> <li>You will get the file you want web.xml, then click next...then finish</li> </ol> <p>(Tested on Netbean 7.4 JDK 7)</p> |
35,139,477 | 0 | <p>Turns out I simply had to implement this method into the viewController that holds this tableView:</p> <pre><code>override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { return "This will appear in footer styling below the section." } </code></pre> |
26,526,756 | 0 | <pre><code>char *a </code></pre> <p><code>a</code> is a pointer to something. That something is a <code>char</code></p> <pre><code>int *b </code></pre> <p><code>b</code> is a pointer to something. That something is an <code>int</code></p> <p>Both <code>a</code> and <code>b</code> are <em>pointers</em>, they only store memory addresses to other things, which is why it is possible (but definitely not reccommended; <code>warning</code> by default, <code>error</code> with <code>-wError</code>) to store the address of an <code>int</code> in a <code>char *</code>.<br> Dereferencing it is undefined behaviour and "<a href="http://www.urbandictionary.com/define.php?term=nasal%20demons" rel="nofollow">anything could happen</a>" which is why the warning/error is there in the first place.</p> <p>It <em>may</em> work with your current machine and compiler. It isn't guaranteed to though, and literally anything could break it. Don't do it</p> |
28,195,823 | 0 | Wait for certain word in teraterm <p>I am now doing some teraterm script which I want to wait for certain word (in some large string) and if the word is found then execute a command, if not found execute another command. I tried to use wait and if_else, but it's not working, please help.</p> |
33,389,208 | 0 | <p>Please try below </p> <p>yum update php*</p> <p>If you have rpm package then you can use rpm -U option to upgrade existing packages.</p> |
38,798,293 | 0 | <p>You can put the audio and video on different tracks and use the mix transition to combine the audio.</p> <pre><code># melt video.mp4 \ -audio-track -blank 100 audio.mp3 \ -transition mix in=100 out=500 a_track=0 b_track=1 </code></pre> <p>Further explanation here: <a href="https://www.mltframework.org/bin/view/MLT/MltMelt#Transitions" rel="nofollow">https://www.mltframework.org/bin/view/MLT/MltMelt#Transitions</a></p> <p>Mix transition documentation here: <a href="https://www.mltframework.org/bin/view/MLT/TransitionMix" rel="nofollow">https://www.mltframework.org/bin/view/MLT/TransitionMix</a></p> <p><strong>EDIT1:</strong></p> <p>To mute the audio from a video clip, you can apply the volume filter:</p> <pre><code># melt video.mp4 -attach-clip volume gain=0 ... </code></pre> <p>To change the volume of a clip, you can also apply the volume filter:</p> <pre><code>... -audio-track -blank 100 audio.mp3 -attache-clip volume gain=3dB ... </code></pre> <p>Volume filter documentation: <a href="https://www.mltframework.org/bin/view/MLT/FilterVolume" rel="nofollow">https://www.mltframework.org/bin/view/MLT/FilterVolume</a></p> <p>To stop the music playing, you should set an "out" point. Also, you should put all the audio clips on one track and then specify the transitions:</p> <pre><code># melt video.mp4 -attach-clip volume gain=0 \ -audio-track -blank 100 audio1.mp3 out=400 -blank 300 audio2.mp3 out=400 \ -transition mix in=100 out=500 a_track=0 b_track=1 -transition mix in=800 out=1200 a_track=0 b_track=1 </code></pre> |
27,654,734 | 0 | <p>I had a similar issue. It was not really an issue with Gmail or with PHP. The issue, in my case, was that when PHP generated the email message from my PHP source file, like the one above, it interpreted the end of lines in some way that Gmail did not like, perhaps it sent a LF instead of CRLF, some thing like that. I did not look at the details. What I know is that, given that the default on my emails was CRLF for an end of line, I wrote explicitly all end of lines using <code><?php echo "\r\n"; ?></code>, instead of relying on empty lines in the file and then Gmail interpreted correctly the message. It is likely that the issue was specific to the editor I used to write the PHP source file. In my case it was Notepad++. Perhaps it was not configured properly. It does not matter, now, just to be on the safe side, I always explicitly enter the end of lines in my email messages, at the least for the part that must be understood by MTAs and MUAs, the Content-Type, the boundary, etc. </p> |
39,165,938 | 0 | <p>Honestly, I find IDEA scarily good at reading my mind of what method I want to call next. And it usually just takes a couple letters for it to narrow down what I'm looking for pretty precisely.</p> <p>But, I think what you may be looking for is the "Sort lookup items lexicographically" option, in the Settings window under Editor / General / Code Completion. This always sorts the list by the name, rather than by predicting a few things to put at the top.</p> <p>You can read more about it and the other code completion options <a href="https://www.jetbrains.com/help/idea/2016.2/code-completion-2.html" rel="nofollow">in the IntelliJ IDEA documentation</a>.</p> <p><a href="https://i.stack.imgur.com/qRlXK.png" rel="nofollow"><img src="https://i.stack.imgur.com/qRlXK.png" alt="Screenshot of Editor / General / Code Completion / Sort lookup items lexicographically"></a></p> |
1,439,394 | 0 | <p>I find it is handy to use SQL*Plus column variables within directives - for example, I'm often in a session and want to spool to a new file name to avoid overwriting another log that may already exist and do this (first three statements through an @file):</p> <pre><code>SQL> column spr new_value spoolref SQL> select user||'_'||abs(dbms_random.random) spr from dual; SQL> spool &spoolref ... do work here ... SQL> spool off </code></pre> <p>I'll then find the new log by sorting by time - you could always use some strategy other than the random number if you prefer.</p> |
5,048,595 | 0 | <p>Probably the following will work: </p> <pre><code>Sub getData() With ... .... End With LastRowColH = Range("H65536").End(xlUp).Row ActiveSheet.Shapes.AddChart.Select ActiveChart.ChartType = xlXYScatter ActiveChart.SetSourceData Source:=Range("Sheet1!$D$3:$H$" & CStr(LastRowColH)) End Sub </code></pre> <p>HTH!</p> |
21,748,444 | 0 | How to select(fetch) all the <select> elements in jQuery <p>I want to fill in all the options for things like </p> <pre><code><select id=such_a_field> </code></pre> <p>to get the inputs in my form I can just go </p> <pre><code>$inputs = $('#myFormName :input'); </code></pre> <p>and iterate through them and set the value based on the id. For my select field, which I am now upgrading from a simple input to restrict what the user can put in, I first want to go read the set of available options (from the DB, via ajax of course), and then set the right one based on what's in the DB. Unfortunately </p> <pre><code>$selects = $('#myFormName :select'); </code></pre> <p>produces</p> <pre><code>Syntax error, unrecognized expression: unsupported pseudo: select </code></pre> <p>as of course :select isnt a pseudo selector. It would be enough just to extend my above :input selector and then enhance my field setting code to handle selects.</p> |
22,799,070 | 0 | asp.net mvc 4 accessing websecurity.Getuserid(user.identity.name) <p>I am trying to access to the user id that is currently logged on... I have two controllers, LicencaController and ProcessoController. In the ProcessoController there is a function that saves the user id and some other stuff, this function was private, but in order to gain access I have change it to public..</p> <p>Now in a function in the controller Licenca I instaciate an object ProcessoController and called the function on the ProcessoController...</p> <p>The problem is that user.identity.name is null.</p> <p>If from the ProcessoController I call the function to save the user id , user.identity.name gives me the username...</p> <p>If from the LicencaController I call the function to save the user id that is declared in the ProcessoController, it gives me null... I have tried other solutions like the one in this topic:</p> <p><a href="http://stackoverflow.com/questions/19515890/authentication-issue-when-debugging-in-vs2013-iis-express/">Authentication issue when debugging in VS2013 - iis express</a></p> <p>but it's not working... Is it possible to do this?</p> <p>What is the problem?</p> <p>Thanks in advance...</p> <p>Here goes the code:</p> <p>Fucntion SaveProcessoSoftware in the controller ProcessoProduto</p> <pre><code> public string SaveProcessoSoftware(int iIDProcesso, int iIDSoftware, int iIDTipoLicenciamento, List<string> NomeVariaveis, List<string> ValorVariaveis, string sNrFactura, string sIDLicencaInicial, string sDescricaoTipoSoftware) { int iIDFactura = GetIDFactura(sNrFactura); string sIDLicenca = SetLicenca(iIDSoftware, sIDLicencaInicial, sDescricaoTipoSoftware); ProcessoProdutos objProcSoft = new ProcessoProdutos(); objProcSoft.IDProcesso = iIDProcesso; objProcSoft.IDLicencaSoftware = sIDLicenca; objProcSoft.IDFactura = iIDFactura; objProcSoft.Rem = 0; objProcSoft.IDU = WebSecurity.CurrentUserId;// .GetUserId(User.Identity.Name); objProcSoft.TStamp = GetDateTimeFromSqlSytem(); db.ProcessoProdutos.Add(objProcSoft); db.SaveChanges(); if (NomeVariaveis != null) SaveVariaveis(sIDLicenca, iIDTipoLicenciamento, NomeVariaveis, ValorVariaveis); return sIDLicenca; } </code></pre> <p>Function SetLicenca...this is function where i save the user id...</p> <pre><code> public string SetLicenca(int iIDSoftware, string sIDLicenca, string sDescricaoTipoSoftware) { string LastTableIDLicenca = ""; Licenca Lic = new Licenca(); Lic.IDProduto = iIDSoftware; Lic.Estado = 4; Lic.Observacoes = ""; Lic.DataValidade = DateTime.MaxValue; Lic.Validado = 2; Lic.IDValidado = 0; Lic.IDTitular = 0; Lic.Rem = 0; Lic.IDU = WebSecurity.GetUserId(User.Identity.Name);<---error Lic.TStamp = GetDateTimeFromSqlSytem(); Lic.IDLicenca = new Licenciamento_v2.Areas.Idonic.IDLicencaGenerator().GenerateCharID(8); db.Licencas.Add(Lic); int t = SaveLicenca(); if (t == -1) SetLicenca(iIDSoftware, sIDLicenca, sDescricaoTipoSoftware); else { LastTableIDLicenca = Lic.IDLicenca; //obter o id introduzido e actualizar o campo idInicial if (sDescricaoTipoSoftware.Equals("Software") == true) { Lic = db.Licencas.Find(LastTableIDLicenca); if (sIDLicenca != "") { Licenca LicAnt = db.Licencas.Find(sIDLicenca); Lic.IDInicial = LicAnt.IDInicial; } else { Lic.IDInicial = LastTableIDLicenca; } db.SaveChanges(); } } return LastTableIDLicenca; } </code></pre> <p>From LicencaController i do this:</p> <pre><code> public void SaveSoftwareToLicenca() { int sessionIDProcesso = (int)Session["EditIDProcesso"]; ProcessoController procCont = new ProcessoController(); procCont.ChangeProcessoProdutoStatus(sessionIDProcesso, t.rowId, 1); procCont.ChangeLicencaEstado(t.rowId, 3); procCont.ChangeLicencaVariaveisStatus(t.rowId, 1); Session["IDLicenca"] = procCont.SaveProcessoSoftware(sessionIDProcesso, t.row.IDSoftware, t.row.IDNivelDeLicenciamento, t.row.NomeVariaveis, t.row.ValorVariaveis, t.row.NumeroFactura, t.row.IDLicenca, t.row.DescricaoTipoDeSoftware); } </code></pre> <p>Thanks again for the help..</p> |
11,736,910 | 0 | <p>I have the answer. Apparently jQuery doesn't support the <a href="http://stackoverflow.com/a/1694803/1062281">default behavior of links clicked programmatically</a> </p> <p>Creating and submitting a form works really well though (tested in <code>Chrome 26</code>, <code>FF 20</code> and <code>IE 8</code>):</p> <pre><code>var form = $("<form></form>"); form.attr( { id : "newform", action : "https://google.nl", method : "GET", target : "_blank" // Open in new window/tab }); $("body").append(form); $("#newform").submit(); $("#newform").remove(); </code></pre> <p>What it does:</p> <ol> <li>Create a form</li> <li>Give it attributes</li> <li>Append it to the DOM so it can be submitted</li> <li>Submit it</li> <li>Remove the form from the DOM</li> </ol> <p>Now you have a new tab/window loading "<a href="https://google.nl" rel="nofollow">https://google.nl</a>" (or any URL you want, just replace it). Unfortunately when you try to open more than one window at once this way, you get an Popup blocked messagebar when trying to open the second one (the first one is still opened).</p> |
31,252,223 | 0 | <p>First, <code>open()</code> is used for files. What you want is <code>opendir()</code>. Next, when you use <code>opendir(), readdir()</code>, it doesn't keep the path information, so you need to prepend it to the files you're renaming. Third, it's more common to use lexical handles as opposed to bare names. Lastly, always <code>use strict;</code> and <code>use warnings;</code> which would have pointed you directly to the problem.</p> <p>Here's a slightly updated version of your code:</p> <pre><code>#!/usr/bin/perl use warnings; use strict; my $dir = "/path/to/dir"; opendir(my $dh, $dir) or die $!; while ( my $file = readdir($dh) ) { next if ( $file =~ m/(^\.)/ ); next unless -f $file; if ( $file !~ m/csv$/ ) { print "*** renaming file $file ***\n"; my $oldfile = $file; $file =~ s/\..*$/.csv/; print "$oldfile => $file\n"; rename "$dir/$oldfile", "$dir/$file"; print "Done\n"; } } </code></pre> <p>Another way to do this is use a file glob (per suggestion by Sobrique):</p> <pre><code>#!/usr/bin/perl use warnings; use strict; my @files = </path/to/dir/*>; for my $file (@files){ next unless -f $file; if ($file !~ /\.csv$/){ print "*** renaming file $file ***\n"; my $oldfile = $file; $file =~ s/\..*$/.csv/; print "$oldfile => $file\n"; rename $oldfile, $file; print "Done!\n"; } } </code></pre> |
35,683,293 | 0 | <p>Seems like a typing mistake: you need <code>compile</code>, but not <code>complie</code>.</p> <p>That line in first gradle file: <code>complie 'org.jopendocument:jOpenDocument:1.3b1'</code></p> |
32,260,332 | 1 | Defining a constructor for ponyorm's Entities results in TypeError <p>i just wanted to try out the pony orm mapper for a small personal web application. Everything works fine except for defining a custom constructor for an entity.</p> <p>In the following code i created a simple entity with a string field <code>name</code> and defined a constructor which does nothing but redirect the arguments to the parent constructor (in my real app i change some of the arguments bevor passing them to the parent constructor). After that i create one <code>User</code> and print its name.</p> <pre><code>from pony.orm import Database, Required, db_session, commit db = Database("sqlite", ":memory:", create_db=True) class User(db.Entity): def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) name = Required(str) db.generate_mapping(create_tables=True) with db_session: u = User(name="Admin") commit() print(u, u.name) </code></pre> <p>The error message is <code>TypeError: object.__init__() takes no parameters</code> in the same line as the <code>super()</code>call. It looks like the keyword arguments are sent to <code>object</code> instead of <code>db.Entity</code>. When i remove the constructor everything works</p> <p>So why doesn't it work. Shouldn't a constructor like the one in my example just always work (and do nothing of course)? Is there something in ponyorm that prevents it from working or am i missing something here?</p> <p>For completeness sake my entity definition actually looks like this</p> <pre><code>class User(db.Entity): def __init__(self, *args, **kwargs): if "password" not in kwargs: raise ValueError("password is required") kwargs["password"] = werkzeug.security.generate_password_hash(kwargs["password"]) super().__init__(*args, **kwargs) name = Required(str) password = Required(str) </code></pre> <p>It produces the same results.</p> <p>Also in the official documentation it says that method creation in entities is allowed at least. <a href="http://doc.ponyorm.com/entities.html#adding-custom-methods-to-entities" rel="nofollow">http://doc.ponyorm.com/entities.html#adding-custom-methods-to-entities</a> . But it doesn't say anything about constructors.</p> |
26,632,199 | 0 | <p>To combine all three of the above answers, you need the stopwords_en.txt as it begins testing for English language text</p> <p>From <a href="http://wiki.apache.org/solr/LanguageAnalysis#Stopwords" rel="nofollow">http://wiki.apache.org/solr/LanguageAnalysis#Stopwords</a></p> <blockquote> <p>Stopwords affect Solr in three ways: relevance, performance, and resource utilization.</p> <p>From a relevance perspective, these extremely high-frequency terms tend to throw off the scoring algorithm, and you won't get very good results if you leave them. At the same time, if you remove them, you can return bad results when the stopword is actually important.</p> <p>From a performance perspective, if you keep stopwords, some queries (especially phrase queries) can be very slow.</p> <p>From a resource utilization perspective, if you keep stopwords, the index is much larger than if you remove them.</p> <p>One tradeoff you can make if you have the disk space: You can use CommonGramsFilter/CommonGramsQueryFilter instead of StopFilter. This solves the relevance and performance problems, at the expense of even more resource utilization, because it will form bigrams of stopwords to their adjacent words.</p> </blockquote> <p>What you need to do is copy the original version located in the /conf/lang folder of your solr directory into just the /conf directory</p> <pre><code>cp PATH/TO/solr/conf/lang/stopwords_en.txt PATH/TO/solr/conf </code></pre> |
40,752,236 | 0 | Xpath Parsing part of name contains white space and special character <p>I have the xml line below:</p> <pre><code><Custom AttributeName="HHPP">ancd</Custom> </code></pre> <p>I want to parse the HHPP part form name, what is the xpath expression to do that?</p> |
15,276,947 | 0 | <p>This code snippet creates a new presentation:</p> <pre><code> private void DpStartPowerPoint() { // Create the reference variables PowerPoint.Application ppApplication = null; PowerPoint.Presentations ppPresentations = null; PowerPoint.Presentation ppPresentation = null; // Instantiate the PowerPoint application ppApplication = new PowerPoint.Application(); // Create a presentation collection holder ppPresentations = ppApplication.Presentations; // Create an actual (blank) presentation ppPresentation = ppPresentations.Add(Office.MsoTriState.msoTrue); // Activate the PowerPoint application ppApplication.Activate(); } </code></pre> <p>And this code snippet saves it:</p> <pre><code> // Assign a filename under which to save the presentation string myFileName = "myPresentation"; // Save the presentation unconditionally ppPresentation.Save(); // Save the presentation as a PPTX ppPresentation.SaveAs(myFileName, PowerPoint.PpSaveAsFileType.ppSaveAsDefault, Office.MsoTriState.msoTrue); // Save the presentation as a PDF ppPresentation.SaveAs(myFileName, PowerPoint.PpSaveAsFileType.ppSaveAsPDF, Office.MsoTriState.msoTrue); // Save a copy of the presentation ppPresentation.SaveCopyAs(“Copy of “ + myFileName, PowerPoint.PpSaveAsFileType.ppSaveAsDefault, Office.MsoTriState.msoTrue); </code></pre> <p>See <a href="http://www.davidallenpollock.com/AutomatingPowerPoint.html" rel="nofollow">this page</a> for references on other powerpoint automation capabilities.</p> |
23,568,649 | 0 | <p>you don't have a variable: '[ || test || ]' is a string. you need this one '[' || test || ']'</p> |
603,558 | 0 | <p>It is probably the McAfee on-access scanner that holds the lock. If you only use read access, it is bypassed. I believe that you can use the Sysinternals Process Viewer tool (free from Microsoft) to confirm that.</p> <p>Not sure what subscription you have for McAfee, but you can define exception rules so that it does not scan this file.</p> |
23,212,466 | 0 | 32feet bluetooth c# which exception thrown when connected device switch off? <p>I am developing a bluetooth application in c# to read data from sensors using 32feet.net library. I am able to communicate with sensors and able to read values , send command etc. The Communicating thread will either be waiting in read or writing command to the sensor. I expected that an IOException will be thrown when sensors suddenly powers off. but never got exception.</p> <p>Need help to figure out What kind of exception will be thrown when the sensors suddenly powers off? </p> |
3,451,451 | 0 | Why do people spend so much time searching for, and hacking around with, "free" toolsets when superior pay ones are available? <p><strong>Clarification:</strong> I'm referring to companies that pay developers, professionally. I understand why a "hobby" or "for fun" developer wouldn't want to (or couldn't afford) a fully-features pay tool, and may prefer to tinker. I'm talking about situations where a deadline is bearing down on a developer/company and development time is diverted away from the goal in pursuit of a "Free" tool to accomplish what a pay one is available to do.</p> <hr> <p>I've noticed a number of Stack Overflow questions recently (they're not new, I've just recently taken notice) where people are searching for free alternatives to popular development tools for things like <a href="http://en.wikipedia.org/wiki/Application_lifecycle_management" rel="nofollow noreferrer">ALM</a>, database comparison, and other functions for which there's a trivially costly pay alternative. The "Free" tag on Stack Overflow has 350 questions, and it doesn't take long to see dozens of examples of "Is there a FREE tool to do X?" followed by discussions that must have taken the asker hours to research and participate in.</p> <p>It's not just about paying less - I'm often amazed at the hoops that some developers (or, perhaps more accurately, their companies) will go through to avoid paying for something - in some cases, a pay solution will be avoided in favor of a poorly documented, buggy, feature-incomplete open-source solution that results in dozens of hours of work that could have been avoided.</p> <p>I understand the most obvious reasons:</p> <ul> <li>Company is short on cash</li> <li>Don't pay for something when a (functionally-comparable) free alternative is available</li> <li>"Hobby" developers don't have the cash to spare, and since they're just learning, it doesn't make sense to pay for a toolset they're only tinkering with</li> </ul> <p>However, I think the "short on cash" reasoning is completely bogus - as a developer not long out of college, I made about $50K annually, or $200/day (meaning my company probably paid close to $300/day to have me in my chair, all considered). When you compare that price to a $300 tool, the obvious answer is "if it's going to waste more than a day of your time, you should buy it instead and get back to work". However, that's not what I observe - people seem willing to kill dozens of hours to avoid paying for something that only costs $50.</p> <p>Help me understand - as a developer myself of tools I'd like to one day sell, I want to understand the mentality. Have I been spoiled by working at a company that's not afraid to spend? Is there an ingrained reason developers (or their companies) don't want to spend money? Can people not accurately estimate the costs of "Free" tools in terms of lost productivity?</p> <hr> <p>I'm not referring to instances where a great free alternative is available. For example, <a href="http://stackoverflow.com/questions/662956/most-useful-free-net-libraries">any of these tools</a> is a great example of something you shouldn't pay for. However, let's say one of those lacks a key feature you need, and which a pay version of the same library provides - people seem to lean towards hacking around with the free version to add the needed functionality (or scaffold in the needed functionality) instead of ditching the free tool in favor of the pay (and feature-complete) version. I'm not saying that's the wrong choice, but it's just a choice I want to understand the reasoning to. The important point is that I'd like to - my intent is not to be argumentative.</p> |
35,127,826 | 0 | <p>In your code you have:</p> <pre><code>html "<a href=" $ { link } ">Activate your account on Kunega</a>" </code></pre> <p>which I suppose should be either:</p> <pre><code>html "<a href=\""+ link + "\">Activate your account on Kunega</a>" </code></pre> <p>or </p> <pre><code>html "<a href=\"${ link }\">Activate your account on Kunega</a>" </code></pre> <p>otherwise you call a method <code>html</code> with params <code>"<a href="</code>, <code>$</code>, <code>{ link }</code> (closure that returns "link") and <code>">Activate your account on Kunega</a>"</code>.</p> |
5,067,745 | 0 | PostgreSQL - use previously computed value from same query <p>I have the following sql query:</p> <pre><code>SELECT (SELECT ...) AS X, (SELECT ...) AS Y from my_table </code></pre> <p>'X' is quite hard to compute, and it's used as an input for computing Y. However, if I try to reference X within the query that computes Y or even within the main query I get the following error message:</p> <pre><code>Error: column "X" does not exist </code></pre> <p>Is there any way to reference X once it is computed? I really don't want to compute it twice, as this seems very inefficient.</p> |
18,973,796 | 0 | <p>Create new iterator</p> <pre><code> bson_iterator nInterat[1]; </code></pre> <p>below subit iterator</p> <pre><code>bson_iterator subit[1]; bson_iterator nInterat[1]; </code></pre> <p>instead of this </p> <pre><code>bson_iterator_subobject_init(subit, sub_Object,1) </code></pre> <p>change like </p> <pre><code>bson_iterator_subobject_init(nInterat, sub_Object,1) if(bson_find(nInterat, sub_Object, "name")) printf("\tName : %s\n", bson_iterator_string(nInterat)); if(bson_find(nInterat, sub_Object, "telephone")) printf("\tTelephone: %s\n", bson_iterator_string(nInterat)); </code></pre> <p>because your subit iterator is overwrite with current sub_object Index </p> |
2,204,656 | 0 | <p>This issue was resolved. I didn't know that when using pylons from the CLI, I have to include the entire environment:</p> <pre><code>from paste.deploy import appconfig from pylons import config from project.config.environment import load_environment conf = appconfig('config:development.ini', relative_to='.') load_environment(conf.global_conf, conf.local_conf) from project.model import * </code></pre> <p>After this the database queries executed without a problem.</p> |
8,468,976 | 0 | <p>I am by no means an expert — when HQL stymies me, I rarely have qualms about bypassing the problem by switching to straight SQL — so I can't tell you if there is a better, more HQL-ish way to do this. But in your specific instance, where <code>B.marker</code> is always either <code>0</code> or <code>1</code>, I suppose you <em>could</em> change</p> <pre><code>COUNT(CASE WHEN B.marker = 1 THEN 1 ELSE NULL END) </code></pre> <p>to</p> <pre><code>SUM(B.marker) </code></pre> <p>and </p> <pre><code>COUNT(CASE WHEN B.marker = 0 THEN 1 ELSE NULL END) </code></pre> <p>to</p> <pre><code>COUNT(*) - SUM(B.marker) </code></pre> <p>(though you <em>may</em> also need to wrap your <code>SUM</code>s in <code>COALESCE(..., 0)</code> — I'm not sure).</p> |
7,677,562 | 0 | What's the difference between argp and getopt? <p>I think the title is self explanatory. I am making a program and I was wondering what I should use of the two and why.</p> |
4,993,060 | 0 | Submitting a form to a new window using JavaScript - with Strict DocType <p>Ok, so here's my code for submitting the form:</p> <pre><code>document.forms['formid'].submit(); </code></pre> <p>The Form Target attribute is deprecated for the DocType I'm using - </p> <p><a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" rel="nofollow">http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd</a></p> <p>and I really don't want to use a different DocType as a work around for something so simple - so what are my options for submitting to a new window?</p> |
36,924,214 | 0 | Identify and count array duplicates <p>I have the following array:</p> <pre><code>var newOrderItems = [Order]() </code></pre> <p>that holds Order type elements:</p> <pre><code>let order = Order(item: itemName, quantity: 1) newOrderItems.append(order!) </code></pre> <p>At some point newOrderItems holds:</p> <pre><code>[ Order("item1", 1), Order("item1", 1), Order("item2", 1), Order("item2", 1), Order("item3", 1), Order("item1", 1) ] </code></pre> <p>I need to identify and count duplicate Order array elements so that I form a string message such as: </p> <p>"You have ordered 3 x item1, 2 x item2, 1 x item3".</p> <p>Is there a simple way for this? My solution(s) either add way too much overhead (i.e nested loops), or too much complexity (i.e. unique <code>NSCountedSet</code>) for something that I expect to be trivial.</p> |
1,308,119 | 0 | <p>Not sure...I learned the 2 technologies by writing a facebook API based on WCF and writing a WPF frontend to browse the albums of my friends. My reasoning was that if WCF can do form-encoded POSTs with bare XML responses then it should be up for a lot of things.</p> |
26,542,624 | 0 | <p>I've done similar thing once. Unfortunately Report Studio can't create prompts (and variables) dynamically. You can construct your set of prompts using JavaScript. Not Cognos prompts. HTML EditBoxes. Then carefully pass values from EditBoxes to real hidden prompt as text.</p> |
7,437,875 | 0 | <p>You should do basic connectivity tests, to determine what exactly that network is blocking. </p> <p>Start with a simple ping and move on to UDP and TCP levels. You might find that some form of communication is allowed.</p> <p>If not, you can try to tell their security guys to accept some form of communication between specific range of ip addresses and/or port numbers and adapt your application accordingly.</p> |
36,883,973 | 0 | html5 multiple file upload with spring mvc 4 and spring boot <p>I'm trying to upload multiple files using spring mvc 4, spring boot and thymeleaf as template engine, but i'm not able to access the uploaded files, the files are dealt with as one multipart file with content type application/octet-stream. here's my front-end code:</p> <pre><code> <form name="offer-form" th:action="@{/submit-property}" method="POST" enctype="multipart/form-data"> <!-- .. other inputs .. --> <div class="col-xs-12 margin-top-60"> <input id="file-upload"name="files[]" type="file" multiple="multiple"/> </div> <div class="col-xs-12"> <div class="center-button-cont margin-top-60"> <button type="submit" class="button-primary button-shadow"> <span>submit property</span> <div class="button-triangle"></div> <div class="button-triangle2"></div> <div class="button-icon"><i class="fa fa-lg fa-home"></i></div> </button> </div> </div> </form> </code></pre> <p>And the controller code:</p> <pre><code>import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.aq.domain.Property; import com.aq.service.AddPropertyFormDataInitializerService; @Controller public class PorpertySubmissionController { public static final Resource PICTURES_DIR = new FileSystemResource("./uploadedPictures"); //some unrelated code @RequestMapping(value="/submit-property", method=RequestMethod.GET) public String getSubmitPropertyForm(Model model) { model.addAttribute("property", new Property()); return "submit-property"; } @RequestMapping(value="/submit-property", method=RequestMethod.POST) public String submitProperty ( @ModelAttribute(value="property") Property property, @RequestParam("files[]") MultipartFile[] uploadedImages ) { //some unrelated code if(uploadedImages != null && uploadedImages.length > 0) { System.out.println("uploadedImages length: " + uploadedImages.length); for(MultipartFile imageFile : uploadedImages) { try { copyFileToPictures(imageFile); System.out.println("copied File: " + imageFile.getOriginalFilename() + " successfully."); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } } } else { System.out.println("no images were uploaded"); } return "redirect:/submit-property"; } private Resource copyFileToPictures(MultipartFile file) throws IOException { System.out.println("File Original Name: " + file.getOriginalFilename()); System.out.println("File Name: " + file.getName()); System.out.println("File size: " + file.getSize()); System.out.println("File Content type: " + file.getContentType()); String fileExtension = getFileExtension(file.getOriginalFilename()); File tempFile = File.createTempFile("pic", fileExtension, PICTURES_DIR.getFile()); try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(tempFile)) { IOUtils.copy(in, out); } return new FileSystemResource(tempFile); } private static String getFileExtension(String name) { return name.substring(name.lastIndexOf(".")); } } </code></pre> <p>the output of the sysout:</p> <p>uploadedImages length: 1 (even though i upload multiple files)</p> <p>File Original Name (using getOriginalFileName): </p> <p>File Name (using getName): files[]</p> <p>File size: 0</p> <p>File Content type: application/octet-stream</p> <p>and then an exception when subsctring is called on the empty original file name.</p> <p>I tried to add commons file upload to my POM and configured CommonsMultipartResolver bean, but then it always prints that there are no uploaded images (which means it's null or length=0)</p> |
16,395,726 | 0 | <p>Unlike what everyone else tells you, this is unrelated to Windows and <code>File.separator</code>.</p> <p><code>String DIR_PATH = "a/b/c/"</code> is just a String, neither Java nor the compiler make any attempt to understand what it could mean, so you get the same value both on Windows and Linux.</p> <p>Also note that <code>/</code> works as a file separator both on Unix and Windows, so this isn't an issue either. When necessary, Java will convert <code>/</code> to <code>\</code>.</p> <p><code>File DIR_FILE = new File(DIR_PATH);</code> is a constant but <code>new File()</code> is still executed by the VM at runtime when the class is loaded. So the path is <strong>not</strong> converted to Windows format while the <em>compiler</em> generates byte code.</p> <p>So the problem you describe must be elsewhere or an important part of the code example you posted was changed when you simplified it for the question. My guess is that someone put a Windows-style path into the code elsewhere or maybe the config and you overlooked this.</p> <p>That said, a safe way to build paths is to use <code>File(File, String)</code>:</p> <pre><code>File DIR_PATH = new File( "a", new File( "b", "c" ) ); </code></pre> <p>This will always build a path that works, no matter what the file separator is. If you must, you can use</p> <pre><code>File DIR_PATH = "a" + File.separator + "b" + File.separator + "c"; </code></pre> <p>but that can fail for more complex examples and it's more text to read.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.