text
stringlengths
64
89.7k
meta
dict
Q: How can I use styled components for an element that doesn't appear on initial render? I have found that styled components, when not included in the initial render tree, present without the correct CSS. Here is one example: I have a paginated 'wizard' interface, which shows back and next buttons. On the first page, there is no back button for obvious reasons. However, presumably because the back button doesn't get its conditional CSS rendered initially, styled components does not set up a class for it. On subsequent pages, the back button appears without any styling at all: <ButtonRow> {canGoBack && ( <Button text='Back' /> )} {canAdvance && ( <Button primary leftSpaced text='Next' /> )} </ButtonRow> canGoBack = false on first render, true after the user advances. But after advancing, the back button appears with no CSS at all, just an out-of-the-box HTML button. I realize I could do something like giving the secondary button 0 opacity rather than leaving it out of the render tree entirely, but there are other contexts where I would like to change the render tree depending on state, and I can't figure out how to get styled components to work in such scenarios. Here is the Button class: import React, { Component } from 'react'; import styled, { css } from 'styled-components'; const StyledButton = styled.button` font-size: 11px; font-weight: 500; letter-spacing: 1px; text-transform: uppercase; border-radius: 20px; padding: 9px 44px 8px; display: flex; justify-content: center; align-items: center; ${props => props.primary ? css` color: #FFF; box-shadow: 0 1px 2px 0 #A0A0A0; background-color: #3E8FF6; ` : css` color: #555; box-shadow: 0 1px 2px 0 #F0F0F0; background-color: #FFF; `} ${props => props.leftSpaced && css` margin-left: 6px; `} &:focus { outline: 0; } `; export default class Button extends Component { render() { return ( <StyledButton onClick={this.didClick} primary={this.props.primary} type={this.props.type || 'button'} leftSpaced={this.props.leftSpaced}>{this.props.text}</StyledButton> ) } } A: Thanks to Oluwafemi Sule's help, I was able to get to the bottom of this problem. This was a very, very specific conflict, not a general issue. In my project, I am using a plugin to cytoscape, cytoscape-node-html-label (https://github.com/kaluginserg/cytoscape-node-html-label), which appears to write style tags in conflict with styled-components. As soon as I disable it, my styled components render perfectly as in Oluwafemi's demo in the comments.
{ "pile_set_name": "StackExchange" }
Q: My jquery code for the hijacked iframe image upload is working in FF, not Safari. Any ideas? Can anyone see why this would work in FF but not Safari? When I alert the return from my CF script that processes the image and returns the image name it works in FF. No go in Safari... $( "#uploadform" ).submit(function( objEvent ){ //alert("Submit"); var jThis = $( this ); var strName = ("uploader" + (new Date()).getTime()); var jFrame = $( "<iframe name=\"" + strName + "\" src=\"about:blank\" />" ); jFrame.css( "display", "none" ); jFrame.load(function( objEvent ){ var objUploadBody = window.frames[ strName ].document.getElementsByTagName( "body" )[ 0 ]; var jBody = $( objUploadBody ); var objData = eval(jBody.html()); var thumb = ('holding/' + eval(jBody.html())); setTimeout(function(){ jFrame.remove(); },100); if (objData !== '') { // Put the preview here and load another form that has a hidden element capturing the image name // then use a button to save the image, close the window and update the database with all the info // and relaod the main page with a location.reload $('#imagePreview').attr('src', thumb ); $('#imageName').html(thumb); $('#imagePreview').click(function(){ rebinder(); }); } else { alert("no thumbnail"); } }); $( "body:first" ).append( jFrame ); jThis .attr( "action", "upload_act_single.cfm" ) .attr( "method", "post" ) .attr( "enctype", "multipart/form-data" ) .attr( "encoding", "multipart/form-data" ) .attr( "target", strName ); }); I'm thinking I must have some syntax errors messing up the works but I'm new enough to this to not see it. When I use the alert to call out the objData variable it says 'undefined' in Safari. It acts like it doesn't even run the CF script... Thank you in advance for any help. A: Instead of using about:blank, try to create your own empty HTML with the body tag. I did a view source in Safari 4 (windows) and Chrome. about:blank source has nothing in it unlike IE or Firefox which has HTML in it. Try to alert(objUploadBody) to see if you get anything it in too.
{ "pile_set_name": "StackExchange" }
Q: Typescript file upload validation I'm trying to upload a file but i get an error for the following code. The error is property does not exist on type HTML Element. How to resolve this? I have commented the error for the following line of code. component.html <input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();"/> <ul> <label>Select a Module Name</label> <select id = "ModuleDropDown"> <option value="">Select</option> <option value="Recuirtmnet">Recuirtmnet</option> <option value="Talent" selected="selected">Talent</option> <option value="Attrition">Attrition</option> <option value="Performance">Performance</option> <option value="Survey">Survey</option> </select> </ul> <div id="fileName"></div> <div id="fileSize"></div> <div id="fileType"></div> component.ts fileSelected() { //Property 'files' does not exist on type 'HTMLElement' let file = document.getElementById('fileToUpload').files[0]; if (file) { let fileSize = 0; if (file.size > 1024 * 1024) this.fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'; else this.fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'; document.getElementById('fileName').innerHTML = 'Name: ' + file.name; document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize; document.getElementById('fileType').innerHTML = 'Type: ' + file.type; let dropDown = document.getElementById("ModuleDropDown"); //Property 'options' does not exist on type 'HTMLElement'. //Property 'selectedIndex' does not exist on type 'HTMLElement' let dpVal = dropDown.options[dropDown.selectedIndex].value; let init_params = {}; this.init_params.action = 'prepare'; this.init_params.file_name = file.name; this.init_params.file_size = fileSize; this.init_params.moduleName = dpVal; ws.send(JSON.stringify(init_params)) console.log("sending init params.....") } } A: There are a lot of issues with your code. You're using Vanilla JavaScript instead of leveraging the Angular Syntax. The change on the File Input can be tracked using (change) and passing an $event Object to the Change Handler. You can use [(ngModel)] to get the value of the selected option from the dropdown. It's not advisable to use document to access the DOM and make changes to it or show data to it. You should use the String Interpolation Syntax({{}}) instead. Here's a Sample StackBlitz for your ref. Select an Option and then Upload a File to see the Selected File Details on the UI and the Selected Dropdown Option on the console.
{ "pile_set_name": "StackExchange" }
Q: How can I manually override managed version for Aluminum SR-1? Definitely Not A Duplicate. The provided link is possibly a general solution to a problem that resembles this one, but is not directly related. The duplicate link isn't helpful. After some investigation I've discovered that it's due to a breaking change in Aluminum SR-1: https://github.com/spring-projects/spring-framework/commit/c85f063d92d1d6ac0daa134ac4b64dac2c218182 There was a breaking update last night and I'm wondering if it is possible to override the dependency in my pom file to call version 1.4.x for Springboot? What would the markup be and where do I put it? [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 3.035 s [INFO] Finished at: 2017-02-22T10:53:28+01:00 [INFO] Final Memory: 18M/218M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal on project tmt: Could not resolve dependencies for project cz.nnit:tmt:war:0.0.1-SNAPSHOT: Failed to collect dependencies at org.springframework.boot:spring-boot-starter-security:jar:2.0.0.BUILD-SNAPSHOT -> org.springframework.boot:spring-boot-starter:jar:2.0.0.BUILD-SNAPSHOT -> org.springframework.boot:spring-boot:jar:2.0.0.BUILD-SNAPSHOT -> org.springframework:spring-core:jar:5.0.0.BUILD-SNAPSHOT: Failed to read artifact descriptor for org.springframework:spring-core:jar:5.0.0.BUILD-SNAPSHOT: Failure to find io.projectreactor:reactor-bom:pom:Aluminium-SR1 in https://repo.spring.io/snapshot was cached in the local repository, resolution will not be reattempted until the update interval of spring-snapshots has elapsed or updates are forced -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal on project tmt: Could not resolve dependencies for project cz.nnit:tmt:war:0.0.1-SNAPSHOT: Failed to collect dependencies at org.springframework.boot:spring-boot-starter-security:jar:2.0.0.BUILD-SNAPSHOT -> org.springframework.boot:spring-boot-starter:jar:2.0.0.BUILD-SNAPSHOT -> org.springframework.boot:spring-boot:jar:2.0.0.BUILD-SNAPSHOT -> org.springframework:spring-core:jar:5.0.0.BUILD-SNAPSHOT at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies(LifecycleDependencyResolver.java:221) at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies(LifecycleDependencyResolver.java:127) at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved(MojoExecutor.java:245) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:199) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288) at org.apache.maven.cli.MavenCli.main(MavenCli.java:199) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356) at org.codehaus.classworlds.Launcher.main(Launcher.java:47) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) Caused by: org.apache.maven.project.DependencyResolutionException: Could not resolve dependencies for project cz.nnit:tmt:war:0.0.1-SNAPSHOT: Failed to collect dependencies at org.springframework.boot:spring-boot-starter-security:jar:2.0.0.BUILD-SNAPSHOT -> org.springframework.boot:spring-boot-starter:jar:2.0.0.BUILD-SNAPSHOT -> org.springframework.boot:spring-boot:jar:2.0.0.BUILD-SNAPSHOT -> org.springframework:spring-core:jar:5.0.0.BUILD-SNAPSHOT at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:180) at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies(LifecycleDependencyResolver.java:195) ... 29 more Caused by: org.eclipse.aether.collection.DependencyCollectionException: Failed to collect dependencies at org.springframework.boot:spring-boot-starter-security:jar:2.0.0.BUILD-SNAPSHOT -> org.springframework.boot:spring-boot-starter:jar:2.0.0.BUILD-SNAPSHOT -> org.springframework.boot:spring-boot:jar:2.0.0.BUILD-SNAPSHOT -> org.springframework:spring-core:jar:5.0.0.BUILD-SNAPSHOT at org.eclipse.aether.internal.impl.DefaultDependencyCollector.collectDependencies(DefaultDependencyCollector.java:291) at org.eclipse.aether.internal.impl.DefaultRepositorySystem.collectDependencies(DefaultRepositorySystem.java:316) at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:172) ... 30 more Caused by: org.eclipse.aether.resolution.ArtifactDescriptorException: Failed to read artifact descriptor for org.springframework:spring-core:jar:5.0.0.BUILD-SNAPSHOT at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:329) at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.readArtifactDescriptor(DefaultArtifactDescriptorReader.java:198) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.resolveCachedArtifactDescriptor(DefaultDependencyCollector.java:535) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.getArtifactDescriptorResult(DefaultDependencyCollector.java:519) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:409) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:363) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.process(DefaultDependencyCollector.java:351) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.doRecurse(DefaultDependencyCollector.java:504) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:458) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:363) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.process(DefaultDependencyCollector.java:351) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.doRecurse(DefaultDependencyCollector.java:504) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:458) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:363) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.process(DefaultDependencyCollector.java:351) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.doRecurse(DefaultDependencyCollector.java:504) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:458) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:363) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.process(DefaultDependencyCollector.java:351) at org.eclipse.aether.internal.impl.DefaultDependencyCollector.collectDependencies(DefaultDependencyCollector.java:254) ... 32 more Caused by: org.apache.maven.model.resolution.UnresolvableModelException: Failure to find io.projectreactor:reactor-bom:pom:Aluminium-SR1 in https://repo.spring.io/snapshot was cached in the local repository, resolution will not be reattempted until the update interval of spring-snapshots has elapsed or updates are forced at org.apache.maven.repository.internal.DefaultModelResolver.resolveModel(DefaultModelResolver.java:177) at org.apache.maven.model.building.DefaultModelBuilder.importDependencyManagement(DefaultModelBuilder.java:1192) at org.apache.maven.model.building.DefaultModelBuilder.build(DefaultModelBuilder.java:455) at org.apache.maven.model.building.DefaultModelBuilder.build(DefaultModelBuilder.java:421) at org.apache.maven.model.building.DefaultModelBuilder.build(DefaultModelBuilder.java:411) at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:320) ... 51 more Caused by: org.eclipse.aether.resolution.ArtifactResolutionException: Failure to find io.projectreactor:reactor-bom:pom:Aluminium-SR1 in https://repo.spring.io/snapshot was cached in the local repository, resolution will not be reattempted until the update interval of spring-snapshots has elapsed or updates are forced at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:444) at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:246) at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifact(DefaultArtifactResolver.java:223) at org.apache.maven.repository.internal.DefaultModelResolver.resolveModel(DefaultModelResolver.java:173) ... 56 more Caused by: org.eclipse.aether.transfer.ArtifactNotFoundException: Failure to find io.projectreactor:reactor-bom:pom:Aluminium-SR1 in https://repo.spring.io/snapshot was cached in the local repository, resolution will not be reattempted until the update interval of spring-snapshots has elapsed or updates are forced at org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.newException(DefaultUpdateCheckManager.java:231) at org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.checkArtifact(DefaultUpdateCheckManager.java:206) at org.eclipse.aether.internal.impl.DefaultArtifactResolver.gatherDownloads(DefaultArtifactResolver.java:585) at org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:503) at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:421) ... 59 more [ERROR] [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException A: Workaround for solving this problem ... exclude all libraries, that has Aluminium-SR1 as dependency. I'm finally able to compile with this pom: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-boot-starter-aop</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-boot-starter-aop</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </exclusion> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </exclusion> </exclusions> </dependency>
{ "pile_set_name": "StackExchange" }
Q: Tidal Power Gen Multiplier? Regarding tidal power generation, the following scheme uses an outer tank and an inner tank that floats on the water of the inner tank. You fill the inner tank first (while it's at high-tide level) and then fill the second tank which raises the innner tank doubling it's potential energy. Question: Would this work? UPDATE: I think it may be important to consider that water pouring into the tank looses energy. Meaning the water at the bottom of the tank has less energy than at the top. So it could be that this mechanism captures some of that energy that would otherwise be lost. Also, the issue does not appear to be buoyancy since force of 1L of water = force of 1L of air in water = 9.8N. So that's not the problem. A: Much to my surprise I think that this does work. However you only get a finite possible benefit from it, even when iterated of course. I also may be wrong somewhere: I would welcome someone pointing out why the following is wrong! So, here is what I think the situation you are describing. There are two tanks which we assume fit closely inside each other (this is just to simplify the maths), and they each have height $H$ and cross-sectional area $A$ (so the inner one has area $A-\Delta A$ if you like so it fits inside the outer one, and $\Delta A$ is small). The inner tank has a partition half way up it, with a tap. Both tanks have taps in their bases (which is how you get the water out to get power) and both tanks have open tops to allow water to flood in. The outer tank is attached to the ground (ie it does not float away), the inner tank isn't. The tanks are light (so I can neglect their mass which will reduce the efficiency of the thing as you have to lift them). At high tide the water level is at or above the top of the tanks, and at low tide it is at or below the bottoms of them. There is lots of water, the density of the water is $\rho$. So, OK, let's just consider the outer tank first of all, with no inner tank. At high tide it fills with water, and at low tide the water is allowed to drain out and do work. How much work does it do? Well, each little disk of water of thickness $\delta h$ at height $h$ does work $(\rho A\delta h) \times g h)$, so the total work we can get from the thing is $$ \begin{align} W_1 &= \int\limits_0^H \rho A g h\,dh\\ &= \frac{\rho A g H^2}{2} \end{align} $$ So, now consider the trick you suggest: place the tanks one inside the other, with all the taps closed; fill the top of the inner tank from the tide (so the inner tank is now half full); now fill the outer tank, raising the inner tank up by half its height; wait for the tide to go out. Now how much work can we get from this? Well to get work out of it: open the tap in the partition of the inner tank, allowing the water to flow into the bottom half of it -- trivially this does work $\rho AgH^2/4$ (the mass of water is $\rho AH/2$, and it falls a distance $H/2$); now open all the taps and let the water run out as before, doing $\rho AgH^2/2$ again. So, now $$ \begin{align} W_2 &= \frac{\rho AgH^2}{2} + \frac{\rho agH^2}{4}\\ &= \frac{3\rho AgH^2}{4}\\ &= \frac{3}{2}W_1 \end{align} $$ And this is more than $W_1$. Well, we can iterate this with a third tank. But the third tank can only be half as high as the second one as it needs to float in the second tank. And we can repeat this, of course: $$ \begin{align} W_1 &= \rho A g H^2\frac{1}{2}\\ W_2 &= \rho A g H^2\frac{1}{2} + \frac{1}{4}\\ W_3 &= \rho A g H^2\frac{1}{2} + \frac{1}{4} + \frac{1}{8}\\ &\cdots\\ W_\infty &= \rho A g H^2\sum\limits_{n=1}^\infty \frac{1}{2^n}\\ &= \rho A g H^2 \end{align} $$ This is the ideal case: in real life the tanks must get smaller in radius so they fit inside each other and will not be massless. As I said: I'm not convinced by this answer: I feel I must have made a mistake somewhere.
{ "pile_set_name": "StackExchange" }
Q: does workbench has access to actual data in the salesforce org does workbench access actual data in the salesforce org ? does workbench access only metadata. specifically does the workbench store the org data in its servers? A: No, the data is not stored by workbench. If you're curious, you can read the source code. Salesforce.com takes your data seriously, and would not violate customers' trust in this manner. You can also host your own copy of workbench, since the source code is available for reuse and modification.
{ "pile_set_name": "StackExchange" }
Q: How can I easily encrypt a file? Is there any simple (IE: right click in Nautilus) way to password protect a particular folder/file in Ubuntu? I've got a few files containing sensitive info and I'd much prefer that if/when I leave my computer alone, they aren't accidentally accessed by someone else. The secruty does not have to be extremely tight. My only concern is that when family/friends come over, I don't really like the idea of them looking at my bank details, accounts or, you guessed it, porn collection. A simple, effective way to let me put my machine in the hands of someone else knowing that said machine can not cause me embarresment is the sole reason why I'd like to see this in Ubuntu. A: You can use the Archive Manager to zip the file and password protect the zip file. That is probably the closest thing to right clicking and entering a password that you describe. To do this right click on the file and choose "Compress" then choose zip as the archive type and in "Other options" you have the option to enter a password. This is simple to do and stops the problem of someone mounting the file system from a live CD and getting the file that way. Also you can easily email the file or copy to USB stick, etc without having to worry about having the means to unencrypt the files at the other end, you just need the password. A: As many pointed out, access control based on user id and encrypted filesystem is the only real way of securing user data. If, however, all that is stopping you from using Truecrypt is because you don't have a free partition / filesystem that you can use exclusively for storing encrypted data, then you can still make an encrypted file-system inside a file within your existing filesystem. For this you need to have "sudo" rights, i.e., you must be able to run sudo. Get the latest version of truecrypt Open TrueCrypt (normally found in Applications -> Accessories) Using the gui you can create a new volume contained in a file. You can choose the location of this file. Steps 1-3 are one-time setup. After this whenever you mount this file-system using truecrypt GUI, you will see it in nautilus. You can move the sensitive files and directories within this filesystem. When "you are leaving your computer alone", unmout this using the "dismount" option in the truecrypt GUI. It is also important to use a good password (more than 20 characters at least, as recommended by the developers). A: If you want to encrypt a lot of files that you access regularly, an encrypted filesystem is the way to go. But if you have single files that you want to encrypt/decrypt quite rarely (say, a list of passwords) you can do it very easily with a right-click in nautilus: Install the seahorse-plugins package Create a new key for GPG/PGP (Applications - Accessories - Passwords and Encryption Keys) After a restart of nautilus (enter nautilus -q in a terminal or simply log out of your GNOME session) you have two new entries in your right-click menu: Encrypt and Sign, respectively Decrypt for encrypted files
{ "pile_set_name": "StackExchange" }
Q: Find matches in 2 columns, compare data in third column with VBA I am hoping someone can help. I am comparing prices of products between a master sheet and a local sheet. I need to flag when the prices don't match. The master sheet contains all possible products but the local sheets do not, so first I need to match the products based on their product code and then based on that result, match the prices. VLookup didn't quite get me where I wanted to go, although I am open to suggestion, so I have tried my hand at the following code: Sub match_price() Dim ws1 As Worksheet Dim ws2 As Worksheet Set ws1 = ActiveSheet Set ws2 = Worksheets("master") For Each i In ws1.Range("A2:A100") For Each C In ws2.Range("A2:A75") If i.Cells.Value = C.Cells.Value Then ws1.Range("C2:C10").Select End If Next C Next i For Each i In ws1.Range("C2:C100") For Each C In ws2.Range("C2:C75") If i.Cells.Value < C.Cells.Value Then i.Cells.Interior.ColorIndex = 3 End If Next C Next i End Sub However, my solution is not recognizing the differences, I suspect this is because it is not fully picking up that the differences should only be based on matched products. Any help is appreciated, thanks in advance. EDIT SAMPLE DATA Master Sheet ID Descrip Invoice 14562738 A 119 25364058 B 245 26584024 C 375 67489542 D 19 Local Sheet ID Descrip Invoice 14562738 A 115 25364058 B 240 67489542 D 19 Edit 2: My resolution: In case anyone is interested, I recorded a macro with my Vlookup code and added user2140261 conditional formatting for the flagging. I only wanted to highlight the text so I removed the coloring of the cell itself. I should mention that I need to use VBA as there are other types of calculations that I need to do across many cells and sheets, but user2140261 highlighting solution helped me take Vlookup to where I need to be. Thank you for your help! Sub Macro() ' 'I always select D2 as the default active cell. Range("D2").Select ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-3],master,3,FALSE)" Selection.AutoFill Destination:=Range("D2:D10"), Type:=xlFillDefault Range("C2:C10").Select Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _ Formula1:="=D2" Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority With Selection.FormatConditions(1).Font .Color = -16383844 .TintAndShade = 0 End With Selection.FormatConditions(1).StopIfTrue = False End Sub A: =VLOOKUP(A2,Master!A2:C5,3,FALSE) Based on your Sample adjust ranges to suite. Enter this in Column D of the local worksheet and Drag down. Then to Highlight use Conditional Formatting where Value in C is < Value in D Below Is a Copy of your Sample Data. On Worksheet Local. In the picture you can see the VLOOKUP returns all values from the rows with matches. TO highlight these values you will need to use a conditional Format: Notice in the SCreen shot that you must have ALL the data selected that you want highlighted. Then in the formula box enter =D2 Make sure that If you try to click on cell D2 and the formula becomes =$D$2 Then you MUST remove the Doller Signs ($) And your final data will look like the following: Both 115 and 240 are red because they are less then the values taken from the Master sheet. And 19 is not because it is only equal to the value from Master sheet From your edit to your question, I think you can shorten the macro a little bit, this will also speed it up a lot you should try to avoid using the select function whenever possible. Although there is a weird bug in VBA that no matter how you enter a cell reference in VBA it is always taken as a Row Column reference and never an actual reference. None the less this should clean up your example a tiny bit and also help with the speed if in the future you use this on a larger scale. Sub Macro() Range("D2:D10").FormulaR1C1 = "=VLOOKUP(RC[-3],master,3,FALSE)" With Range("C2:C10") .Select .FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _ Formula1:="=D2" .FormatConditions(1).Font.Color = -16383844 End With End Sub
{ "pile_set_name": "StackExchange" }
Q: How to set DialogInterface.OnClickListener without AlertDialog.Builder? I want to create custom AlertDialog, but without AlertDialog.Builder. I set ListView as content view and wish to set DialogInterface.OnClickListener on its items. Here is method onCreate() of my custom MyAlertDialog extends AlertDialog. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Context context = getContext(); setTitle("Custom title"); ListView listView = new ListView(context); listView.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, new String[] { "One", "Two" })); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); setContentView(listView); } I had read docs about DialogInterface, Dialog and AlertDialog many times, but I didn't find the option like "AlertDialog.setOnClickListener()". The solution must be without AlertDialog.Builder. A: Use OnItemClickListener instead. If you want to use your dialog in different places, Add a function to your Dialog and try to make your whole code more reusable. public void setOnItemClickListener(OnItemClickListener listener){ listView.setOnItemClickListener(listener); }
{ "pile_set_name": "StackExchange" }
Q: Local file inclusion in JS app I am working on a project which requires the name of the page as a query parameter 'path'. The app stores path variable as res.query.path. My manager asked me to pay attention to LFI, so I'm concerned about it. The app is using Express.JS, and no PHP. My question is if the input is not handled carefully, is it still vulnerable to PHP wrappers? A: The app is using JS(express) and no PHP, so my first question is if the input is not handled carefully is it still vulnerable to PHP wrappers? PHP wrappers concerns php based application and has nothing to do with ways express js handles data. I've written a small function to sanitize user input. Please tell me if it vulnerable in an environment where the path parameter is being prepended using the below function prepare for getting an absolute path that is then used as input to res.sendFile(). The code will not prevent you from getting hacked if the logic behind it is incorrect. The LFI not only means inclusion of local system files but also file uploaded by attacker to spawn shell as an attempt for escalation of privileges. In such case ../ shall not be the only thing to look for. In the app's request flow's last step, consider this as suggested addition: res.sendFile((if possible)check if the intended page will be prepared and it is surely not from system files or the page to be prepared belongs from specific directory of the server & then prepare(page))
{ "pile_set_name": "StackExchange" }
Q: Laplace transform of $\cosh(t)$ from first principles: How to deal with infinities? I'm trying to find the Laplace transform of $\cosh(t)$ from first principles. My work is as follows: $$\begin{align} \mathcal{L}\{\cosh(t)\} &= \int_0^\infty e^{-st} \cosh(t) \ dt \\ &= \dfrac{1}{2} \int_0^\infty e^{-st} \left( \dfrac{e^t + e^{-t}}{2} \right) \ dt \ \ \text{(Using the definition of $\cosh(t)$.)} \\ &= \dfrac{1}{2} \int_0^\infty e^{t - st} \ dt + \dfrac{1}{2} \int_0^\infty e^{-t - st} \ dt \\ &= \dfrac{1}{2(1 - s)} \lim_{t_1 \to \infty - s\infty} \int_0^{t_1} e^{u_1} \ du_1 + \dfrac{1}{2(-1 - s)} \lim_{t_2 \to -\infty - s\infty} \int_0^{t_2} e^{u_2} \ du_2 \\ &= \dfrac{1}{2(1 - s)} \lim_{t_1 \to \infty - s\infty} \left[ e^{u_1} \right]^{t_1}_0 + \dfrac{1}{2(-1 - s)} \lim_{t_2 \to -\infty - s\infty} \left[ e^{u_2} \right]^{t_2}_0 \\ &= \dfrac{1}{2(1 - s)} \left[ e^{\infty - s\infty} - 1 \right] + \dfrac{1}{2(-1 - s)} \left[ e^{-\infty - s\infty} - 1 \right] \\ &= \dfrac{1}{2(1 - s)} \left[ e^{\infty} e^{-s \infty} - 1 \right] + \dfrac{1}{2(-1 - s)} \left[ e^{-\infty} e^{- s\infty} - 1 \right] \\ &= \dfrac{1}{2(1 - s)} \left[ e^{\infty} e^{-\infty (x + iy)} - 1 \right] + \dfrac{1}{2(-1 - s)} \left[ e^{-\infty} e^{-\infty (x + iy)} - 1 \right] \\ &= \dfrac{1}{2(1 - s)} \left[ e^{\infty} e^{-\infty x} e^{-\infty iy} - 1 \right] + \dfrac{1}{2(-1 - s)} \left[ e^{-\infty} e^{-\infty x} e^{-\infty iy} - 1 \right] \\ &= \dfrac{1}{2(1 - s)} \left\{ e^{\infty} e^{-\infty x} \cos[(- \infty y) + i \sin(- \infty y)] - 1 \right\} + \dfrac{1}{2(-1 - s)} \left\{ e^{-\infty} e^{-\infty x} \cos[(- \infty y) + i \sin(- \infty y)] - 1 \right\} \\ &= \dfrac{1}{2(1 - s)} \left\{ e^{\infty} e^{-\infty x} \cos[(- \infty y) + i \sin(- \infty y)] - 1 \right\} + \dfrac{1}{2(-1 - s)} \left\{ \dfrac{1}{e^{\infty x} e^{\infty}} \cos[(- \infty y) + i \sin(- \infty y)] - 1 \right\} \\ &= \dfrac{1}{2(1 - s)} \left\{ e^{\infty} e^{-\infty x} \cos[(- \infty y) + i \sin(- \infty y)] - 1 \right\} - \dfrac{1}{2(-1 - s)} \\ &= \dfrac{1}{2(1 - s)} \left\{ \dfrac{e^{\infty}}{e^{\infty x}} \cos[(- \infty y) + i \sin(- \infty y)] \right\} - \dfrac{1}{2(-1 - s)} \end{align}$$ I know that, by the theory of Laplace transforms, we require that $\Re(s) > 0$. However, I'm still unsure of how to deal with the term with $\dfrac{e^{\infty}}{e^{\infty x}}$? How does this lead to a solution? I would greatly appreciate it if people would please take the time to clarify this. A: You are OK up to here: $$ \dfrac{1}{2} \int_0^\infty e^{t - st} \ dt + \dfrac{1}{2} \int_0^\infty e^{-t - st} \ dt $$ Now go like this: $$ \int_0^M e^{t-st}\;dt = \frac{1}{1-s}e^{t-st}\big|_{t=0}^M =\frac{e^{M(1-s)}}{1-s}-\frac{1}{1-s} \\ \int_0^\infty e^{t-st}\;dt = \lim_{M \to \infty} \left(\frac{e^{M(1-s)}}{1-s}-\frac{1}{1-s}\right) = \frac{-1}{1-s} \qquad\text{(assuming $\mathrm{Re}\;s>1$)} $$ And similarly for the other one $$ \int_0^\infty e^{-t-st}\;dt = \lim_{M \to \infty} \left(\frac{-e^{-M(s+1)}}{1+s}+\frac{1}{1+s}\right) = \frac{1}{1+s}\qquad\text{(assuming $\mathrm{Re}\;s>-1$)} $$
{ "pile_set_name": "StackExchange" }
Q: What exactly is a "Console"? I am trying to writing a console application. It has its original console, let's name it console A. And I want this application to do the following things via C#: Open another console B in another thread, then get input from A and output it to B; type a command in A, such as dir, and show the output in B; while doing the above things (still not done yet. X_X ), I find myself lack a through understanding of what a console window is, and how it is assigned to a console application, especially the very first console when my console application starts to run. Could some one shed some light on me? Is console window physically a memory area in the video memory? Or something else? Could different threads within the same process have different console of its own for its own I/O? Many thanks... Hi, guys, now I am using one console application to start another console application in a new process. Thus I can have 2 consoles output at the same time. My understanding now is that, for Windows OS, a console is a special window, and it's a system resource that OS assigned to the application without-a-UI as a necessary user interface. Windows OS handles the wiring between the system-prepared console window with our UI-less application. A: In Windows terms, a Console is a textual GUI window that you see when you run "cmd.exe". It allows you to write text to, and read text from, a window without the window having any other UI chrome such as toolbars, menus, tabs, etc,.. To get started you'll want to load Visual Studio, create a new project and choose "Console Application". Change the boilerplate code that Visual Studio produces to: using System; using System.Text; namespace MyConsoleApp { class Program { static void Main(string[] args) { Console.Write("Hello, world!"); Console.ReadKey(); } } } When you run your application, a console window will open with the text "Hello, world!" and it'll stay open until you press a key. That is a console application. Is console window physically a memory area in the video memory? Or something else? It's not physically a memory area in video memory, it's "something else". The Wikipedia Win32 console page gives a fairly robust descrption of the ins and outs.
{ "pile_set_name": "StackExchange" }
Q: Create circular references between class instances? I'm trying to construct a class that allows an instance to point to another class, but I want these to eventually form a loop (so instance A → Instance B → Instance C → Instance A) I tried the following, but I'm getting a NameError: class CyclicClass: def __init__(self, name, next_item): self.name = name self.next_item = next_item def print_next(self): print(self.next_item) item_a = CyclicClass("Item A", item_b) item_b = CyclicClass("Item B", item_a) Is this an inappropriate pattern in Python? If so, what would be the correct way to implement this? This seems similar but not the same as the following, since the class definition itself is not circular: Circular dependency between python classes A: You need to create the objects first, then link them. item_a = CyclicClass("Item A", None) item_b = CyclicClass("Item B", item_a) item_a.next_item = item_b Think of the second argument to CyclicClass as a convenience, rather than the primary way of linking two objects. You can emphasize that by making None the default parameter value. class CyclicClass: def __init__(self, name, next_item=None): self.name = name self.next_item = next_item def print_next(self): print(self.next_item) item_a = CyclicClass("Item A") # item_b = CyclicClass("Item B") # item_b.next_item = item_a item_b = CyclicClass("Item B", item_a) item_a.next_item = item_b
{ "pile_set_name": "StackExchange" }
Q: Closure: 'Is there Brutalist Music composed after 1900 that doesn't hurt the listener?' Sorry, but I'm not certain why Is there Brutalist Music composed after 1900 that doesn't hurt the listener? was closed as off-topic? Is the hitch my writing? How can I improve? This is a question on music composition that is covered by the on-topic criteria: Music: Practice & Theory Stack Exchange is for musicians, students, and enthusiasts. If you have a question about... [...] music theory, notation, history, or composition A: As stated in the close reason, and the discussions we have had with you on this subject: This question does not appear to be about music practice, performance, composition, technique, theory, or history within the scope defined in the help center. The three examples you give are not analogous, despite you thinking they are, and as Todd pointed out it may be that they also are not a good fit, but whether or not they are is irrelevant to your question.
{ "pile_set_name": "StackExchange" }
Q: States and Countries select box - best way to do it? this may seem trivial but I'm setting up, on a profile form page I'm building, a countries and states select box such that when you select the US or Canada then the states box would display states of the selected countries else it would display a None Applicable instead. My countries and states are in a database and I'm populating m y selects from that - I would like a simple yet proper way to do this - I noticed that for some reason disabling select options is not supported in all browsers :( - or is there any nice free snippet online I could use [maybe I'm feeling too lazy to code this here] I'm using JQuery for the javascripting here though. Edited Thanks for the replies - the cascading drop down seems to do what I need but I'm looking for a php based solution. How have mainstream websites accomplished this btw. Because I don't want to leave it to the user and end with entries including American/ Canadian states with countries that are not the US/Canada. The Ajax idea is what I had in mind but the thing is that the application form I'm building has a section where you can add contact addresses. Its been built such that you can add multiple addresses to the same contact. Theres an add button which just duplicates the address inputs using a javascript function so basically when you submit the form you have data like : _POST['address[]'], _POST['city[]'], _POST['state[]'],_POST['country[]'] The thing is binding this action to each instance of state and countries when created. A: I think I would not even show the state selector, if neither US nor Canada has been selected from the country selector. This approach has two advantages, users from all other countries are not bothered by meaningless content, you don't have to deal with unwanted input. Now I would save the value of the country selector via AJAX and then send/activate the additional selector div with the response, if needed. After your edit: How flexible are you then? If you are stuck with some existing code then a cron job which eliminates unnecessary state entries might be another way. I mean you could also handle the state later on retrieval but I assume there is also preexisting code which creates addresses and that code doesn't check if the state makes sense...
{ "pile_set_name": "StackExchange" }
Q: Django CSRF Error PW Reset and Login I'm using django.contrib.auth.views for password reset. I get the CSRF error when I try to submit the password change form. It lets me enter my email, sends me a link with uidb64 and token, and then lets me enter a new password twice. When I submit this password_reset_confirm form I get the CSRF invalid error. Here is my template for password reset confirm: <div class="reset-page"> <h3 class="reset-header">{% blocktrans %}Reset Password - Step 2 of 2{% endblocktrans %}</h3> <form class="login-form" action="" method="post"> <div class='form'> {% csrf_token %} {% if validlink %} <input id="id_new_password1" name="new_password1" type="password" class="text-login" placeholder="Password" /> <input id="id_new_password2" name="new_password2" type="password" class="text-login" placeholder="Confirm Password" /> <input type="submit" class="submit-login" value="{% trans 'Submit' %}" /> {% if error_messages %} <p class="reset-error">Error: {{ error_messages }}</p> {% endif %} {% else %} <p class="reset-bad-link">{% blocktrans %}Error: This reset link is no longer valid!{% endblocktrans %}</p> {% endif %} </div> </form> <p class="reset-info">{% blocktrans %}Enter your new password, twice.{% endblocktrans %}</p> </div> I have no idea how to debug this, help would be appreciated greatly. There isn't any custom code, just the contrib views. One last question, in the source code of django.contrib.auth.views.password_reset_confirm it says that it doesn't need CSRF since noone can guess the URL. I've tried removing the {% csrf_token %} tag and it still didn't work. Do I need it or not? EDIT: The django.contrib.auth.views confirm view: # Doesn't need csrf_protect since no-one can guess the URL @sensitive_post_parameters() @never_cache def password_reset_confirm(request, uidb64=None, token=None, template_name='registration/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None, current_app=None, extra_context=None): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ UserModel = get_user_model() assert uidb64 is not None and token is not None # checked by URLconf if post_reset_redirect is None: post_reset_redirect = reverse('password_reset_complete') else: post_reset_redirect = resolve_url(post_reset_redirect) try: # urlsafe_base64_decode() decodes to bytestring on Python 3 uid = force_text(urlsafe_base64_decode(uidb64)) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and token_generator.check_token(user, token): validlink = True title = _('Enter new password') if request.method == 'POST': form = set_password_form(user, request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(post_reset_redirect) else: form = set_password_form(user) else: validlink = False form = None title = _('Password reset unsuccessful') context = { 'form': form, 'title': title, 'validlink': validlink, } if extra_context is not None: context.update(extra_context) if current_app is not None: request.current_app = current_app return TemplateResponse(request, template_name, context) A: Remove the <div class='form'> tag. Place {% csrf_token %} right after <form class="login-form" action="" method="post">.
{ "pile_set_name": "StackExchange" }
Q: How to fix android.widget.TextView() requires api 21 error I have BubbleTextView which is a custom TextView with a blue bubble behind as background. Here is my code: class BubbleTextView(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : TextView(context, attrs, defStyleAttr, defStyleRes) { private val paint = Paint(Paint.ANTI_ALIAS_FLAG) private val rectPath = Path() private val trianglePath = Path() private val rectF = RectF() private val triangleSize = resources.getDimensionPixelSize(R.dimen.triangle_size_20dp).toFloat() private val cornerRadius = resources.getDimensionPixelSize(R.dimen.corner_radius_4dp).toFloat() constructor(context: Context?):this(context, null, 0, 0) constructor(context: Context?, attrs: AttributeSet?):this(context, attrs, 0, 0) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int):this(context, attrs, defStyleAttr, 0) init{ paint.style = Paint.Style.FILL paint.color = Color.CYAN } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) val myWidth = (right - left).toFloat() val myHeight = (bottom - top).toFloat() val centerX = myWidth / 2f val lowerEdgeY = myHeight * 0.8f rectF.set(0f, 0f, myWidth, lowerEdgeY) rectPath.addRoundRect(rectF,cornerRadius, cornerRadius, Path.Direction.CW ) val delta = triangleSize * 0.5f trianglePath.moveTo(centerX - delta, lowerEdgeY) trianglePath.lineTo(centerX + delta, lowerEdgeY) trianglePath.lineTo(centerX, myHeight) trianglePath.close() } override fun onDraw(canvas: Canvas?) { canvas?.drawPath(rectPath, paint) canvas?.drawPath(trianglePath, paint) super.onDraw(canvas) } } : TextView is highlighted red with error: android.widget.TextView() requires api 21. For api 21 and above the apl is working fine. But for below the app crashed instantly. Thanks in advance. A: Constructor class BubbleTextView(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : TextView(context, attrs, defStyleAttr, defStyleRes) added in API level 21, so you only can use >= 21 You should: class BubbleTextView : TextView { private val paint = Paint(Paint.ANTI_ALIAS_FLAG) private val rectPath = Path() private val trianglePath = Path() private val rectF = RectF() private val triangleSize = resources.getDimensionPixelSize(R.dimen.triangle_size_20dp).toFloat() private val cornerRadius = resources.getDimensionPixelSize(R.dimen.corner_radius_4dp).toFloat() constructor(context: Context?):super(context) constructor(context: Context?, attrs: AttributeSet?):super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int):super(context, attrs, defStyleAttr) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) init{ paint.style = Paint.Style.FILL paint.color = Color.CYAN } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) val myWidth = (right - left).toFloat() val myHeight = (bottom - top).toFloat() val centerX = myWidth / 2f val lowerEdgeY = myHeight * 0.8f rectF.set(0f, 0f, myWidth, lowerEdgeY) rectPath.addRoundRect(rectF,cornerRadius, cornerRadius, Path.Direction.CW ) val delta = triangleSize * 0.5f trianglePath.moveTo(centerX - delta, lowerEdgeY) trianglePath.lineTo(centerX + delta, lowerEdgeY) trianglePath.lineTo(centerX, myHeight) trianglePath.close() } override fun onDraw(canvas: Canvas?) { canvas?.drawPath(rectPath, paint) canvas?.drawPath(trianglePath, paint) super.onDraw(canvas) } }
{ "pile_set_name": "StackExchange" }
Q: How to apply product filters from homepage I want a functionality in which I want a filter form in homepage. When a customer submit that form it should redirect to a category page with the products filtered by their selection in from. Suppose we have 2 attributes: Player level & Gender. When customer select their option from form and submit form, then customer should redirect to the category with filtered products. Till now I have prepared a form with required attributes in homepage. And on its submission I am getting its value in separate controller. Please let me know the solutions for it. A: First you have to keep the form field names same as the attribute code in your magento, e.g. if you have a color attribute which you want to add to your form, use it as <select name='color'><option></option></select> Then, get the values in your controller post action, loop through all selected attributes and values like, $data = YOUR_POST_DATA; $collection = YOUR_PRODUCT_COLLECTION(WITH_CATEGORY_FILTER); $filter = array(); foreach ($data as $attributeCode => $value) { $filter[] = array( 'attribute' => $attributeCode, 'eq' => $value ); } if (count($filter) > 0) { $collection->addAttributeToFilter($filter); } This way you will get collection of products with selected attribute values. Now to put the collection to your PHTML file, You have to create a Block which extends Magento's Product List Block Magento\Catalog\Block\Product\ListProduct. Now, take all the content of app/design/frontend/YOUR_THEME/YOUR_TEMPLATE/template/catalo‌​g/product/list.phtml to your phtml file. Replace $_productCollection = $block->getLoadedProductCollection(); with your custom collection.
{ "pile_set_name": "StackExchange" }
Q: How can I pass 2 date values in field expression I have been trying to pass 2 dates through field expression and i'm encountering an error. Please find my code below: FilterExpression="PreparedDate >= 'id={0}' and PreparedDate <= 'id2{0}'" I want to achieve the query: select * from table where date between date1 and date2. I have 2 controls with the date values. The exception: [EvaluateException: Cannot perform '>=' operation on System.DateTime and System.String.] System.Data.BinaryNode.SetTypeMismatchError(Int32 op, Type left, Type right) +26 System.Data.BinaryNode.BinaryCompare(Object vLeft, Object vRight, StorageType resultType, Int32 op, CompareInfo comparer) +2133 System.Data.BinaryNode.EvalBinaryOp(Int32 op, ExpressionNode left, ExpressionNode right, DataRow row, DataRowVersion version, Int32[] recordNos) +11692 System.Data.BinaryNode.Eval(DataRow row, DataRowVersion version) +26 A: My Filter expression was wrong. This is the correct code: FilterExpression="preparedDate >= '{0}' and preparedDate <= '{1}'" Thank you all...
{ "pile_set_name": "StackExchange" }
Q: Building Sencha Touch app with Cordova - [You may not have the required environment or OS to build this project] error I am trying to build a sencha touch 2.4 application for Android using the sencha cmd "sencha app build native" and I am getting an error that I can't solve. "You may not have the required environment or OS to build this project" I am working on Win7, using sencha touch 2.4 and sencha cmd v5.1. I downloaded the Android sdk (API 19) using the Android SDK Manager. This is the command output: D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA>sencha app build native Sencha Cmd v5.1.1.39 [INF] Processing Build Descriptor : native [INF] Loading app json manifest... [INF] Concatenating output to file D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA/build/temp/production/GeoMapTematicPA/sencha-compiler/cmd-packages.js [INF] writing content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\bootstrap.js [INF] appending content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\bootstrap.js [INF] appending content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\bootstrap.js [INF] appending content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\bootstrap.js [INF] Appending content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA/bootstrap.json [WRN] C1014: callParent has no target (me.callParent in Ext.dataview.DataView.onAfterRender) -- D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\touch\src\dataview \DataView.js:892 [WRN] C1014: callParent has no target (this.callParent in Ext.Decorator.setDisabled) -- D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\touch\src\Decorator.js:157 [WRN] C1014: callParent has no target (this.callParent in Ext.data.ArrayStore.loadData) -- D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\touch\src\data\ArrayStore.js:64 [WRN] C1014: callParent has no target (this.callParent in Ext.fx.animation.Wipe.getData) -- D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\touch\src\fx\animation\Wipe.js:119:7 [INF] merging 0 input resources into D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova\www\resources [INF] merged 0 resources into D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova\www\resources [INF] merging 87 input resources into D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova\www [INF] merged 0 resources into D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova\www [INF] executing compass using system installed ruby runtime identical ../css/app.css [INF] Copying page resources to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova\www [INF] Writing content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA/cordova/www/microloader.js [INF] Appending content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA/cordova/www/microloader.js [INF] Building output markup to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA/cordova/www/index.html [INF] Writing content to D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA/cordova/www/index.html [INF] [Cordova] Attempting Cordova Build for platforms "android" [INF] [shellscript] [INF] [shellscript] D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova>cordova build android [INF] [shellscript] Running command: D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova\platforms\android\cordova\build.bat [INF] [shellscript] events.js:85 [INF] [shellscript] throw er; // Unhandled '''error''' event [INF] [shellscript] ^ [INF] [shellscript] Error: spawn cmd ENOENT [INF] [shellscript] at exports._errnoException (util.js:746:11) [INF] [shellscript] at Process.ChildProcess._handle.onexit (child_process.js:1046:32) [INF] [shellscript] at child_process.js:1137:20 [INF] [shellscript] at process._tickCallback (node.js:355:11) [INF] [shellscript] ERROR building one of the platforms: Error: D:\Sviluppo\varie\source\PROGETTI\GeoMapTematicPA\GeoMapTematicPA\cordova\platfrms\android\cordova\build.bat: Command failed with exit code 1 [INF] [shellscript] You may not have the required environment or OS to build this project Thanks in advance, any help would be really appreciated. A: As suggested here, Cordova / Ionic build error (sometimes): don't have required environment, what to do is Copy and paste this "%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\" to the enviroment variables Path.
{ "pile_set_name": "StackExchange" }
Q: GSM Modem Send Message in UCS2 format error I'm using java to communicate with a gsm modem (Siemens) using AT commands. I set the encoding of modem to "UCS2". When sending messages as soon as I send the phone number I get ERROR from the device: AT+CSCS=UCS2 OK AT+CSMP=17,167,0,8 OK AT+CMGF=1 OK AT+CMGS="0919xxxxxxx" ERROR HELP ME, PLEEEEEEASE! :( A: I think you are encoding the <da> address argument to AT+CMGS incorrectly. You refer to 91 and 92 style, but are you actually referring to the '81'/'82' format as explained in the Coding of Alpha fields in the SIM for UCS2 blog post about encoding as specified in 3GPP TS 11.11? After you run AT+CSCS="UCS2" every single string must be encoded that way, so for instance to switch from UCS2 to UTF-8 would be AT+CSCS="005500540046002D0038". Alpha fields with 80/81/82 encoding only applies to some cases, and not UCS2 encoded strings in general. In particular notice that the encoding of the string "UTF-8" in the above AT+CSCS command has nothing to do with this. That also applies to the <da> argument to AT+CMGS.
{ "pile_set_name": "StackExchange" }
Q: Using similar MySQL tables but for different varchar size of one column to save on DB size, querying via UNION I'm creating 2 similar tables, atestunion1 and atestunion2, with columns of: of id, customer_id, product_id, comment, date. The only difference between these is the length of the varchar comment. The "why" of this structure is below. As comments are entered, the number of characters are counted, and then the entry is saved to the table (via if or switch php statement) with the smallest varchar character size that the comment with fit into. Then, these are accessed like a single table, using UNION, like this: SELECT * FROM atestunion1 UNION SELECT * from atestunion2 ORDER BY date This query seems to work without issue - the different comment field size doesn't seem to cause a problem - but I'm wondering if there are issues with this conceptually. The reason for doing this is to save on the DB size. I believe (assumption 1) that a comment field with 20 characters in varchar(30) column takes up less memory than one with varchar(500). However, I would think that this sort of optimization might be built into MySQL and is thus not in need of my lowly hack. Maybe it does this already, such that my assumption 1 is simply incorrect? Or, perhaps there is a setting for the varchar column that will cause this? My waterfall of questions: Does MySQL already do such an optimization behind the scenes, such that an entry with some number of characters takes up the same memory regardless of the varchar setting and such that I don't need to mess with it? If not, is there a setting for the varchar that would cause it to do so? If not, does this concept of similar tables but for the varchar size difference, then accessed like a single table via UNION, seem like a valid and non-problematic way to save on DB size? A: The difference in storage size between varchar(30) and varchar(500) (for the same string) is one byte. See String Type Storage Requirements: L represents the actual length in bytes of a given string value. [..] VARCHAR(M), VARBINARY(M) [..] L + 1 bytes if column values require 0 − 255 bytes, L + 2 bytes if values may require more than 255 bytes So no - It's not worth splitting the table and overcomplicating your code. The only case I know, where it might make a significant difference, is when you use temporary tables with MEMORY engine. Then the VARCHAR columns will be expanded to it's maximum size (That are 2000 bytes for VARCHAR(500) with utf8mb4 character set). See The MEMORY Storage Engine: MEMORY tables use a fixed-length row-storage format. Variable-length types such as VARCHAR are stored using a fixed length.
{ "pile_set_name": "StackExchange" }
Q: Incremental loading in Azure Mobile Services Given the following code: listView.ItemsSource = App.azureClient.GetTable<SomeTable>().ToIncrementalLoadingCollection(); We get incremental loading without further changes. But what if we modify the read.js server side script to e.g. use mssql to query another table instead. What happens to the incremental loading? I'm assuming it breaks; if so, what's needed to support it again? And what if the query used the untyped version instead, e.g. App.azureClient.GetTable("SomeTable").ReadAsync(...) Could incremental loading be somehow supported in this case, or must it be done "by hand" somehow? Bonus points for insights on how Azure Mobile Services implements incremental loading between the server and the client. A: The incremental loading collection works by sending the $top and $skip query parameters (those are also sent when you do a query by using the .Take and .Skip methods in the table). So if you want to modify the read script to do something other than the default behavior, while still maintaining the ability to use that table with an incremental loading collection, you need to take those values into account. To do that, you can ask for the query components, which will contain the values, as shown below: function read(query, user, request) { var queryComponents = query.getComponents(); console.log('query components: ', queryComponents); // useful to see all information var top = queryComponents.take; var skip = queryComponents.skip; // do whatever you want with those values, then call request.respond(...) } The way it's implemented at the client is by using a class which implements the ISupportIncrementalLoading interface. You can see it (and the full source code for the client SDKs) in the GitHub repository, or more specifically the MobileServiceIncrementalLoadingCollection class (the method is added as an extension in the MobileServiceIncrementalLoadingCollectionExtensions class). And the untyped table does not have that method - as you can see in the extension class, it's only added to the typed version of the table.
{ "pile_set_name": "StackExchange" }
Q: select rows from SQL table and 5 rows from another i have three SQL server tables like this i need to select the categories from LS_categoires where nodeid = 183 and select only 5 files from LS_files that related to each category was selected if i have two categories related to node 183 the result should be 10 rows is that possible ? A: Try this: SELECT * FROM LS_Categories c INNER JOIN ( SELECT *, ROW_NUMBER() OVER(PARTITION BY catid ORDER BY item_id ASC) rownum FROM LS_ItemTypes ) l ON c.catid = l.catid AND l.rownum <= 5 INNER JOIN LS_Files f ON l.item_id = f.id where c.nodeid = 183; This will select first files for each category.
{ "pile_set_name": "StackExchange" }
Q: How can I configure removing space between line comment slasles and text in Intellij IDEA? If I want to comment line I use "Ctrl+/" and get the "//" at start of line Then I use auto formatting with "Ctrl+alt+L" keys and get At the end I must remove space between "//" and text manually every time... Can I do all of these steps in one time? I didn't find any settings for this... A: An alternative, not perfect though, is: Editor -> Code Style -> Java -> Code Generation Uncheck Line Comment at first column The menu hierarchy is the one in Intellij IDEA 14.
{ "pile_set_name": "StackExchange" }
Q: Why do Groups need Inverses? Why are groups required to have inverses? What is the motive behind it? It doesn't fall out of another requirement, so what was the goal of adding them in? A: 1) You don't have to require the existence of inverses. If you have a set $M$ with a binary operation that is associative and contains an identity, you have what is called a monoid. Monoids are very interesting structures that come up in many areas of mathematics. 2) Why are groups more interesting than monoids? (At least, to most people's tastes.) One reason is that groups are related to the notion of symmetry. A symmetry of an object is a (bijective) transformation that leaves the object unchanged. In that case, the inverse of the transformation will also leave the object unchanged. So the algebraic structure that models symmetries is associative (composition of transformations is associative), has an identity (doing nothing is always a symmetry!), and has inverses. So groups are the right algebraic structure to study symmetry. 3) Mathematically, the existence of inverses is very powerful. If you try to solve the equation $ax = b$ in a monoid ($a,b$ are given; $x$ is unknown), then you may no solutions, one solution, or many solutions. But in a group, there is always a unique solution: $x = a^{-1} b$. This is very useful. Said differently, in a group if I perform some unknown operation $x$ followed by $a$ and the resulting composition is the operation $b$, then I can figure out what $x$ had to be. If instead we were working in a monoid, we would not be able to recover what $x$ is (or even know whether or there is some $x$ for which the statement holds), without additional information specific to the monoid at hand.
{ "pile_set_name": "StackExchange" }
Q: Exception while adding contact in google.Internal server Error We have been getting the following error from today morning onwards while inserting the contacts through Google API from java. Please find the stack trace below Exception while adding contact in google.... com.google.gdata.util.ServiceException: Internal Server Error A temporary internal problem has occurred. Try again later. at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:624) at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:563) at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:552) at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:530) at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:535) at com.google.gdata.client.Service.insert(Service.java:1409) at com.google.gdata.client.GoogleService.insert(GoogleService.java:599) And we are getting this error while inserting at the line ContactsService.insert(postUrl, contact) Please reply if anyone knows the solution. A: I have raised a CASE with Google. I suggest you all do the same. Here are the details of the case that I raised. A detailed description of the problem We have an integration that has been running for 5 years between external database and Google Contacts. Today we are receiving errors when trying to insert or update Google Contact Records. Others are also experiencing this issue as outlined at Exception while adding contact in google.Internal server Error We have multiple customers that use our marketplace application and they are also having the problem on their Google Domain Instances. https://chrome.google.com/webstore/detail/ilink-by-i3cloudcom-api/nnidipmclichhijaifbfckcckdpbnmhj What is the scope of the issue? Were you able to call the API without any errors before? YES - Our Service has run for 5 years without this issue ** Are all users affected, has anything changed in your internal environment?** YES - all users are affected across many domains and Google instances. Occurs for all users trying to INSERT/UPDATE contacts. We are using the .Net client with the following call Google.Contacts.Contact createdContact = cr.Insert<Google.Contacts.Contact>(new OAuthUri("https://www.google.com/m8/feeds/contacts/default/full/", user, domain), newContact); The Error that is returned is: Execution of request failed: https://www.google.com/m8/feeds/contacts/default/full/?xoauth_requestor_id=paul%40i3000.com.au A temporary internal problem has occurred. Try again later. This is affecting a lot of our users - please look into this ASAP
{ "pile_set_name": "StackExchange" }
Q: How to get index of a cell in QTableWidget? I created a table widget and added a contextmenu to it. When I right click the cell,I want to get a file directory and put it into the cell. I've got the directory and pass it to a variable, but i failed to display it in the cell,because I can't get the index of the cell.How to get index of a cell in QTableWidget? Is there any orther method to figure out this qusstion? I'm using Python and PyQt5. enter image description here @pyqtSlot() def on_actionAddFolder_triggered(self): # TODO: Open filedialog and get directory filedir = str(QFileDialog.getExistingDirectory(self, "Select Directory")) return filedir @pyqtSlot(QPoint) def on_tableWidget_customContextMenuRequested(self, pos): # TODO: get directory and display it in the cell x = self.tableWidget.currentRow y = self.tableWidget.currentColumn RightClickMenu = QMenu() AddFolder = RightClickMenu.addAction('Add Folder') FolderAction = RightClickMenu.exec_(self.tableWidget.mapToGlobal(pos)) if FolderAction == AddFolder: NewItem = QTableWidgetItem(self.on_actionAddFolder_triggered()) self.tableWidget.setItem(x,y, NewItem) A: hahaha, I find the mistake! x = self.tableWidget.currentRow y = self.tableWidget.currentColumn replace these two lines x = self.tableWidget.currentRow() y = self.tableWidget.currentColumn() then it works.
{ "pile_set_name": "StackExchange" }
Q: How to make the background color of `x-show-tip` defined in `pos-tip.el` transparent? I found the flycheck-pos-tip package uses a function defined in pos-tip-show which uses a built-in function: x-show-tip. I want to change the background color of x-show-tip to be transparent. There is a custom variable named pos-tip-background-color in the pos-tip package, how can I change this value to transparent? For example, the value of pos-tip-background-color is #FF0000, how can I change its alpha value to 50, so that I get a color of RGBA(255,0,0,0.5) if I use a CSS style value. A: You can't make a frame background transparent by changing the background color. The alpha frame parameter is a separate parameter from background-color. Function x-show-tip accepts an alist of tooltip frame parameters as argument. If you are the caller of x-show-tip then you can add an alpha parameter and its value to the alist that you pass to x-show-tip. Example: (x-show-tip "HELLO" nil '((alpha . 20))) ; Show 80%-transparent tooltip Here's an image showing the effect: However, the call to x-show-tip in pos-tip-show-no-propertize is beyond your control in this regard: it hard-codes the parameter alist. You could, however, advise or redefine pos-tip-show-no-propertize, giving yourself the possibility of modifying the parameters it passes to x-show-tip. But pos-tip.el apparently doesn't offer any non-surgical way to do what you want. You might want to consider requesting such a possibility from the maintainer of pos-tip.el. S?he could, for example, add an optional argument that lets a caller pass the alist, defaulting to the alist that is currently hard-coded.
{ "pile_set_name": "StackExchange" }
Q: Why do I have twice the foreign keys using Sequelize I'm trying to setup a simple blog application, I have the following schema definition: Here is User: module.exports = function(sequelize, DataTypes) { var User = sequelize.define("User", { id: {type: DataTypes.BIGINT, autoincrement:true, primaryKey: true}, firstName: {type: DataTypes.STRING}, lastName: {type: DataTypes.STRING}, nickName: {type: DataTypes.STRING}, email: {type: DataTypes.STRING, unique: true, comment: "Unique "}, password: {type: DataTypes.STRING}, salt: {type: DataTypes.STRING}, enabled: {type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true} }, { freezeTableName: true, classMethods: { associate: function (models) { User.hasMany(models.Article, {as: "Articles", constraints: false}); User.hasMany(models.Comment, {as: "Comments", constraints: false}); } } }); return User; }; Here is Article: module.exports = function(sequelize, DataTypes) { var Article = sequelize.define("Article", { id: {type: DataTypes.BIGINT, autoincrement:true, primaryKey: true}, slug: {type: DataTypes.STRING, comment: "Unique URL slug to access the article"}, title: {type: DataTypes.STRING}, content: {type: DataTypes.TEXT}, created: {type: DataTypes.DATE, defaultValue: DataTypes.NOW}, published: {type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true} }, { freezeTableName: true, classMethods: { associate: function (models) { Article.belongsTo(models.User, {as: "Author", foreignKey: "author_id"}); Article.hasMany(models.Comment, {as: "Comments", constraints: false}); } } }); return Article; }; and Comment: module.exports = function(sequelize, DataTypes) { var Comment = sequelize.define("Comment", { id: {type: DataTypes.BIGINT, autoincrement:true, primaryKey: true}, content: {type: DataTypes.TEXT}, status: {type: DataTypes.INTEGER, defaultValue: 1}, author: {type: DataTypes.BIGINT}, article: {type: DataTypes.BIGINT} }, { freezeTableName: true, classMethods: { associate: function (models) { Comment.hasOne(Comment, {as : "Parent", foreignKey: "parent_id"}); Comment.belongsTo(models.User, {as: "Author", foreignKey: "author_id"}); Comment.belongsTo(models.Article, {as: "Article", foreignKey: "article_id"}); } } }); return Comment; }; The tables are created correctly but I end up with 2 foreign keys each time, for instance this is the Article table in MySQL: 'id','bigint(20)','NO','PRI','0','' 'slug','varchar(255)','YES','',NULL,'' 'title','varchar(255)','YES','',NULL,'' 'content','text','YES','',NULL,'' 'created','datetime','YES','',NULL,'' 'published','tinyint(1)','NO','','1','' 'createdAt','datetime','NO','',NULL,'' 'updatedAt','datetime','NO','',NULL,'' 'author_id','bigint(20)','YES','MUL',NULL,'' 'UserId','bigint(20)','YES','',NULL,'' UserId == author_id User Table: 'id','bigint(20)','NO','PRI','0','' 'firstName','varchar(255)','YES','',NULL,'' 'lastName','varchar(255)','YES','',NULL,'' 'nickName','varchar(255)','YES','',NULL,'' 'email','varchar(255)','YES','UNI',NULL,'' 'password','varchar(255)','YES','',NULL,'' 'salt','varchar(255)','YES','',NULL,'' 'enabled','tinyint(1)','NO','','1','' 'createdAt','datetime','NO','',NULL,'' 'updatedAt','datetime','NO','',NULL,'' This table is correct (no foreign keys) Comment: 'id','bigint(20)','NO','PRI','0','' 'content','text','YES','',NULL,'' 'status','int(11)','YES','','1','' 'author','bigint(20)','YES','',NULL,'' 'article','bigint(20)','YES','',NULL,'' 'createdAt','datetime','NO','',NULL,'' 'updatedAt','datetime','NO','',NULL,'' 'ArticleId','bigint(20)','YES','',NULL,'' 'parent_id','bigint(20)','YES','MUL',NULL,'' 'author_id','bigint(20)','YES','MUL',NULL,'' 'article_id','bigint(20)','YES','MUL',NULL,'' 'UserId','bigint(20)','YES','',NULL,'' ArticleId == article_id and UserId == author_id As you can see I have the version camel cased and the one I've specified. What did I miss? ** EDIT ** There is no constraints in the database for the camel case field: UserId and ArticleId but Sequelize created the fields in the tables. A: You need to add the foreign key on both sides of the relation, e.g: User.hasMany(models.Article, {constraints: false, foreignKey: 'author_id'});
{ "pile_set_name": "StackExchange" }
Q: Arbitrary Length ORDER BYs using NHibernate If I were doing this using PHP and MySQL, it would look something like this (disclaimer that this PHP code is not suitable for external/web-facing use, as it's vulnerable to SQL injection): <?php function orderByColumns ($columns, $sql) { if (0 < count($columns)) { $column = array_shift($columns); if (! stripos($sql, "ORDER BY")) { $sql .= " ORDER BY"; } $sql .= " {$column['name']} {$column['dir']}"; $sql .= 0 < count($columns) ? "," : ""; return orderByColumns($columns, $sql); } return $sql; } $columns = array( array( "name" => "foo", "dir" => "ASC" ), array( "name" => "bar", "dir" => "DESC" ) ); $sql = "SELECT * FROM baz"; $sql = orderByColumns($columns, $sql); // And from here I could make my query The point is that $columns is to be an input from a user somewhere, and that that could be used to order the columns without knowing the list in advance, and in a method that is reusable. I'm looking for a way to do something similar using C# and specifically NHibernate, but it doesn't really seem to work. Here is something along the lines of what I've been trying in C#: List<string> columns = new List<string>() { "Column1", "Column2", "Column3" // And there could be more. } string column = columns.First(); fq = foo.Queryable.OrderBy( i => i.GetType().GetProperty(column).GetValue(i, null) ); foreach (string column in columns) { fq = fq.ThenBy( i => i.GetType().GetProperty(column).GetValue(i, null) ); } And, I've looked at a few StackOverflow answers (ok, more than a few), but they don't seem to be addressing how to build NHibernate queries dynamically in the way I'm looking for. The one that felt most promising is Dynamic QueryOver in nHibernate, but I'm having a hard time fully grokking whether that's even in the right direction. A: So, the problem where is that you aren't executing anything at this point, so nhibernate is going to try to translate that to SQL, which is going to complain because it doesn't know about the GetType() method. You'd have to build up your own Expression instance, and there aren't great ways of doing that dynamically, though it can be done, but still not fun to do. I think it'd be easier to make a dictionary of lambda expressions and columns var lookup = new Dictionary<string, Expression<Func<T, object>>> { { "ColumnA", x => x.ColumnA }, { "ColumnB", x => x.ColumnB } }; foreach (string column in columns) { fq = fq.ThenBy(lookup[column]); } Even then, this might not work if it complains about Expression<Func<T,object>>
{ "pile_set_name": "StackExchange" }
Q: Add keys to values already inside a key and then add extra value and key based on key name I am trying to create a nested dict from a dict I have already created. In my dict for every key I have a list of values. I want to add an additional key to those values and then create a new key and value pair, the value being from the original key for all those values previously. I am also generating the dictionary from two other dictionaries if that is relevant (Sorry it's hard for me to explain) Code used to make original dict dict1 = cls.make_ssc() dict2 = cls.make_tg() dictfinal = {} for key in dict1.keys(): dictfinal[key] = [dict1[key], dict2[key]] return dictfinal This is kind of what I have now: {'blue': ['dog', 'carrot'], 'red': ['cat', 'peas'], 'yellow': ['elephant', 'broccoli'],} I would like to make this: {'blue': {'color': 'blue', 'animal': 'dog', 'vegetable': 'carrot'}, 'red': {'color': 'red', 'animal': 'cat', 'vegetable': 'peas'}, 'yellow': {'color': 'yellow', 'animal': 'elephant', 'vegetable': 'broccoli'},} A: Looks like you need dict with zip Ex: dictfinal = {} keys = ['color', 'animal', 'vegetable'] for key in dict1.keys(): dictfinal[key] = dict(zip(keys, [key, dict1[key], dict2[key]])) return dictfinal
{ "pile_set_name": "StackExchange" }
Q: Heroku: custom domain Trying to host a custom domain with Heroku. i have putting the following into terminal - CNAME www.example.com example.herokuap.com but I keeping getting the following error -bash: CNAME: command not found help A: That's not a Heroku command, you need to use the Heroku CLI heroku domains:add www.example.com or do it from the web dashboard. You then need to setup a CNAME record with your DNS provider to set www.example.com to example.herokuapp.com
{ "pile_set_name": "StackExchange" }
Q: Node.js Express app: if cookie is present, than add CSS class to element from server side I have an express static site app. I calling my site's translation with a cookie in app.js: // i18n app.get('/hu', function (req, res) { // http://127.0.0.1:3000/hu res.cookie('locale', 'hu', { maxAge: 900000, httpOnly: true }); res.redirect('back'); }); app.get('/en', function (req, res) { // http://127.0.0.1:3000/en res.cookie('locale', 'en', { maxAge: 900000, httpOnly: true }); res.redirect('back'); }); If someone visiting http://127.0.0.1:3000/en URL, than it will store a cookie which calling the translation. hu is the default language, when someone visiting my site at the first time, there's no any cookie stored. But how can I add a CSS class to my site when the english translation is active? I have a navigation bar with my logo in the middle which is centered horizontally. On english language, the words length different, causing even the centered flexbox elements left-nav | logo | right-nav slightly not be in the center. Somehow I want to add a CSS class into my handlebar template from app.js (which is on the server side) when the specific cookie is presented. Is it possible? Is it possible to solve this from app.js globally, not from the routers? Final solution, thank you for @t.niese! In app.js: app.use(function(req, res, next) { var defaultLang = 'hu'; var activeLang = req.cookies.locale || defaultLang; res.locals.langClass = activeLang + '-' + activeLang.toUpperCase(); next(); }); In my handlebars template: <!doctype html> <html class="no-js lang-{{langClass}}" lang="{{langClass}}"> A: You would define your own middleware function that will set e.g. langClass for your template values based on the cookie value of locale: app.use(function(req, res, next) { var activeLang = req.cookies.locale || defaultLang; req.local.langClass = 'lang-'+activeLang; next(); }); Then you can use this in your template as class: <html class="{{langClass}}"> </html> You can't solve it globally, because then the language would be the same for every visitor.
{ "pile_set_name": "StackExchange" }
Q: Hide apk file such that no one can download it from play store using web? i need to know how to hide apk file so that no one from web can download apk file using some apk downloading websites e.g https://apkpure.com and so on. A: I don't think there is a way you could prevent users to download the apk file. The best solution I guess is to obfuscate it. :)
{ "pile_set_name": "StackExchange" }
Q: Expand / Collapse all function with AngularJS accordion I am using the Angular UI accordion and I am trying to add a toggle button that will expand and collapse the panels. At present the panels will only open when a user clicks on the heading. The button I added toggles a variable 'isopen' to true or false but it does not seem to work. Here is my code: <button ng-click="isopen =!isopen">expand/collapse</button> {{isopen}} <accordion close-others="false"> <accordion-group is-open="isopen" ng-repeat="site in groups"> <accordion-heading ng-click="isopen = !isopen"> hey {{isopen}} </accordion-heading> hello </accordion-group> </accordion> And here is a plunker: http://plnkr.co/edit/8AkWUxzOir5NNoA0fT5R?p=preview When a user clicks on a panel header it should open that panel only. The Toggle button will hopefully expand and collapse them all. A: Your $scope changes inside accordion. Solution is attach this property in an object on $scope. See working fiddle here. Updated plunkr. It's not much difficult once you find out your mistake in previous question.
{ "pile_set_name": "StackExchange" }
Q: Upgrading to latest stable Mono Mono 2.8 was recently released boasting a couple of large performance improvements. It's far too late for it to make it into Maverick and I'm fairly inpatient. I don't use Mono for anything mission-critical (just playing music and sorting photos) and if it breaks everything related to Mono, I can probably either live with it or fix it. I'm aware of how much I stand to lose if I mess things up. So with that acknowledged, does anybody here know how to build Mono in a way where it could be dropped in to replace the current Mono (2.6.7)? By this I mean ideally mirroring the packages that Ubuntu uses so that if the worse does happen, I can just downgrade the packages. Or is there a PPA that does all this for me? A: Download and install the mono-parallel 2.10 deb package. After installing the deb file paste this in the terminal (Ctrl + Alt + T) source mono-2.10-environment After this your terminal will look like [mono] /var/dev/mono @ Source A: Mono 2.8 is not available in a PPA. But someone made a script to automatically download, compile and install Mono 2.8 from source. That makes it a little bit easier. A: The place to go for a mono PPA is http://badgerports.org/ unfortunately it could be months before it will have mono 2.8 Novell do not believe it is their responsibility to provide mono packages for ubuntu so the effort has to come from the community. Jo Shields maintains both the official packages and the badgerports PPA. He said it could be months before mono 2.8 is available via his PPA. So your only option at this stage is to build from source. Which is not for the faint hearted.
{ "pile_set_name": "StackExchange" }
Q: combine different row data into one cell in sql I have a view with the following structure: areas employee_id complaint_type_id a1 e1 c1 a2 e1 c1 a3 e2 c1 a1 e1 c2 . Now in the code, I am fetching area and complaint_type_id for a particular employee from view. I want to display the complaint categories assigned to an employee for different areas. The output I am getting is as follows: area complaint_type_id a1 c1 a2 c1 a3 c1 a1 c2 a2 c2 a3 c2 In this output, the areas are getting repeat for each kind of complaint id. I want to display complaint categories in a single row for a particular area My desired output is as follows: area complaint_type_id a1 c1,c2 a2 c1,c2 a3 c1,c2 I tried using the group by clause but in the output of the group by areas are appearing twice for each complaint type. How can I achieve my desired output? A: Take CTEs for other tables and this will work: select distinct t1.area, STUFF((SELECT distinct ',' + t2.complaint_type_id from Table1 t2 where t1.area = t2.area FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,0,'') data from Table1 t1; check:http://sqlfiddle.com/#!18/0f121/7
{ "pile_set_name": "StackExchange" }
Q: Why isn't this LINQ to XML Query Working (Amazon S3) Given this XML ... <ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <Name>public.rpmware.com</Name> <Prefix></Prefix> <Marker></Marker> <MaxKeys>1000</MaxKeys> <IsTruncated>false</IsTruncated> <Contents> <Key>0.dir</Key> <LastModified>2008-06-25T16:09:49.000Z</LastModified> <ETag>"0ba2a466f9dfe225d7ae85277a99a976"</ETag> <Size>16</Size> <Owner> <ID>1234</ID> <DisplayName>kyle</DisplayName> </Owner> <StorageClass>STANDARD</StorageClass> </Contents> <!-- repeat similar 100x --> </ListBucketResult> And this C# code: XDocument doc = XDocument.Load(xmlReader); var contents = from content in doc.Descendants("Contents") select new {Key = content.Element("Key").Value, ETag = content.Element("ETag").Value}; foreach (var content in contents) { Console.WriteLine(content.Key); Console.WriteLine(content.ETag); } I know the Xdoc is not empty and contains the right XML. I also implemented some ScottGu code (http://weblogs.asp.net/scottgu/archive/2007/08/07/using-linq-to-xml-and-how-to-build-a-custom-rss-feed-reader-with-it.aspx) as a sanity check and it works exactly as expected. XDocument doc2 = XDocument.Load(@"http://weblogs.asp.net/scottgu/rss.aspx"); var posts = from items in doc2.Descendants("item") select new { Title = items.Element("title").Value }; foreach (var post in posts) { Console.WriteLine(post.Title); } A: Xml namespaces: XNamespace ns = "http://s3.amazonaws.com/doc/2006-03-01/"; var contents = from content in doc.Descendants(ns + "Contents") select new { Key = content.Element(ns + "Key").Value, ETag = content.Element(ns + "ETag").Value };
{ "pile_set_name": "StackExchange" }
Q: YouTube Data API returns "Access Not Configured" error, although it is enabled My internally used web solution to retrieve YouTube video statistics that is based on this example (https://developers.google.com/youtube/v3/quickstart/js) now fails to work. Not sure when exactly it happened, but it used to work couple of months ago. I now tried to run unedited example code (apart from adjusting the CLIENT_ID, of course), and I am getting exactly the same error: { "domain": "usageLimits", "reason": "accessNotConfigured", "message": "Access Not Configured. YouTube Data API has not been used in project 123 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=123 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.", "extendedHelp": "https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=123" } ], "code": 403, "message": "Access Not Configured. YouTube Data API has not been used in project 123 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=123 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry." } When I check the YouTube API in developer console, it shows enabled status, and the Credentials compatible with this API include the ID used to authenticate the client. I can see the statistics for credential use increment when I retry the API call attempts, and the metrics reflect the number of requests and also show that the error rate is 100%. But there is no extra info on those failed attempts in the console to help on debugging the problem. I have deleted and recreated API key and OAuth key, but that did not change anything. Had there been any extra info on those errors on the developer console side, for example client quote exceeded, I could see how to fix this. Now I am completely stuck. A: Create a new project Weirdly, creating a new project just gets the API to work properly!
{ "pile_set_name": "StackExchange" }
Q: Does the 'super-moon' have a measurable effect on probability and magnitude of earthquakes? On the 14th of November 2016, the moon is both full, and is on its closest approach to Earth, causing its largest appearance size until 2033. Citation This large appearance gives it the 'super-moon' name. On the 13th of November 2016, New Zealand suffered a major earthquake, with a magnitude of 7.8, as well as an accompanying tsunami. BBC Link about Earthquake Currently, a post is going around on Facebook, with someone predicting this earthquake, claiming that the supermoon is the cause of this, due to an increased gravitational pull from the moon. It is known that the moon's gravitational pull does have an affect on the earth, as seen by tidal behaviour, but is this pull enough to cause an earthquake and tsunami, or is this behaviour purely coincidental? From https://www.facebook.com/groups/1680211292261330/permalink/1817053615243763/, Heads Up: On 14th November and a couple of days either side of that date, watch for a major earthquake, and quite possible in South Pacific area. The reason for this is that 14th of Nov will be a "super moon" largest for this century (ie. moon closest to Earth on this date than it has been for a long time). This means it will be a period of increased gravitational pull from the moon. There was a recent large earthquake in Italy and as when one plate shifts it places stress on other plates, the chances of a big quake are higher for something down this end of the globe. Also geo-engineering is more likely to have success during this time and can be targeted on a specific area. This is just a possibility, but be alert, that is all I am saying. Always be prepared with water supplies and even food supplies as is possible. Rice is a good food supply item because it lasts a long time and will keep people fed....and is relatively cheap. It can be bought in 5 or 10kg bags from a supermarket for usually $10 to $20. Stay safe. A: To first order, no, supermoons don't have measurable effects on earthquakes. They might have a very very small effect on small earthquakes. It isn't a ridiculous question. The strength of tidal forces is related to distance - tidal acceleration scales as roughly the inverse cube of distance. Wikipedia has the textbook derivation if you are curious. Phil Plait at the Bad Astronomer blog points out that if you combine a spring tide (when Earth-Sun-Moon are in a straight line) with the moon being very close, you can get tides that are 50% stronger than normal. But of course, having stronger tides doesn't mean that you must have more earthquakes (or more volcanic eruptions). Groups like the USGS have looked at earthquake frequency vs tides, and come to the conclusion that any effect is nonexistent, or at best very tiny. According to John Vidale, a seismologist at the University of Washington in Seattle and director of the Pacific Northwest Seismic Network: "Both the moon and sun do stress the Earth a tiny bit, and when we look hard we can see a very small increase in tectonic activity when they're aligned...you see a less-than-1-percent increase in earthquake activity, and a slightly higher response in volcanoes ." From livescience. The same page quotes William Wilcock (also from the University of Washington) as saying he sees greater earthquake activity in subduction zones at low tide, but he sees no more activity during new and full moons. Finally from the same source, quoting John Bellini, a geophysicist at the U.S. Geological Survey: A lot of studies have been done on this kind of thing by USGS scientists and others. They haven't found anything significant at all.
{ "pile_set_name": "StackExchange" }
Q: Count number of entries in whole SQL Server database Is there any way I can count the number of all entries in a SQL Server database? Preferably with only one query. Edit: The total amount of entries in all tables in a given database. A: select sum(rows) from sys.partitions; This is a correct answer, for a conveniently definition of 'entry' (chosen by me): a row in a heap or a b-tree. A: This query will return a list of all the tables, with an approximate row count for each table: SELECT [TableName] = sysobjects.name, [RowCount] = MAX(sysindexes.rows) FROM sysobjects, sysindexes WHERE (sysobjects.xtype = 'U') AND (sysindexes.id = OBJECT_ID(sysobjects.name)) GROUP BY sysobjects.name ORDER BY 2 DESC;
{ "pile_set_name": "StackExchange" }
Q: Split file and know how many files were generated I'm using the following lines to split a file into smaller parts: split --line-bytes=100M -d $input $output/FILENAME echo "$input was split into ??? 100MB files." >> demo.log After that, I need to write in a log file how many smaller files were generated from this split. Is there any way to do that? A: The easiest way is to simply save the resulting pieces names in an array e.g. splitarr=($output/FILENAME*) and get the array length (number of elements) with ${#splitarr[@]}. This assumes the only filenames matching that pattern are those produced by the split command. You appear to be using gnu split so here are some other ways to do it: you could add the --verbose option (see man page for details) and just count the lines that split prints to stdout and save that into a variable: ct=$(split --verbose --line-bytes=100M -d $input $output/FILENAME | wc -l) You could get the same result with the less known option --filter: ct=$(split --filter='printf %s\\n;cat >$FILE' --line-bytes=100M -d $input $output/FILENAME | wc -l) Alternatively, if you know that only your split command will create files in that directory in the next N seconds you could use inotifywatch to gather statistics for e.g close_write event: inotifywatch . -t 20 -e close_write will watch the current dir for close_write events for the next 20 seconds and will output something like: Establishing watches... Finished establishing watches, now collecting statistics. total close_write filename 11 11 ./ so it's only a matter of extracting that number from the table (e.g. pipe it to awk 'END{print $2}'; also keep in mind the first two lines are printed on stderr)
{ "pile_set_name": "StackExchange" }
Q: Xamarin forms navigation page back button mvvm command Is there a property in XAML to set when back button pressed launch MVVM method through command? Or another way to do it avoiding code behind? A: I think you can use EventToCommandBehavior to bind NavigationPage.Popped, NavigationPage.PoppedToRoot events to a Command on XAML.
{ "pile_set_name": "StackExchange" }
Q: I am trying to upload data to server and data is in blob I am trying to upload data to server and data is in blob and the problem is when the file is empty it gets upload but it won't if file contain any data in it following is my code function uploadData() { var param = { subjectName: $("#ipName").val(), subjectID: $("#DocSubject").val(), typeID: $("#DocType").val(), year: $("#ipDate").val(), data: dataURL.substr(dataURL.indexOf(',') + 1, dataURL.length), }; Handler("Json", param, "UploadData"); } var dataURL; var handleFiles = function (event) { var input = event.target; var reader=new FileReader(); reader.onload=function(){ dataURL=reader.result; var output=document.getElementById('ipSelect'); output.src=dataURL; }; reader.readAsDataURL(input.files[0]); } Handler is .ashx file which save my data to sql server.I don't know what I am missing. A: FileReader() .readAsDataURL() method returns results asynchronously. You can pass dataURL to uploadData() call at load event of FileReader. Note also, that reader.result:dataURL is a data URI returned from .readAsDataURL(), not a Blob function uploadData(dataURL) { var param = { subjectName: $("#ipName").val(), subjectID: $("#DocSubject").val(), typeID: $("#DocType").val(), year: $("#ipDate").val(), data: dataURL.substr(dataURL.indexOf(',') + 1, dataURL.length) }; Handler("Json", param, "UploadData"); } var dataURL; var handleFiles = function (event) { var input = event.target; var reader=new FileReader(); reader.onload=function(){ dataURL=reader.result; var output=document.getElementById('ipSelect'); output.src=dataURL; uploadData(dataURL); // call `uploadData()` with `dataURL` as parameter }; reader.readAsDataURL(input.files[0]); }
{ "pile_set_name": "StackExchange" }
Q: Dial number with Name from iOS app I have found the answer on how to dial a number programmatically from an app. @IBOutlet weak var phoneNumberTextField: UITextField! ... @IBAction func phoneDialButton(sender: UIButton) { let phoneNumberToCall = phoneNumberTextField.text let url: NSURL = NSURL(string: "tel://\(phoneNumberToCall)")! UIApplication.sharedApplication().openURL(url) } What I am curious about is if I introduce a new field @IBOutlet weak var phoneNameTextField: UITextField! How would I go about putting that string as the name you are dialing when you make the call? Is it even possible? A: What you're asking for is not possible. The name that comes up when you dial a number is either the contact name associated with that number, or a suggested contact from your email. You would have to create a contact programmatically and associated the desired name with the number you want to dial, or update an existing contact if one for that phone number already exists.
{ "pile_set_name": "StackExchange" }
Q: bash command to remove lines which are present in other text file I am on bash I have two files added.txt and unmatched.txt , now imagine that all lines from added.txt are present in unmatched.txt . I want to remove lines from unmatched.txt which are present in added.txt . for example 1) added.txt apple ball 2) unmatched.txt cat dog apple rar ball 3) required output.txt cat dog rar A: Trivial to do with grep: $ cat added.txt cat dog $ cat unmatched.txt aardvark cat dog giraffe civet cat $ grep -F -vx -f added.txt unmatched.txt aardvark giraffe civet cat Prints just lines of unmatched.txt that don't exactly match lines of added.txt (-v inverts the usual meaning of grep).
{ "pile_set_name": "StackExchange" }
Q: Make variables from jquery function to be accessible from other functions I have a jquery function like this: (function($){ $.fn.myjqfunction = function(cfg){ var foo1, foo2; return this.each... }; })(jQuery); How can I make foo1 and foo2 to be accessible from outside (from another function like this)? These variables will store the state of some things that affect the entire document, and I want the other function to be aware of that... A: Declare them outside the function, i.e., global. You may want to put them in a namespace/object/module to be on the safe side. Which method is best depends on what you're actually doing with them. For example, if they're related to specific selectors, it might be "best" to attach them directly to the DOM elements using .data, or keep them inside another jQuery function, etc.
{ "pile_set_name": "StackExchange" }
Q: Find the minimal tank capacity to be able to travel from any city to any other There are $n$ cities in the country. The car can go from any city $u$ to city $v$, On this road it spends $w_{u,v} > 0$ fuel. At the same $w_{u,v}$ can differ from $w_{v, u}$. The task is to find the minimal tank capacity to be able to travel from any city to any other (possibly with refuels) in $O(n^2\log n)$. A: A possible solution may be to compute the all pair shortest path matrix and then select the largest value in the matrix. As long as |E|<<|V|^2 or the graph is not dense, your complexity constraint should be satisifed. Johnson's algorithm does it in O(|V|^2 log |V|+|V||E|). Refer to this for a better understanding of time complexity in case of Jhonson's Algorithm.
{ "pile_set_name": "StackExchange" }
Q: How to control column width in gridview? How can I make the GridView auto-resize the width of each column or fix the width of each column in Default.aspx? The problem I'm having is that some columns are too wide and that others are too narrow (data go to the next line). <div class="divNext"> <asp:ScriptManagerProxy ID="DisplayResultsScriptManager" runat="server"> </asp:ScriptManagerProxy> <asp:UpdatePanel ID="DisplayResultsUpdatePanel" runat="server" UpdateMode="Conditional"> <ContentTemplate> <div> <asp:GridView ID="GridViewX" RowStyle-Wrap="false" AllowSorting="true" GridLines="Vertical" OnSorting="GridViewX_Sorting" OnRowDataBound="GridViewX_RowDataBound" runat="server" Height="100" Width="100%" EnableViewState="true"> </asp:GridView> </div> <asp:Timer ID="ResultsTimer" Interval="60000" Enabled="true" runat="server" OnTick="DisplayResultsTimer_Tick"> </asp:Timer> </ContentTemplate> </asp:UpdatePanel> </div> A: You need to use BoundField or some other fields if you want more control over each column. Look Declarative Syntax Section of this page for other type of fields. Note: make sure AutoGenerateColumns="False" if you create columns by yourself. <asp:GridView ID="GridViewX" runat="server" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="Name" HeaderText="Name"> <ItemStyle Width="150px"/> </asp:BoundField> <asp:BoundField DataField="Address" HeaderText="Address"> <ItemStyle Width="50px"/> </asp:BoundField> </Columns> </asp:GridView> protected void Page_Load(object sender, EventArgs e) { GridViewX.DataSource = new List<Custom> { new Custom {Name = "Jon Doe", Address = "123 Street"}, new Custom {Name = "Merry Doe", Address = "123 Street"}, }; GridViewX.DataBind(); } public class Custom { public string Name { get; set; } public string Address { get; set; } }
{ "pile_set_name": "StackExchange" }
Q: Troubles with eso-pic package, later to update MiKTeK 2.9 I have a .tex document in which I use the logo of the research center as watermark. In order to insert this watermark, in my LaTeX file I always add the eso-pic package. In the past, I had never had problems with watermarks in my documents. But recently, I had to do maintenance of my LaTeX distribution (MiKTeX 2.9) and I used the option of “Update MiKTeX (Admin)”. In the Updateable Packages window, I selected all the packages which required to be updated. All the updated process was successful. Later of updating the packages, I tried to compile my .tex file with TecXnicCenter 2.02 (32B), the output profile that I used was Latex->pdf. The compilation process was aborted and I got the error message: pdflatex> ! LaTeX Error: File ‘eso-pic.sty’ not found. I checked the folder Program Files\MiKTeX 2.9\tex\latex and I found that eso-pic folder has the showframe.sty file. So, my sistem has the eso-pic package. Now, I have the eso-pic version 2.0f and before, I had the 2010/10/06 v2.0c of this package. I have reviewed the .log file in order to understand why MiKTeX can’t find the eso-pic.sty file, but I haven’t had success to figure out this problem. I also tried to review my .tex file to detect some mistake, but my code is right. Even I can’t get the pdf file with these lines: \documentclass[12pt]{book} \usepackage{graphicx} \DeclareGraphicsExtensions{.pdf,.png,.jpg} \graphicspath{{./figures/}} \usepackage{eso-pic} \newcommand\BackgroundPic{ \put(0,0){ \parbox[b][\paperheight]{\paperwidth}{% \vfill \centering \includegraphics[width=\paperwidth,height=\paperheight,keepaspectratio]{onu.png}% \vfill }}} \listfiles \begin{document} AddToShipoutPicture{\BackgroundPic} bla,bla,bla \end{document} Any idea about to figure out this problem. Thanks. A: I had the same problem, I used basic-miktex-2.9.4250. so, I try to replace the name "showframe.sty" with "eso-pic.sty". following this link http://web.mit.edu/texsrc/source/latex/ms/contrib/eso-pic.sty then do like this MikTex Options > Refresh FNDB and Update format. If it does not work, I suggest you to update your packages from MixTex Update Wizard and repeat again.
{ "pile_set_name": "StackExchange" }
Q: Question about configuration EEPROM or Flash I want to make an external (not related to Arduino) computer application that creates a big 'setup file' (like max. 64 KB). This setup file contains lookup tables (which are configurable and the tables with data themselves). This 'setup file' needs be stored in the Arduino. Now I thought of the following alternatives: Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM). Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB). Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted. Use a SD card and read information from there; however, I read 512 bytes SRAM is needed. To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms. Can you please give me some more information which alternative would work or not? Or maybe I missed out something trivial or an alternative is impossible? A: Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM). Perfectly viable - although an SPI Flash chip would be more appropriate. Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB). It is the bootloader that can write to flash. I don't thing the main program can write to flash, or it would wipe itself out. You may need a special bootloader with your own protocol and upload program to go with it. Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted. Perfectly viable, but tricky to say the least. Use a SD card and read information from there; however, I read 512 bytes SRAM is needed. Yes, 512 bytes of SRAM, since that is the size of one block on an SD card. But an UNO has 2048 bytes of SRAM - more than enough for SD card support. The SD card would be my route of choice. It's the easiest from a user's perspective (slip the card into their computer and copy the files), and pretty simple and straight forward to connect and program the Arduino for. To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms. If you know where in the file the byte are then you can seek() straight to them. Takes almost no time. 20ms is an eternity for a microcontroller.
{ "pile_set_name": "StackExchange" }
Q: How to find a specific column name in table design view? I have a table in my database in SQL server 2014 with a lot of columns, and when I want to find a column for modify properties, it is difficult to find that column, how can I find that column (ex: column name = "Birthdate"), has SSMS have any tools (such as find tool) for finding that column. A: If you start by looking at the table definition in the Object Explorer and expand the columns properties, you can simply type the first letter of the column you are looking for. If you keep hitting the same letter, SSMS will cycle through all the columns that start with that letter... if you then right click the column and and choose modify, it will open the designer at the right column... (using ssms 17.9.1 - but worth a try)
{ "pile_set_name": "StackExchange" }
Q: How to use Google Maps Stylers with jquery-ui-map plugin? i'm too weak on writing js. I need to build and customize a google map. For this i do use the jquery-ui-map plugin and this code: if ($("#map_canvas").length){ $('#map_canvas').gmap().bind('init', function(ev, map) { $("[data-gmapping]").each(function(i,el) { var data = $(el).data('gmapping'); $('#map_canvas').gmap('addMarker', {'id': data.id, 'tags':data.tags, 'position': new google.maps.LatLng(data.latlng.lat, data.latlng.lng), 'bounds':true }, function(map,marker) { $(el).click(function() { $(marker).triggerEvent('click'); }); }).click(function() { $('#map_canvas').gmap('openInfoWindow', { 'content': $(el).find('.info-box').html() }, this); }); }); }); } Where do i have to put in this generated variables: { stylers: [ { lightness: 7 }, { saturation: -100 } ] } Links i used: http://code.google.com/p/jquery-ui-map/ http://gmaps-samples-v3.googlecode.com/svn/trunk/styledmaps/wizard/index.html A: There are many places to put it, e.g. into the instantiating of the map: now: $('#map_canvas').gmap() //...more code then: $('#map_canvas').gmap({styles:[{stylers:[{lightness:7},{saturation:-100}]}]}) //...more code the gmap-constructor accepts all options that google.maps.Map.setOptions() accepts. One of those options is "style", which is expected to be an array with google.maps.MapTypeStyle's (your generated output is a MapTypeStyle)
{ "pile_set_name": "StackExchange" }
Q: Robocopy issue with *.txt files EDITED: I have specific problem with robocopy in PowerShell. My entire code looks like this: $yesterday = (Get-Date).AddDays(-1).Date.ToShortDateString() $ifExistFilesToCopy = (Get-ChildItem *.txt | Where-Object {$_.CreationTime.Date -le $yesterday}) IF ($ifExistFilesToCopy) { $i=1 DO { $yesterdayDay = ((Get-Date).AddDays(-$i).Date.ToShortDateString()) $yesterdayFiles = (Get-ChildItem *.txt | Where-Object {$_.CreationTime.Date -eq $yesterdayDay}) IF ($yesterdayFiles) { & robocopy $PSScriptRoot "$PSScriptRoot\$yesterdayDay" $yesterdayFiles /copyall } $i++ } WHILE (!($yesterdayFiles -contains (Get-ChildItem *.txt | Sort CreationTime | select -First 1))) } pause My main problem is: When I put *.txt after Get-ChildItem, robocopy does not copy .txt files, because it gives result back like $yesterdayFiles = '' while this variable contains information about this files and I am sure about that. Without *.txt after Get-ChildItem the whole script works perfect for me: it copies files to different folders and everything works just fine. As I said earlier it crashes only when I try to specify extension of file. I have 2 files from 21 July (file1.txt, file2.txt) and 1 file from 21 April (file3.txt), all in C:\, and there's an error that appears in my console: ERROR! invalid parameter #3: C:\file1.txt and after that another: ERROR! invalid parameter #3: C:\file3.txt I Tried using Get-ChildItem –Include *.txt and also I tried to give *.txt as parameter to robocopy, but it didn't work as well. Any idea what's wrong? A: Your code errors out, because $yesterdayFiles contains FileInfo objects, which are expanded to their full path when used in the robocopy statement. robocopy syntax, however, is robocopy <Source> <Destination> [<File>[ ...]] [<Options>] wherein <File> represents a file name or a pattern for a file name (without path). Also, I think the logic in your while condition is a little ... unorthodox. Even though !($yesterdayFiles -contains (Get-ChildItem *.txt | Sort CreationTime | select -First 1)) should terminate the loop after the currently processed group of files contains the oldest file in the directory you may get better results (and better maintainability) with a more PoSh approach like this: $src = $PSScriptRoot $fmt = 'yyyy-MM-dd' $yesterday = (Get-Date).AddDays(-1).Date Get-ChildItem *.txt | Where-Object { $_.CreationTime.Date -le $yesterday } | Group-Object { $_.CreationTime.Date.ToString($fmt) } | Sort-Object Name | ForEach-Object { $dst = Join-Path $PSScriptRoot $_.Name $files = $_.Group | Select-Object -Expand Name & robocopy $src $dst $files /copyall }
{ "pile_set_name": "StackExchange" }
Q: vb.net console application only works once I'm just learning to code in vb.net and am currently messing around with VB.net console applications. I can't for the life of me figure something out. It's probably been asked before on here, but I can't find anything by searching. I just coded a simple "check if Y or N was entered. If y/n was entered, display 'you have entered y/n'" program, and it works fine the first time. However, after the first entry I can't get the process to repeat. All I get back is blank space. For example, if i enter y, I'll get the corresponding message. however, if after that I enter n I get nothing back. here's the code: Module Module1 Sub Main() Console.Title = "Hello" Console.WriteLine("Y or N") Dim line As String line = Console.ReadLine() Do Until line = "exit" If line = "y" Then Console.WriteLine("you have chosen y") Console.ReadLine() ElseIf line = "n" Then Console.WriteLine("you have chosen n") Console.ReadLine() End If line = "" Loop End Sub End Module I'm assuming the answer's super simple, but I can't seem to figure it out or fin the answer online. Thanks for the help. A: You have to store the value of Console.ReadLine() in the Line string. Module Module1 Sub Main() Console.Title = "Hello" Console.WriteLine("Y or N") Dim line As String line = Console.ReadLine() Do Until line = "exit" If line = "y" Then Console.WriteLine("you have chosen y") ElseIf line = "n" Then Console.WriteLine("you have chosen n") End If line = Console.ReadLine() Loop End Sub End Module
{ "pile_set_name": "StackExchange" }
Q: Setting slower shutter speeds for canon 5d mark ii How do I set shutters speeds slower than 1/30 on canon 5d markII ? In the manual setting I cannot seem to scroll down slower than 1/30. A: If the top of camera LCD display and viewfinder are showing [30"] (without the brackets) the selected shutter speed is 30 seconds which is the same as one-half minute. For shutter speeds slower than 30 seconds you will need to use Bulb mode (B on the Mode Dial) and time the shot with a watch or use a cable release with a built in timer. If the display in the viewfinder and top of camera LCD is showing [30] (without the brackets) the selected shutter speed is 1/30 second. On quick way to double check is to use the Quick Control screen. While shooting in M or Tv mode press the small, 8-way button at the top right of the LCD screen on the back of the camera straight down. The Quick control screen will appear on the LCD and the selected shutter speed (Tv) will be displayed in the upper left corner. If you have selected a speed of 1/4 second or shorter the Tv will be displayed as a fraction [1/30]. For shutter speeds between 1/4 and 1 second the display will show [0"] followed by a number denoting tenths of seconds. So [0"3] is 3/10 seconds, [0"4] is 4/10 seconds, and so on. If you have selected a shutter time of one second or longer, the number of seconds followed by ["] and then tenths of seconds, if any, will be displayed [30"] Another way to see the Quick Control Screen is to use the Custom Functions to map the SET button to turn on the Quick Control Screen. Set C. Fn IV:3 (Assign SET Button) to option 5: Quick Control screen. When in normal shooting mode press the Set button in the middle of the large control dial on the back of the camera to turn on the Quick Control Screen.
{ "pile_set_name": "StackExchange" }
Q: Convert Calendar to XMLGregorianCalendar with specific formatting I am having some issues in converting a calendar object to an XMLGregorian calendar in the format of YYYY-MM-DD HH:mm:ss. My current code is: Calendar createDate = tRow.getBasic().getDateCreated(0).getSearchValue(); Date cDate = createDate.getTime(); GregorianCalendar c = new GregorianCalendar(); c.setTime(cDate); XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); which returns a date of 2013-01-03T11:50:00.000-05:00. I would like it to read 2013-01-03 11:50:00. I have checked a bunch of posts, which use DateFormat to parse a string representation of the date, however my dates are provided to me as a Calendar object, not a string. I'd appreciate a nudge in the right direction to help me figure this one out. A: An XMLGregorianCalendar has a specific W3C string representation that you cannot change. However, you can format a Date with SimpleDateFormat. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateStr = dateFormat.format(cDate); You can get a Date object from a XMLGregorianCalendar object as follows: xmlCalendar.getGregorianCalendar().getDate()
{ "pile_set_name": "StackExchange" }
Q: NoMethodError (undefined method `created_at' for nil:NilClass) I have the following Rails code in my conversations_controller: A user may be : master or rookie. @conversations = current_user.master.conversations.all @conversations = @conversations.sort_by { |c| c.messages.last.created_at }.reverse But on running this I'm getting a no method error for created_at. If I do a puts like this: puts "Sorted: #{@conversations.map { |c| c.messages.last}}" this gives me the following response: Sorted: [#<Message id: 9, content: "some content", user_id: 3, conversation_id: 1, created_at: "2017-03-01 00:00:36", updated_at: "2017-03-01 00:00:36", attachment_url: []>, nil, #<Message id: 11, content: "new message", user_id: 3, conversation_id: 6, created_at: "2017-03-01 15:15:58", updated_at: "2017-03-01 15:15:58", attachment_url: []>] If I'm getting created_at then why can't I extract the last messages created_At to compare and sort? On doing a simple puts "The conversations sorted are: #{@conversations.map { |c| c.messages}}" Gives me the following response: The conversations sorted are: [#<ActiveRecord::Associations::CollectionProxy [#<Message id: 1, content: "Hey there! This is my first message.", user_id: 1, conversation_id: 1, created_at: "2017-02-28 23:57:46", updated_at: "2017-02-28 23:57:46", attachment_url: []>, #<Message id: 2, content: "Thank you for your message. I am a coach.", user_id: 3, conversation_id: 1, created_at: "2017-02-28 23:57:46", updated_at: "2017-02-28 23:57:46", attachment_url: []>, #<Message id: 9, content: "adsdadasd", user_id: 3, conversation_id: 1, created_at: "2017-03-01 00:00:36", updated_at: "2017-03-01 00:00:36", attachment_url: ["https://ace-up-www.s3.amazonaws.com/message-attachments%2Fbd450b1e-f85c-47ec-94c7-c539809f8d68%2Frecommendation-bg.jpg"]>]>, #<ActiveRecord::Associations::CollectionProxy []>, #<ActiveRecord::Associations::CollectionProxy [#<Message id: 10, content: "Add a new message", user_id: 8, conversation_id: 6, created_at: "2017-03-01 14:58:29", updated_at: "2017-03-01 14:58:29", attachment_url: []>, #<Message id: 11, content: "new message", user_id: 3, conversation_id: 6, created_at: "2017-03-01 15:15:58", updated_at: "2017-03-01 15:15:58", attachment_url: []>]>] As you can see there is an empty #<ActiveRecord::Associations::CollectionProxy []> which is probably getting translated to nil. Any help in debugging this? A: The error occured when you tried to get the created at attribute of the converstions last message which actually dont have any messages with it. @conversations = current_user.master.conversations.joins(:messages) @conversations = @conversations.sort_by { |c| c.messages.last.created_at }.reverse By joining the messages with the conversations only the conversation with atleast one message will be retrieved so by that i think the issue get fixed.
{ "pile_set_name": "StackExchange" }
Q: What's the best way to set a windows service description in .net I have created a C# service using the VS2005 template. It works fine however the description of the service is blank in the Windows Services control applet. A: Create a ServiceInstaller and set the description private System.ServiceProcess.ServiceInstaller serviceInstaller = new System.ServiceProcess.ServiceInstaller(); this.serviceInstaller.Description = "Handles Service Stuff"; A: To clarify on how to accomplish this without using code: Add a service installer to your project as described here: http://msdn.microsoft.com/en-us/library/ddhy0byf%28v=vs.80%29.aspx Open the installer (e.g. ProjectInstaller.cs) in Design view. Single-click the service installer component (e.g. serviceInstaller1) or right-click it and choose Properties. In the Properties pane, set the Description and/or DisplayName (this is also where you set StartType etc.) Description is probably all you want to change, although if you want to give a slightly more human-readable DisplayName (the first column in Services manager) you can also do so. If desired, open the auto-generated designer file (e.g. ProjectInstaller.Designer.cs) to verify that the properties were set correctly. Build the solution and install using installutil.exe or other means. A: After you create your service installer project in VS2010, you need to add an override to the Install method in the class created by VS to create the registry entry for your service description. using System; using System.Collections; using System.ComponentModel; using System.Configuration.Install; using System.ServiceProcess; using Microsoft.Win32; namespace SomeService { [RunInstaller(true)] public partial class ProjectInstaller : System.Configuration.Install.Installer { public ProjectInstaller() { InitializeComponent(); } /// <summary> /// Overriden to get more control over service installation. /// </summary> /// <param name="stateServer"></param> public override void Install(IDictionary stateServer) { RegistryKey system; //HKEY_LOCAL_MACHINE\Services\CurrentControlSet RegistryKey currentControlSet; //...\Services RegistryKey services; //...\<Service Name> RegistryKey service; // ...\Parameters - this is where you can put service-specific configuration // Microsoft.Win32.RegistryKey config; try { //Let the project installer do its job base.Install(stateServer); //Open the HKEY_LOCAL_MACHINE\SYSTEM key system = Registry.LocalMachine.OpenSubKey("System"); //Open CurrentControlSet currentControlSet = system.OpenSubKey("CurrentControlSet"); //Go to the services key services = currentControlSet.OpenSubKey("Services"); //Open the key for your service, and allow writing service = services.OpenSubKey("MyService", true); //Add your service's description as a REG_SZ value named "Description" service.SetValue("Description", "A service that does so and so"); //(Optional) Add some custom information your service will use... // config = service.CreateSubKey("Parameters"); } catch (Exception e) { throw new Exception(e.Message + "\n" + e.StackTrace); } } } } http://msdn.microsoft.com/en-us/library/microsoft.win32.registrykey.aspx http://www.codeproject.com/KB/dotnet/dotnetscmdescription.aspx
{ "pile_set_name": "StackExchange" }
Q: C# XML Deserialization W/ Default Values I've got an object that is being serialized / deserialized via the XmlSerializer in C#, .NET 3.5. One of the properties (and more in the future) is a collection: List where T is an enum value. This serializes / deserializes fine. We are also using a "default values" mechanism to provide default values for the object, in case the serialized version doesn't have any value set. as a simple example, here is what we are dong: public enum MyEnum { Value1, Value2 } public class Foo { public List SomeSetting{ get; set; } public Foo() { SomeSetting = new List(); SomeSetting.Add(MyEnum.Value1); SomeSetting.Add(MyEnum.Value2); } } This code works fine for setting the default values of SomeSetting when the object is constructed. However, when we are deserializing an xml file that has values for SomeSetting, this default value setup is causing problems: the xml deserializer does not 'reset' the SomeSetting collection - it does not wipe it clean and populate with new data. Rather, it adds on to the data that is already there. So, if the xml file has Value1 serialized into it, when I deserialize that file, i end up with SomeSettings having {Value1, Value2, Value1} as the values being stored. I need a way for the xml deserialization process to allow my default values to exist when there is no data for SomeSetting in the xml document, and also to wholesale replace the SomeSetting values when there is data in the xml document. How can I do this? FYI - this is not the only property in the document. The document does exist, and is being serialized / deserialized for the other 'simple' values. This is the property that is causing problems, though. I have to support this scenario because I need to do this a lot, now. A: FYI - i solved this with the IXMLSerializable interface. Note that this code is very specific to my needs in this one class, so YMMV. public void WriteXml(XmlWriter writer) { foreach (PropertyInfo prop in GetType().GetProperties()) { XmlIgnoreAttribute attr; if (prop.TryGetAttribute(out attr)) continue; if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition().Equals(typeof(List))) { XmlSerializer serializer = new XmlSerializer(prop.PropertyType, new XmlRootAttribute(prop.Name)); serializer.Serialize(writer, prop.GetValue(this, null)); } else { writer.WriteElementString(prop.Name, prop.GetValue(this, null).ToString()); } } } public void ReadXml(XmlReader reader) { if (reader.IsEmptyElement) return; XmlDocument xDoc = new XmlDocument(); xDoc.Load(reader); Type type = GetType(); foreach (XmlNode node in xDoc.DocumentElement.ChildNodes) { PropertyInfo prop = type.GetProperty(node.Name); if (prop != null && prop.CanWrite) { object value; if (prop.PropertyType.IsEnum) { string stringValue = node.InnerText; value = Enum.Parse(prop.PropertyType, stringValue); } else if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition().Equals(typeof(List))) { Type enumType = prop.PropertyType.GetGenericArguments()[0]; value = Activator.CreateInstance(prop.PropertyType); var addMethod = value.GetType().GetMethod("Add"); foreach (XmlNode subNode in node.ChildNodes) { object enumValue = Enum.Parse(enumType, subNode.InnerText); addMethod.Invoke(value, new[] { enumValue }); } } else { string stringValue = node.InnerText; value = Convert.ChangeType(stringValue, prop.PropertyType); } prop.SetValue(this, value, null); } } } public XmlSchema GetSchema() { return null; }
{ "pile_set_name": "StackExchange" }
Q: pgfplots using strings *from data table* as x axis labels in bar chart I've seen some of the other threads on using strings as x axis labels, but nothing that fits my situation. I'm trying to create a bar chart from a CSV file. I can do it so long as everything in the data is numeric. However, in my actual data table, the first row is multi-word string descriptions. I need these descriptions to be the x axis labels for each bar. I've tried symbolic x coords, but I get the "could not parse input as a floating point number" error. I've also tried adding an ID column and using that as the x values, and assigning xtick labels as the string descriptors. I get the same issue that way. Here's an attempt at an MWE: \documentclass{article} \usepackage{lmodern} \usepackage{tikz} \usepackage{pgfplots} \usepackage{pgfplotstable} \begin{document} \pgfplotstabletypeset[columns/category/.style={string type},col sep=comma]{Book3.csv} \vspace{1cm} \begin{tikzpicture} \begin{axis}[ ybar, xlabel=Xstuff, ylabel=Value, symbolic x coords={cat a,cat b,cat c,cat d,cat e,cat f,cat g}, %xtick labels={cat a,cat b,cat c,cat d,cat e,cat f,cat g},% this is from when i tried the xtick label method xtick=data, nodes near coords, nodes near coords align={vertical}] \addplot table[x=category,y=value]{Book3.csv}; %\addplot table[x=category,y=value]{Book3.csv};& again, from trying the xtick label method \end{axis} \end{tikzpicture} \end{document} Since I suspect this might get answered quickly by you chart gurus, I have a follow-up question: I have to do a bunch of these charts, and I would like to automate the symbolic x coords process. Is there a way to populate the dictionary of accepted x coords by reading a column of the data? (something like symbolic x coords={columns/category/{Book3.csv}} )? Book3.csv looks like this (ignore the ID column if using the xtick label method): ID, category, value, value 2 1, cat a, 1, 7 2, cat b, 2, 6 3, cat c, 3, 5 4, cat d, 4, 4 5, cat e, 5, 3 6, cat f, 6, 2 7, cat g, 7, 1 A: Instead of trying to populate the list of permitted symbolic coordinates, I would recommend to use the xticklabels from table key to set the labels. You don't need to provide an explicit ID column for this to work, you can just use x expr=\coordindex. As long as you also use xtick=data, the labels will always be assigned to the correct bars. \documentclass{article} \usepackage{pgfplots} \usepackage{pgfplotstable} \usepackage{filecontents} \begin{filecontents}{testdata.csv} category, value, value 2 cat a, 1, 7 cat b, 2, 6 cat c, 3, 5 cat d, 4, 4 cat e, 5, 3 cat f, 6, 2 cat g, 7, 1 \end{filecontents} \pgfplotstableread[col sep=comma]{testdata.csv}\datatable \makeatletter \pgfplotsset{ /pgfplots/flexible xticklabels from table/.code n args={3}{% \pgfplotstableread[#3]{#1}\coordinate@table \pgfplotstablegetcolumn{#2}\of{\coordinate@table}\to\pgfplots@xticklabels \let\pgfplots@xticklabel=\pgfplots@user@ticklabel@list@x } } \makeatother \begin{document} \begin{tikzpicture} \begin{axis}[ ybar, ymin=0, xlabel=Xstuff, ylabel=Value, flexible xticklabels from table={testdata.csv}{category}{col sep=comma}, xticklabel style={text height=1.5ex}, % To make sure the text labels are nicely aligned xtick=data, nodes near coords, nodes near coords align={vertical}] \addplot table[x expr=\coordindex,y=value]{\datatable}; \end{axis} \end{tikzpicture} \end{document}
{ "pile_set_name": "StackExchange" }
Q: the map doesn't show up i have a problem with my simple google map in android here is my MapsActivity.java package udin.MapsActivity; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; import android.os.Bundle; public class MapsActivity extends MapActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected boolean isRouteDisplayed() { return false; } } and this is my main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <com.google.android.maps.MapView android:id="@+id/mapView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:enabled="true" android:clickable="true" android:apiKey="00j2bA4ivSvH0cSDJJ4aiPiVCq_OSH0adwf6I2w" /> </RelativeLayout> and this is my AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="udin.MapsActivity" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MapsActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <uses-library android:name="com.google.android.maps" /> </application> <uses-permission android:name="android.permission.INTERNET" /> </manifest> when i run this, its have no error in DDMS but why the map doesn't show up like this the code for GoogleMap API is right... yesterday i try this code is work for me....but now why this isn't work? can anyone help??why this is happening? i will really appreciate if you can help me Thank You A: Try putting the uses-permissions tags above the application in the manifest file. Also, I think that occasionally the signing between Eclipse and the Emulator gets messed up, and restarting both can sometimes fix the issue.
{ "pile_set_name": "StackExchange" }
Q: The image of a polynomial curve $p:F\to F^2$ lies in the zero set of another polynomial $q:F^2\to F$ Suppose $\mathbb{F}$ is an infinite field. Define $p:\mathbb{F}\to\mathbb{F}^2$ as $p(t)=(p_1(t),p_2(t))$ where $p_1,p_2:\mathbb{F}\to\mathbb{F}$ are polynomials. Show that the image of $p$ lies in the zero set of some polynomial $q:\mathbb{F}^2\to\mathbb{F}$. (Bonus) Give a lower bound to the degree of $q$. Any polynomial $q:\mathbb{F}^2\to\mathbb{F}$ of degree $D$ looks like $$q(x,y)=\sum_{0\leq i+j\leq D}c_{ij}x^iy^j\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;(1)$$ where $c_{ij}\in\mathbb{F}$. Now finding $q$ is solving the equation $$q(p(t))=q(p_1(t),p_2(t))=0.(2)$$ Plugging (1) in (2) we will have the equation $$\sum_{0\leq i+j\leq D}c_{ij}p_1(t)^ip_2(t)^j=0,\;\;\text{ for all }t\in\mathbb{F}.$$ Since this is true for all $t\in\mathbb{F}$ and the field is infinite, we can choose $t_1,t_2,\ldots,t_{N=\frac{(D+1)(D+2)}{2}}$ values for $t$ from $\mathbb{F}$ so that we get a system \begin{cases} \sum_{0\leq i+j\leq D}c_{ij}p_1(t_1)^ip_2(t_1)^j=0\\ \vdots\\ \sum_{0\leq i+j\leq D}c_{ij}p_1(t_N)^ip_2(t_N)^j=0 \end{cases} So now we want to show that there exists those $t_1,t_2,\ldots,t_N$ that make this system not invertible. How to do that? A: You are working too hard. To say that $p_1$ and $p_2$ satisfy a polynomial relationship is equivalent to saying that the polynomials $\{ p_1^i p_2^j \}$ must be linearly dependent. We can prove this using a degree argument: if $\deg p_k = d_k$, then $p_1^i p_2^j$ has degree $d_1 i + d_2 j$. The number of these polynomials of degree less than or equal to $D$ is then the number of nonnegative integer solutions to the inequality $$d_1 i + d_2 j \le D.$$ It's not hard to see that this number grows like the area of a triangle with side lengths $\frac{D}{d_1}, \frac{D}{d_2}$, so grows something like $\frac{D^2}{2 d_1 d_2}$, which in particular is quadratic in $D$. On the other hand, the dimension of the space of polynomials of degree less than or equal to $D$ is $D+1$, which is linear in $D$. So as soon as $D$ is large enough there must be a linear dependence, and "large enough" is around $2 d_1 d_2$.
{ "pile_set_name": "StackExchange" }
Q: When you have 5 instead of 4, what's the word instead of "quadrant"? ...or, to phrase it differently, like one of those silly SAT questions... please help me fill in this blank: 4 is to 5 as "quadrant" is to ???? (Does that make sense?) A: Though a very rare word, that would be a quintant. A: Though "quintant" seems more correct to me for English Language, in practical English Usage the answer is, surprisingly, quadrant. For example, the city of Portland, Oregon, US, is divided into five parts that they still call "quadrants:" Folks in the city of Richmond, Virginia, USA also refers to five quadrants when discussing results of a poll by a small business association: Extending beyond the map example OP asked about, a company called JDA also announces and reports itself as "the only company recognized as a leader in ALL FIVE Gartner Supply Chain Magic Quadrants!" Finally, looking at Google Ngrams, "quintants" is not found in use (in Google's English corpus) even going back to 1800 while "five quadrants" is more common, not even counting instances where there are descriptive words between the two terms:
{ "pile_set_name": "StackExchange" }
Q: ¿Por qué las partes del cuerpo toman una -i- antes de componerlas con un adjetivo? Acabo de ver en una de estas imágenes que pone el Windows 10 de fondo un pájaro llamado "monarca nuquinegro". Eso me llevó a pensar que las partes del cuerpo (y no sé si pasa con otros sustantivos) toman una i antes de ser compuestas con un adjetivo. Se me ocurre patizambo, por ejemplo, aunque también existen patiblanco, manirroto, ojijunto, e incluso en términos inventados como "ojiplático" o "cabecicubo". ¿Cuál es la causa de esta i ante adjetivos? ¿De dónde viene? ¿Sucede con otros sustantivos que no denoten partes del cuerpo? Entiendo que esta i es diferente de la que aparece en compuestos como blanquinegro, en los que la i es la conjunción y integrada en la palabra. A: Según este interesante trabajo de investigación que he encontrado en Internet, el uso de esa "i" no está en absoluto limitado a partes del cuerpo y puede observarse en palabras compuestas de múltiples significados. Según dicen los autores, en los compuestos de origen latino prevalece la desinencia "i", mientras que en los de origen griego el enlace ocurre con "o". Tenemos así pares como: avicultura/ornitología, morbífico/patógeno, calorímetro/termómetro, pescívoro/ictiófago, unicolor/monocromo, vinicultura/enología. En cuanto al origen de esa "i", dicen los autores: Sentado el principio de que los compuestos latinos se integran usualmente por la vocal temática i cabe preguntarse de dónde deriva dicho cambio interno. Aunque el campo parece poco estudiado, una filóloga de enjundia sugiere que deriva «posiblemente del genitivo latino». Desde el punto de vista morfosemántico, el genitivo latino tenía varias funciones que frecuentemente en las lenguas romances establecen el régimen con la preposición "de", lo cual, bien mirado, tiene validez para los compuestos atributivos, ya que «ojinegro» designa al ser de ojos negros o negro de ojos. A: Si entiendo bien la pregunta, aquí estamos hablando de una clase restringida de compuestos: los adjetivos formados por una fusión de sustantivo + adjetivo. En un libro sobre compuestos en español encuentro un largo análisis de esta clase de compuestos. Si bien estos compuestos son casi todos de la forma N-i-Adj, algunos no tienen -i- intermedia, como cabizbajo. Sin embargo todos pertenecen claramente a un mismo tipo, referido casi siempre a partes del cuerpo y con otras varias características semánticas. Estos compuestos no son de origen latino, porque los adjetivos compuestos latinos no se formaban de esa manera sino con el orden adjetivo + sustantivo. Hay ejemplos similares, pero no idénticos, en italiano y catalán, pero no se trata de una derivación productiva (mientras que en español sí lo es). En catalán la forma preferida del sustantivo es la forma completa (alallarg "alilargo", camacurt "piernicorto"). Según este análisis, lo que vemos en castellano es el radical del sustantivo sin desinencia, al cual se le añade por motivos de composición la -i-, y luego el adjetivo. A fines del siglo XIII aparecen en castellano formas con la raíz desnuda como tiestherido ("herido en la cabeza", figurativo por "loco"), con la raíz acortada como racorto (con ra < rabo), y con la raíz desnuda más una vocal intermedia, que puede ser -i- (barbirrapado) o también -e- (cuellealuo "de cuello albo, cuelliblanco"). Entre el siglo XVI y el XVII aparecen muchos más adjetivos de este tipo y quedan descartadas las varias formas alternativas en favor de la moderna, con -i- intermedia. A: Dado que nadie la ha citado aún, quiero comentar que este tipo de construcciones se trata ampliamente en la Nueva Gramática de la RAE, en los párrafos 11.7h y siguientes. La pauta N-i-A es la más productiva del español entre todas las que dan lugar a compuestos adjetivales de sustantivo y adjetivo. A ella pertenecen barbilampiño, bracicorto, narilargo, ojizarco, pernilargo y otros muchos adjetivos que se predican mayoritariamente de las personas y los animales. La Gramática concuerda con Gustavson en cuanto al origen latino de la construcción: Este esquema se remota al latín (barbirāsus), donde alternaba con la pauta que presentaba el sustantivo en segunda posición: aureispīnus ('de espina dorada'), longimănus ('de mano larga'), versipellis ('que muda de piel'). La pauta A-i-N se ha conservado en español en curvilíneo o rectilíneo. La vocal -i- de estos compuestos procedía de un genitivo latino, pero ya en latín se propagó de los sustantivos que la contenían (agrilĕgus, coeligĕnus, florĭfer) a otros en los que no estaba presente, pero que la aceptaron como vocal de enlace, como aquilĭfer (de aquĭla, -ae); fructĭfer (de fructus, -us); fluctĭger, fluctisŏnus y fluctivăgus (de fluctus, -us); herbĭfer (de herba, -ae); terrĭgena (de terra, -ae), y otros muchos. Sobre su uso actual: Se han observado algunas restricciones en lo relativo al tipo de sustantivo con el que se forman estos compuestos. Constituyen el grupo más numeroso los que se refieren a partes del cuerpo de las personas y de los animales. Pero no se limita a esto: El nombre se refiere a una prenda de vestir, en lugar de a una parte del cuerpo, en faldicorta ('corta de faldas') o capipardo ('de capa parda' y, por extensión, 'del pueblo bajo'). Sobre el adjetivo: También existen restricciones que afectan a los adjetivos con los que se forman los compuestos N-i-A. Muchos de ellos designan colores (albo, blanco, negro, rojo, rubio, zarco); otros expresan propiedades físicas, normalmente referidas al tamaño o la forma de lo que se caracteriza: alto, ancho, bajo, corto, gordo, espeso, largo, redondo, como en barbiespeso, cabeciancho, cañihueco, carirredondo u ojimoreno. En general, son mucho más numerosos en esta pauta los adjetivos que expresan carencias o defectos (cojo, hueco, ralo, tuerto, zambo) que los que destacan algún aspecto positivo (alegre, lindo, tierno). El adjetivo además puede ser un participio, como en barbiteñido, boquiabierto, carilavado, cuellierguido, labihendido, manirroto...
{ "pile_set_name": "StackExchange" }
Q: Issue with HTML5 audio control in Visual Studio 2010 and ASP.NET MVC I am trying to add HTML5 audio control to my page. Here's the code: <audio src="../../Content/BattleNet_MusicLoop.ogg" controls="controls" autoplay="autoplay" loop="loop"> Your browser does not support the new HTML5 audio element. </audio> When I click debug, I can see the audio player for about a second and then it turns dark gret with light "x" icon in the middle. I clicked on "Copy Audio Source" and the source seems to be correct. Browser is not the issue because it's a Firefox 4.0 Beta 1. It plays this exact HTML5 audio player fine on http://www.w3schools.com/html5/tag_audio.asp. That's where I got it from by the way. I am using Visual Studio 2010 HTML5 add-in by Mikhail Arkhipov. My project is based on ASP.NET MVC 2 and .NET Framework 3.5 Any ideas what could be causing this issue? A: You have to upload the song to a server, for some reason firefox can't play the song if it's on the localhost, try to upload the file to some host like toofiles and get the url and use it as src example: <audio autoplay="autoplay" controls="controls" > <source src="http://dl.toofiles.com/vaaoje/audios/rooster.ogg" type="audio/ogg" /> <source src="http://dl.toofiles.com/vaaoje/audios/rooster.mp3" type="audio/mpeg"/> </audio> the ogg file is for firefox and the mp3 file for chrome and IE.
{ "pile_set_name": "StackExchange" }
Q: How is a counterpoise corrected geometry optimization done? I understand the problem of basis set superposition error (BSSE) and I know how the counterpoise correction for single point energies is calculated. Today I found out that many software packages allow for counterpoise correction during optimization calculations, but how does this actually work, especially for methods where analyical gradients are used for optimization? During geometry optimization we calculate the first derivative of the energy to get energy gradients which we follow down to our minima. I understand that I could use counterpoise correction if I calculate those gradients numerically, which is quite easy to understand but very expensive to do, but it seems that counterpoise can also be used in combination with analytical gradients. How is the counterpoise implemented to get counterpoise corrected gradients? A: Background For a system consisting of two molecules (monomers or fragments are also used) X and Y, the binding energy is $$ \Delta E_{\text{bind}} = E^{\ce{XY}}(\ce{XY}) - [E^{\ce{X}}(\ce{X}) + E^{\ce{Y}}(\ce{Y})] \label{eq:sherrill-1} \tag{Sherrill 1} $$ where the letters in the parentheses refer to the atoms present in the calculation and the letters in the superscript refer to the (atomic orbital, AO) basis present in the calculation. The first term is the energy calculated for the combined X + Y complex (the dimer) with basis functions, and the next two terms are energy calculations for each isolated monomer with only their respective basis functions. The remainder of this discussion will make more sense if the complex geometry is used for each monomer, rather than the isolated fragment geometry. The counterpoise-corrected (CP-corrected) binding energy [1] to correct for basis set superposition error (BSSE) [2] is defined as $$ \Delta E_{\text{bind}}^{\text{CP}} = E^{\ce{XY}}(\ce{XY}) - [E^{\ce{XY}}(\ce{X}) + E^{\ce{XY}}(\ce{Y})] \label{eq:sherrill-3} \tag{Sherrill 3} $$ where the monomer calculations are now performed in the dimer/complex basis. Let's explicitly state how this works for the $E_{\ce{XY}}(\ce{X})$ term. The first molecule X contributes nuclei with charges, basis functions (AOs) centered on those nuclei, and electrons that will count to the final occupied molecular orbital (MO) index into the MO coefficient array. There is no reason why additional AOs that are not centered on atoms can't be added to a calculation. Depending on their spatial location, if they're close enough to have significant overlap, they may combine with atom-centered MOs, increasing the variational flexibility of the calculation and lowering the overall energy. Put another way, place the AOs that would correspond to molecule Y at their correct positions, but don't put the nuclei there, and don't consider the number of electrons they would contribute to the total number of occupied orbitals. This means that for the full electronic Hamiltonian $$ \hat{H}_{\text{elec}} = \hat{T}_{e} + \hat{V}_{eN} + \hat{V}_{ee} $$ calculating the electron-nuclear attraction $\hat{V}_{eN}$ term is now different. Considered explicitly in matrix form in the AO basis, $$ \begin{align*} V_{\mu\nu} &= \int \mathop{d\mathbf{r}_{i}} \chi_{\mu}(\mathbf{r}_{i}) \left( \sum_{A}^{N_{\text{atoms}}} \frac{Z_{A}}{|\mathbf{r}_{i} - \mathbf{R}_{A}|} \right) \chi_{\nu}(\mathbf{r}_{i}) \\ &=\sum_{A}^{N_{\text{atoms}}} Z_{A} \left< \chi_{\mu} \middle| \frac{1}{r_{A}} \middle| \chi_{\nu} \right> \end{align*} $$ there are now fewer terms in the summation, since the nuclear charges from molecule Y are zero (the atoms just aren't there), but the number of $\mu\nu$ are the same as for the XY complex. This and the $\hat{T}_{e}, \hat{V}_{ee}$ terms aren't really mathematically or functionally different then; this is more to show where the additional basis functions enter, or to show where nuclei appear in the equations [3]. These atoms that don't have nuclei or electrons, only basis functions, are called ghost atoms. Sometimes you also see the term ghost functions, ghost basis, or ghost {something} calculation. Adding the basis of monomer Y to make the full "dimer basis" means taking the monomer X and including basis functions at the nuclear positions for Y. Geometry optimization Now to calculate the molecular gradient, that is, the derivative of the energy with respect to the $3N$ nuclear coordinates. This is the central quantity in any geometry optimization. For the sake of simplicity, consider a steepest descent-type update of the nuclear coordinates $$ R_{A,x}^{(n+1)} = R_{A,x}^{(n)} - \alpha \frac{\partial E_{\text{total}}^{(n)}}{\partial R_{A,x}} \label{eq:steepest-descent} \tag{Steepest Descent} $$ where $n$ is the optimization iteration number, $\alpha$ is some small step size with units [length2][energy], and the last term is the derivative of the total (not just electronic) energy with respect to a change in atom $A$'s $x$-coordinate. Even Newton-Raphson-type updates with approximate Hessians (2nd derivative of the energy with respect to nuclear coordinates, rather than the 1st) need the gradient, so we must formulate it. Formulation of the energy We're in a bit of trouble, because we want to replace $E_{\text{total}}$ in the gradient with $E_{\text{total}}^{\text{CP}}$, but all we have is $\Delta E_{\text{bind}}^{\text{CP}}$. The concept of CP correction can still be applied to a total energy, but the BSSE must be removed from each monomer. The BSSE correction itself for each monomer is $$ \begin{split} E_{\text{BSSE}}(\ce{X}) &= E^{\ce{XY}}(\ce{X}) - E^{\ce{X}}(\ce{X}), \\ E_{\text{BSSE}}(\ce{Y}) &= E^{\ce{XY}}(\ce{Y}) - E^{\ce{Y}}(\ce{Y}), \end{split} \label{eq:2} $$ which, when subtracted from $\eqref{eq:sherrill-1}$, gives $\eqref{eq:sherrill-3}$. More correctly, considering that the geometry for each step is at the final cluster geometry and not the isolated geometry, the above is [4] $$ \begin{split} E_{\text{BSSE}}(\ce{X}) &= E_{\ce{XY}}^{\ce{XY}}(\ce{X}) - E_{\ce{XY}}^{\ce{X}}(\ce{X}), \\ E_{\text{BSSE}}(\ce{Y}) &= E_{\ce{XY}}^{\ce{XY}}(\ce{Y}) - E_{\ce{XY}}^{\ce{Y}}(\ce{Y}). \end{split} \label{eq:sherrill-10} \tag{Sherrill 10} $$ The CP-corrected total energy is the full dimer energy with BSSE removed from each monomer is then $$ \begin{split} E_{\text{tot}, \ce{\widetilde{XY}}}^{\text{CP}} &= E_{\ce{\widetilde{XY}}}^{\ce{XY}}(\ce{XY}) - E_{\text{BSSE}}(\ce{X}) - E_{\text{BSSE}}(\ce{Y}), \\ &= E_{\ce{\widetilde{XY}}}^{\ce{XY}}(\ce{XY}) - \left[ E_{\ce{\widetilde{XY}}}^{\ce{XY}}(\ce{X}) - E_{\ce{\widetilde{XY}}}^{\ce{X}}(\ce{X}) \right] - \left[ E_{\ce{\widetilde{XY}}}^{\ce{XY}}(\ce{Y}) - E_{\ce{\widetilde{XY}}}^{\ce{Y}}(\ce{Y}) \right]. \end{split} \label{eq:sherrill-15} \tag{Sherrill 15} $$ Note that I have modified which geometry is used for each monomer in $\eqref{eq:sherrill-15}$. All monomers are calculated at the supermolecule geometry. This is convenient for two reasons: 1. We are only interested in removing the BSSE, not the effect of monomer deformation, and 2. a isolated monomer geometry without deformation doesn't make sense in the context of a geometry optimization. I also added the tilde to signify that the supermolecular/dimer geometry used may not be the final or minimum-energy geometry, as would be the case during a geometry optimization. We simply extract all structures consistently from a given geometry iteration. Perhaps $\ce{XY}(n)$ would be better notation. Formulation of the gradient As Pedro correctly states, the differentiation operator is a linear operator. Because there are no products in $\eqref{eq:sherrill-15}$, the total gradient needed for $\eqref{eq:steepest-descent}$ will be a sum of gradients [5]: $$ \frac{\partial E_{\text{tot}, \ce{\widetilde{XY}}}^{\text{CP}}}{\partial R_{A,x}} = \frac{\partial E_{\ce{\widetilde{XY}}}^{\ce{XY}}(\ce{XY})}{\partial R_{A,x}} - \left[ \frac{\partial E_{\ce{\widetilde{XY}}}^{\ce{XY}}(\ce{X})}{\partial R_{A,x}} - \frac{\partial E_{\ce{\widetilde{XY}}}^{\ce{X}}(\ce{X})}{\partial R_{A,x}} \right] - \left[ \frac{\partial E_{\ce{\widetilde{XY}}}^{\ce{XY}}(\ce{Y})}{\partial R_{A,x}} - \frac{\partial E_{\ce{\widetilde{XY}}}^{\ce{Y}}(\ce{Y})}{\partial R_{A,x}} \right], $$ so each step of a CP-corrected geometry optimization will require 5 gradient calculations rather than 1. Note that the nuclear gradient should be included for each term as well, which is a trivial calculation. Extension to other molecular properties Although not commonly done, counterpoise correction can be applied to any molecular property, not just energies or gradients. Simply replace $E$ or $\partial E/\partial R$ with the property of interest. For example, the CP-corrected polarizability $\alpha$ of two fragments is $$ \alpha_{\text{tot}, \ce{\widetilde{XY}}}^{\text{CP}} = \alpha_{\ce{\widetilde{XY}}}^{\ce{XY}}(\ce{XY}) - \left[ \alpha_{\ce{\widetilde{XY}}}^{\ce{XY}}(\ce{X}) - \alpha_{\ce{\widetilde{XY}}}^{\ce{X}}(\ce{X}) \right] - \left[ \alpha_{\ce{\widetilde{XY}}}^{\ce{XY}}(\ce{Y}) - \alpha_{\ce{\widetilde{XY}}}^{\ce{Y}}(\ce{Y}) \right] $$ where I believe it now makes even less sense to have each individual fragment calculation not be at the cluster geometry. In papers that calculate CP-corrected properties, no mention is usually made of which geometry the individual calculations are performed at for this reason. References Boys, S. Francis; Bernardi, F. The calculation of small molecular interactions by the differences of separate total energies. Some procedures with reduced errors. Mol. Phys. 1970, 19, 553-566. Sherrill, C. David. Counterpoise Correction and Basis Set Superposition Error. 2010, 1-6. One implementation note: Most common quantum chemistry packages should allow for the usage of ghost atoms in energy and gradient calculations. However, as Sherrill states, they do not properly allow for composing the full gradient expression to perform CP-corrected geometry optimizations. Gaussian can, and Psi4 may. For programs that can calculate gradients with ghost atoms, Cuby can be used to drive the calculation of CP-corrected geometries and frequencies. There is a typo in the Sherrill paper; the subscripts for all 4 energy terms should be $AB$, which here are $\ce{XY}$. Simon, S.; Bertran, J.; Sodupe, M. Effect of Counterpoise Correction on the Geometries and Vibrational Frequencies of Hydrogen Bonded Systems. J. Chem. Phys. A 2001, 105,, 4359-4364. A: The CP-correction can be seen as a sum of a correction term to the total energy of the complex. That correction term is essentialy the diference between the energies of the fragments with their basis set and with the whole basis set at the complex's geometry. The total CP-corrected energy is thus a sum of different complex and monomer's energies. Then, as the derivative is a linear operator, any derivative of the total CP-corrected energy is a sum of derivatives of the individual energies.. as simple as that... You can obtain CP-corrected 1st derivatives wrt nuclear coordinates and get optimized structures, but also CP-corrected armonic (and anarmonic) frequencies from 2nd (and 3rd) derivatives, dipole moments, etc...
{ "pile_set_name": "StackExchange" }
Q: How can we keep old threads from coming back This site has a necro-thread problem. Old questions get commented on (often in a questionalble manner). Perhaps SE in general needs a way to graphically show the age of the thread to give you a warning? I often mistakenly comment on or answer obviously dead threads before I think to check the question date. EDIT: To clarify - How can we prevent OLD threads from being mistaken for NEW threads. Old threads often have an acceptable answer, but are not marked as answered. Or, even if un-answered, the discussion has died out. Therefore, any comment or answer is probably wasted effort, because the original poster has long since lost interest. This is the real problem. When an old thread is mistaken for new, one answers it in all seriousness - perhaps spending a non-trivial amount of effort, but the asker never sees the answer. A: The fact that an old question can reappear and get new answers is by design. Things change, what was the best answer a year or two ago might not be any more. Admittedly this is less likely in the world of DIY, but it can still happen - especially if electrical codes change. I too get thrown sometimes by old questions reappearing - they might have been edited for example - you just have to be careful.
{ "pile_set_name": "StackExchange" }
Q: Show that if a metric space is complete, separable and not countable then it has cardinal $\aleph_1$ Show that if a metric space is complete, separable and not countable then it has cardinal $\aleph_1$ I have encountered this exercise and I don't know where to start. There is a lot of important information and I can't imagine how to use it. Any hint? A: Although the answer @Shalop contributed with is surely correct, this course is about metric spaces, not topological spaces. And that's why when dealing with the concepts of given a topology, etc, I can't follow. However, I came up with a proof, that in a similar manner, I don't see why $X$ has to be complete. Since $X$ is separable, it contains a countable dense subset $\mathcal{D} \subset X$. We have that $\overline{\mathcal{D}}=\mathcal{D} \cup \{\text{the set of limit points of } \mathcal{D}\}=X$. (Here $\overline{\mathcal{D}}$ stands for the closure of $\mathcal{D}$). Now, since $\mathcal{D}$ is countable, then the "number" of sequences in $\mathcal{D}$ is $\aleph_{0}^{\aleph_{0}}=\aleph_{1}$ Therefore, $\# \{\text{the set of limit points of } \mathcal{D}\} \leq \aleph_{1}$. However $\# \{\text{the set of limit points of } \mathcal{D}\} > \aleph_{0}$. Because if not $\# (\overline{\mathcal{D}})=\#(\mathcal{D} \cup \{\text{the set of limit points of } \mathcal{D}\})= \# (X) = \aleph_0$ Which contradicts the fact that $X$ is not countable. Therefore $\# (\overline{\mathcal{D}})= \# (X) = \aleph_{1}$
{ "pile_set_name": "StackExchange" }
Q: How to use "contains" in antMatchers? I'm using spring security in a ZUUL application, my API controls all access to my microservices. Using a filter can allow specif routes per login, in the filter inside i have the object HttpSecurity who makes the control through the method ".antMatchers". For example: protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable(); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.authorizeRequests() .antMatchers("/**/swagger-ui.html").permitAll() .antMatchers("/**/webjars/**").permitAll() .antMatchers("/**/swagger-resources/**").permitAll() .antMatchers("/**/csrf/**").permitAll() .antMatchers("/**/v2/**").permitAll() .antMatchers("/**/signin/**").permitAll() .antMatchers("/**/microservice/chatws/**").permitAll() .antMatchers("/**/microservice/*swagger*").permitAll() .antMatchers("/**/microservice/swagger-resources/**").permitAll() .antMatchers("/**/microservice/v2/**").permitAll() .antMatchers("/**/microservice/webjars/**").permitAll() .antMatchers("/**/microservice/csrf/**").permitAll() .anyRequest() .authenticated(); http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider)); } I want to allow all routes who has "swagger" in any locale, in the begging, middle or end. I was thinking in something like method contains of String class, if contains "swagger" so permitAll. A: Yes can always implement your own matching logic by implementing RequestMatcher. The following example shows matching the request URI (without query parameter) containing the word "swagger" : http.authorizeRequests() .requestMatchers(req-> req.getRequestURI().contains("swagger")).permitAll()
{ "pile_set_name": "StackExchange" }
Q: Составление регулярного выражения python Нужно создать регулярное выражение типа - слово [Сс]тена, потом идет либо число, либо несколько слов. Пытался сделать что-то типа pattern = r'\s*[Сс]тена\s[((\w{1,50}){1,10})(-?\d+)]' Но не работает. Мне нужно понять один момент: В квадратные скобки передаются операторы и при поиске регулярного выражения выбирается один из элементов в квадратных скобках. А можно ли передать в квадратные скобки два шаблона, чтобы выбирался целый кусок, а не один символ. Мне нужно что-то вроде этого pattern = r'[pattern1, pattern2]' То есть мне нужно, чтобы выбиралась одна из групп операторов. Я пытался сделать это с помощью круглых скобок, но это не сработало. Тогда мне хотелось бы также узнать, как правильно использовать круглые скобки и для чего они нужны Поподробнее объясню, какой шаблон мне нужен: 1) Слово стена с заглавной или маленькой буквы и пробел(1+) (r'[Сс]тена\s+') 2) Далее выбирается один из двух шаблонов: 2.1) Либо несколько слов, разделённых пробелами 2.2) Либо какое-либо число, у которого в начале может стоять минус(r'-?\d+') Допустим поиск по строке "[anything-|=] Стена имя фамилия [anything=)=-(]" Должен дать строку "Стена имя фамилия" A: strings = [ "[anything-|=] Стена имя фамилия [anything=)=-(]", "[anything-|=] Стена -12 [anything=)=-(]", "[anything-|=] Стена 112 [anything=)=-(]" ] pat = re.compile(r'(стена\s+(?:[-+]?\d+|[\w\s]+))', flags=re.I) for s in strings: m = pat.search(s) if m: print(m.group(1)) результат: Стена имя фамилия Стена -12 Стена 112
{ "pile_set_name": "StackExchange" }
Q: Unable to focus on Input Field in Bootstrap Carousel I am unable to focus on any input field inside bootstrap carousel. No matter how many times you click on it, the input field is not getting focused. I even tried giving z-index to the input field but it still doesn't get focused. You can check the error by running the snippet below. $(document).ready(function(){ $(".carousel").swipe({ swipe: function(event, direction, distance, duration, fingerCount, fingerData) { if (direction == 'left') $(this).carousel('next'); if (direction == 'right') $(this).carousel('prev'); }, allowPageScroll:"vertical" }); }); .carousel-indicators { position: absolute !important; bottom: -100px !important; } .carousel-indicators li { background-color: green; border: 1px solid green !important; } .carousel-inner>.item>div { padding: 30px; } .carousel-inner>.item>div>div { text-align: center; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <div class="container" id="skill-builder"> <div class="row"> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel" data-interval="false"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic" data-slide-to="1"></li> <li data-target="#carousel-example-generic" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <div> <p>In the diagram shown, assume the pulley is smooth and fixed and the ropes are massless. The mass of each block is marked on the block in the diagram. Assume . Find the magnitute of the acceleration of block M.</p> <div> <img src="./assets/questions/1-question.jpg" alt=""> </div> <div> <input type="text" placeholder="Enter Answer" name="answer"> </div> <div> <button>Confirm</button> </div> </div> </div> <div class="item"> <div> <p>In the diagram shown, assume the pulley is smooth and fixed and the ropes are massless. The mass of each block is marked on the block in the diagram. Assume . Find the magnitute of the acceleration of block M.</p> <div><img src="./assets/questions/2-question.png" alt=""></div> <div> <input type="text" placeholder="Enter Answer" name="answer2"> </div> <div> <button>Confirm</button> </div> </div> </div> <div class="item"> <div> <p>In the diagram shown, assume the pulley is smooth and fixed and the ropes are massless. The mass of each block is marked on the block in the diagram. Assume . Find the magnitute of the acceleration of block M.</p> <div><img src="./assets/questions/1-question.jpg" alt=""></div> </div> </div> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.touchswipe/1.6.18/jquery.touchSwipe.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> A: Change touchSwipe version from 1.6.18 to 1.6.4
{ "pile_set_name": "StackExchange" }
Q: Jquery Remove Attributes from element (in loop) only work the first time I have a function that create and removes all data-attributes from 18 images elements (#scelta1, #scelta2, etc) it will run every time the user click one of these images: $(document).ready(function () { $('#scelta6']").on("click", function() { // For simplicity #scelta6, // the real function gets the id based on the element you click $('#scelta6'+).attr({'data-a': foo, 'data-b': bar, [a lot of data-] }); // All the variables is taken from the dropdowns choices of the user in a // separate function [do something] var conta = 1; var fiamma; while (conta < 19) { fiamma = $('#scelta'+conta); $.each($(fiamma).data(), function(i){ $(fiamma).removeAttr("data-" + i); }); console.log(conta); // Just to know if the function is running conta++; } } Now the problem: on a fresh new loaded page if I click on one these elements the function above will run without any problem and removes all the data-attributes from all elements. When I will click again on one of these elements all the all the data-attributes remain in their place! Why this function works only for the first time? I missed something? EDIT The data will be removed in every element if the first time the function run and have in ALL the elements the data set. For example: I will set data to #scelta1, #scelta2, #scelta3, the run the function, it will remove the data from all. Then I set again it in #scelta2, click and all the data will be removed. Then I set again data in #scelta1, #scelta2, #scelta3, click and all the data will be removed from them all. But if I set data to #scelta2 and #scelta4 it will remove ONLY the data in #scelta2... A: EDIT: it seems that using attr to set data attributes was causing the bug (i verified and the behaviour was like you described). With setting the attributes with data() it seems to work all right. $(document).ready(function () { //setting data with attr seems to be the cause of the bug here, use data() instead $('.sceltaButt').on("click", function() { //$('#' + $(this).attr('id')).attr({'data-a': 'foo', 'data-b': 'bar'}); $('#' + $(this).attr('id')).data('a', 'foo').data('b', 'bar'); showData(); }); //then you don't need to remove them manually anymore, removeData is enough $('#removeData').on("click", function() { var conta = 1; var fiamma; while (conta < 7) { fiamma = $('#scelta'+conta); $(fiamma).removeData(); //console.log(conta); conta++; } showData(); }); //now this version doesn't work anymore because we use data() $('#removeWithoutData').on("click", function() { var conta = 1; var fiamma; while (conta < 7) { fiamma = $('#scelta'+conta); $.each($(fiamma).data(), function(i){ $(fiamma).removeAttr("data-" + i); }); //console.log(conta); conta++; } showData(); }); function showData(){ var result = '<br>'; $('.sceltaButt').each(function(){ /*$.each($(this)[0].attributes, function(){ result += ' ' + this.name + ':' + this.value; });*/ $.each($(this).data(), function(name){ result += ' ' + name + ':' + this; }); result += '<br>'; }); $('#result').html(result); } showData(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="sceltaButt" id="scelta1">ADD TO 1</button> <button class="sceltaButt" id="scelta2" data-c="test">ADD TO 2</button> <button class="sceltaButt" id="scelta3">ADD TO 3</button> <button class="sceltaButt" id="scelta4" data-d="test2">ADD TO 4</button> <button class="sceltaButt" id="scelta5">ADD TO 5</button> <button class="sceltaButt" id="scelta6">ADD TO 6</button> <button id="removeData">CLICK ME TO REMOVE (with removeData)</button> <button id="removeWithoutData">CLICK ME TO REMOVE (without removeData)</button> <div>CURRENT DATA: <span id="result"></span></div>
{ "pile_set_name": "StackExchange" }
Q: Connecting to database dynamically with table adapters I have an application which creates table adapters using a dataset at design time. This is tied to a specific database. My requirement is, I want to be able to connect to a different database which has the same schema as the previous one. I should be able to achieve this at runtime. Is there anyway I could do it ? Or what is the best alternate way using TableAdapters ? Cheers, Harish A: Yes, you can change the database your adapters point to by simply closing the existing connection, changing the connection string, then opening the new connection. //Work with existing connection... tableAdapter1.Connection.Close(); tableAdapter1.Connection.ConnectionString = "Your new DB connection string"; tableAdapter1.Connection.Open(); //Work with same adapter but now pointing to new DB specified in above string.
{ "pile_set_name": "StackExchange" }
Q: When (not) to use diode/wired logic I'm interfacing to a microprocessor system, and purposefully not using programmable logic. Feel free to call me a masochist. There's a lot of address decoding etc. happening and I may be able to cut costs and save board space if I use some diode logic. I'd probably also be saving in propagation delay — some of the gates are three levels of cascaded 74HC32s or 74HC08s involving 8 to 16 inputs. The functions I'm considering replacing sit between HC (possibly some AC) family ICs, all running at 5V. They always sit between an HC IC and another HC IC (usually a '138), so signal restoration shouldn't be an issue. If necessary, I can change those to HCT to give more leeway. They're going to be running at clock periods of 500ns to 250ns at most (that's 2–4 MHz). Can I use wired gates with relative impunity? Do you have a suggestion on the type of diode to use (ideally available as through-hole and surface-mount), or shall I go with my all-time favourite, the 1N4148? A: The main problem with diode logic is slow rise time due to the (relatively) weak pull-up in combination with the ever-present stray capacity in your circuit (assuning a wired AND circuit). The use of a buffer transistor might get you into slow switching due to saturation. I don't think you will get into (addiotional) trouble from the less-than-perfect switching characteristics of your diode. If you want to cut PCB size consider using some of the very small one-gate-per-package chips. OTOH, if you realy are a masochist, go for all the trouble you can find! But that does not match with asking here... So impunity: NO. Check your timing margins, if you have a few us to spare I guess brew-it-yourself logic might work. Below 100ns I would not try it.
{ "pile_set_name": "StackExchange" }
Q: Swift 2 - Function not return Bool when using Alamofire I am creating a static function that checks if the user email for registration is in use. If the email is in use the function should return true otherwise false. The code I have is returning always false and seems that the variable I use is not updated. Any Idea what am I doing wrong and why is this not working as expected? class userInfo: NSObject { static func userRegistration(email: String) -> Bool { var emailIsavailable = false Alamofire.request(.GET, "https://example/check_email.php?email=\(email)") .responseString{ response in if let responseValue = response.result.value { print("Response String: \(responseValue)") if responseValue == "email is available"{ print("email available") emailIsavailable = true //emailIsavailable is not updated }else{ print("email not available") emailIsavailable = false //emailIsavailable is not updated } } } return emailIsavailable // returns always false } } A: Because it run in different thread so you can't return straight. You should use callback (or another call block, closure). You should edit code: class userInfo: NSObject { static func userRegistration(email: String, callBack : (emailIsavailable : Bool) -> Void) { Alamofire.request(.GET, "https://example/check_email.php?email=\(email)") .responseString{ response in if let responseValue = response.result.value { print("Response String: \(responseValue)") if responseValue == "email is available"{ print("email available") callBack(emailIsavailable: true) }else{ print("email not available") callBack(emailIsavailable: false) } } } } } And you can call like: yourInstance.userRegistration("test") { (emailIsavailable) -> Void in //you can get emailIsavaiable or something here }
{ "pile_set_name": "StackExchange" }
Q: Generating Doyle spiral painting I recently came across an interesting paining by Nicola Sutcliffe: This painting is actually related to Doyle spirals. From author's website: The central part of the picture shows the Doyle spiral cicle packing P = 2 Q = 12. Three spirals pass through each circle, dividing it into six segments, each of which is a different colour, organised so that no touching segments have the same colour. There are Wolfram demos devoted to Doyle spirals: $\qquad$http://demonstrations.wolfram.com/DoyleSpirals/ $\qquad$http://demonstrations.wolfram.com/DoyleSpiralsAndMoebiusTransformations/ Can Mathematica somehow generate the above painting (just the central part with circles)? Furthermore, can the code be written to generate a parametrized version of the painting so that one could produce and enjoy an unlimited number of pieces of art? The solution does not even have to be an exact copy of the painting, but it should preserve its spirit. The Wolfram demo contains the interesting code with many options that may serve as a good starting point. Related Wolfram demonstrations: Link to the painting: $\qquad$http://wokinghamartsociety.org.uk/6_Gallery/Sutcliffe/doylespiral.htm By the way, the paining was part of the art exhibition at the Bridges (maths and arts) 2008 conference in Leeuwarden. Interesting math notes related to Doyle spirals: $\qquad$http://www.math.u-szeged.hu/~hajnal/courses/PhD_Specialis/Schramm.pdf A: TL;DR Yes, this can be done! If you read the article "Hexagonal circle packings and Doyle spirals" by Leys, you will see that for a choice p and q, we need to find the complex values A, B and r. For that purpose, we can steal this part from the demonstration you linked: doyle[pi_, qi_] := Module[{p = pi, q = qi, s, t, r}, r[s_, t_, p_, q_] := (s^2 + s^(2 p/q) - 2 s^((p + q)/q) Cos[(2 \[Pi] + p t - q t)/q])/(s + s^(p/q))^2; {s, t} = {s, t} /. FindRoot[ {r[s, t, 0, 1] - r[s, t, p, q] == 0, r[s, t, 0, 1] - r[s^(p/q), (p*t + 2. Pi)/q, 0, 1] == 0}, {{s, 1.5}, {t, 0}}]; {s*Exp[I*t], s^(p/q)*Exp[I (p*t + 2*Pi)/q], Sqrt[r[s, t, 0, 1]]} ] {a, b, r} = doyle[2, 12] Now we have the centers for both additional complex circles. Knowing a bit of complex analysis, one understands that for creating all packed circles, we only need to iteratively multiply by e.g. a. So we could write down a function that does this multiplication. I'm keeping complex values until the final visualization, where we use the real part for x and the imaginary part for y: iterate[a_, b_, j_, n_] := Module[{start = b^j}, Table[a^i*start, {i, Range[-n, n]}] ] Graphics[Circle[ReIm[#], r*Abs[#]] & /@ iterate[a, b, 0, 3]] This shows the $0th$ spiral of packed circles, $3$ circles inward to our base circle and $3$ circles outward. To create the complete plane, we have to create $12$ columns, since q was $12$: toCirle[z_, r_] := Disk[{Re[z], Im[z]}, Abs[z]*r]; pack = Table[iterate[a, b, j, 5], {j, 12}]; gr = Graphics[{EdgeForm[Black], Map[{RandomColor[], toCirle[#, r] & /@ #} &, pack]}, PlotRange -> {{-10, 10}, {-10, 10}}] Unfortunately, that is not enough, because the artist chose to use the logarithmic spirals through the circle centers as guide to divide each circle into different parts. In order to do this, we need to go further. Let us make a cut here and divide the following into small sections where we look at the details. These details will be important for the overall approach Connection between a, b, r and the circles As pointed out in the article, the complex numbers a and b are the generators of the circles. This means, all circle centers can be obtained by repeated multiplication. The base circle with the center {1,0} is given by $a^0\cdot b^0$ which is 1 (meaning re=1 and im=0). Now each multiplication by a or by b gives the center of the circle that is next to the base circle. So 1*a*a=a^ gives the second circle in the direction of a. a^2*b shifts this last circle in the direct of b. Note, that even a^(-3) is perfectly OK and gives the 3rd circle in the oposite direction. These are the small circles the fill the center. OK, one Manipulate says more than a thousand words. Let us create a dynamic table of all circles in a range for a^i*b^j. Note that, as pointed out in the article, the correct radius for each circle is Abs[a^i*b^j]*r where r is the radius we got from the solution of doyle. Manipulate[ Graphics[{EdgeForm[Black], FaceForm[Gray], Table[ toCirle[a^i*b^j, r], {i, i1, i2}, {j, j1, j2}]}, PlotRange -> {{-10, 10}, {-10, 10}}], {{i1, 0}, -5, 3, 1}, {{i2, 0}, i1, 5, 1}, {{j1, 0}, -5, 3, 1}, {{j2, 0}, j1, 5, 1} ] Circles and spirals We have seen that we can go from one circle to any neighbour by increasing (or decreasing) either i or j by 1. But what if we don't make jump from say a^3 to a^4 but a smooth transition? Well, the function for such a thing is easy because a^0=1 and a^1=a, so we can make a function a^3*a^t and let t run from 0 to 1. Show[ Graphics[{ FaceForm[Gray], toCirle[#, r] & /@ {a^3, a^4}} ], ParametricPlot[ReIm[a^3*a^t], {t, 0, 1}, PlotStyle -> White] ] This looks very much like the spirals that were used to divide the circles in the original art. So it seems if we pick out the center any circle next to our base circle, we can create spiral functions that go through the circles. Note that the approach of shifting a spiral to its neighbouring spiral is similar to shifting circles. Here is an example: Show[ gr, ParametricPlot[Table[ReIm[b^i a^t], {i, 12}], {t, -10, 10}, PlotRange -> {{-10, 10}, {-10, 10}}, PlotStyle -> White], ParametricPlot[Table[ReIm[a^j b^t], {j, 5}], {t, -10, 10}, PlotRange -> {{-10, 10}, {-10, 10}}, PlotStyle -> White] ] Spiral functions inside circles For our later approach, I want to be able to draw the spiral only inside a circle. As we have seen, going from t=0 to t=1 will connect the centers of the circles. This is not what we want. We want values for t that start and end with the circle. Let's make the plot we did earlier again, but use values for t between -1/3 and 1/3 OK, that looks promising. Remember, we know the center of this circle with a^3 and we know its radius with Abs[a^3]*r. What are the bounds where our spiral is exactly on the radius? Let us ask FindRoot: tb = t /. FindRoot[Abs[1 - a^t] - r, {t, #}] & /@ {-1/3, 1/3} (* {-0.565183, 0.433533} *) But wait! I haven't used a^3 at all! Correct. The good thing is that the bounds for the circles apply to each circle of the same spiral. Therefore I'm using the next neighbour of the base circle which is a for FindRoot. Look here: Show[ Graphics[{ FaceForm[Gray], toCirle[#, r] & /@ {a^3, a^4}} ], ParametricPlot[ReIm[a^3*a^t], {t, tb[[1]], tb[[2]]}, PlotStyle -> White] ] What spirals did the artist use? As it turns out she used the spirals of the following direct neighboring circles of the base circle: spoints = {a*b^-1, a, b} (* {1.46301 - 0.54185 I, 1.67036 + 0.343254 I, 0.927594 + 0.578172 I} *) Let's make a small function that calculates their bounds and returns them with a spiral function. The spiral function will directly incorporate the i and j so that we can easily draw it on every circle we like spiral[pt_] := Module[{t1, t2}, {t1, t2} = Block[{t}, t /. FindRoot[Abs[1 - pt^(t)] - r, {t, #}] & /@ {-1/3, 1/3}]; {t1, t2, Function[{i, j, t}, a^i*b^j*pt^t]} ] Now let's plot these 3 spirals inside our base circle {1,0} Show[{ Graphics[Circle[{1, 0}, r]], ParametricPlot[ReIm@#3[0, 0, t], {t, #1, #2}] & @@@ spiral /@ spoints }] Now, we can calculate the points of the spirals inside each circle, we have the radius of each circle and through the spiral's start and end points, we have 6 points on each circle. Creating polygons points for the parts of a circle For each cake-part of a circle, we can now create a polygon by starting in the center creating points along a spiral outwards to the circle boundary going counterclockwise along the circle to the endpoint of the next spiral create points along this next spiral from the outer point to the center However, one tiny point is missing. How do we create points along the circle from when we go from one spiral point to the next. That is not as hard as it sounds. Assume you have two (complex) points that lie on a circle around a center. Then you can subdivide them and create arbitrarily many points between them that all lie on the circle. circle[z1_, z2_, cent_] := Module[{zz1 = z1 - cent, zz2 = z2 - cent, r}, r = Abs[Mean[{zz1, zz2}]]; # + cent & /@ Nest[Riffle[#, Function[zz, With[{m = Mean[zz]}, m/Abs[m]*Abs[zz1]]] /@ Partition[#, 2, 1]] &, {zz1, zz2}, 5] ] Having this, we can create the points for all cake-parts of circle i, j defined by the provided spirals that divide the circle: createCircleParts[spirals_, i_, j_] := Module[{center, outward, inward}, outward = Table[#3[i, j, t], {t, 0, #2, #2/10.}] & @@@ spirals; inward = Table[#3[i, j, t], {t, 0, #1, #1/10.}] & @@@ spirals; center = a^i*b^j; {i, j, Join[#1[[;; -2]], circle[#1[[-1]], #2[[-1]], center], Reverse[#2[[;; -2]]]] & @@@ Partition[Join[outward, inward, {First[outward]}], 2, 1]} ] The function returns {i,j, {part1, part2, ...}} and we will use i and j later for the coloring as it gives us information about the position of the circle. To test this function, let us see what happens with the circle i=1 and j=2: Graphics[{RandomColor[], Polygon[ReIm[#]]} & /@ Last@createCircleParts[spiral /@ spoints, 1, 2] ] Coloring of circles For one circle we have the information i, j which encodes the global position and of course we have n cake-parts. An easy way would be to provide a list of colors and select a color depending on the information we have. I could not really find a pattern in the coloring of the artists image, so lets keep it simple but let us use equivalent colors: cols = {Black, RGBColor[0.078, 0.71, 0.964], Orange, Red, Darker@Green, Purple}; colorCircleParts[{i_, j_, parts_}, col_List] := Table[{col[[Mod[i + j + n, Length[col]] + 1]], Polygon[ReIm@parts[[n]]]}, {n, Length[parts]}] Putting everything together The last thing we need to do is to create a table containing the circles and their parts for a range of i and j values. Then we color the circle parts and display them: all = Table[colorCircleParts[createCircleParts[spiral /@ spoints, i, j], cols], {i, -5, 6}, {j, 0, 12}]; Graphics[all, PlotRange -> {{-20, 20}, {-20, 20}}] Aftermath: Getting something close to the artist's work The webpage of the artist suggests that The central part of the picture shows the Doyle spiral circle packing P = 2 Q = 12. That is not true. The values of P and Q define how many circles you need to close one loop. Additionally, the rotation of the circles in the artist's work is clockwise while in mathematics, we usually prefer to go counter-clockwise. Lucky for us, this is no big deal because to go clockwise we just need to conjugate our complex values a and b. After printing the painting and counting the circles (and paying absolutely no attention to Wjx's comment who already found out that the values are off), I discovered that the painting uses P=3 and Q=8. Let me show you what that means: pqPlot[p_, q_] := Module[{a, b, r, c1, c2}, {a, b, r} = doyle[p, q]; {a, b} = Conjugate /@ {a, b}; c1 = toCirle[#, r] & /@ NestList[a*# &, 1, p - 1]; c2 = toCirle[#, r] & /@ NestList[b*# &, 1, q - 1]; Graphics[{EdgeForm[Black], FaceForm[LightYellow], c2, FaceForm[LightBlue], c1, FaceForm[LightGreen], EdgeForm[Thick], toCirle[1, r], toCirle[a^p, r]}] ] pqPlot[3, 8] If you include the inner base circle in your counting, you have 3 circles in the first and 8 circles in the other direction until you reach the outer end circle. Taking this into account and including some of the colors in the original painting, we can come up with a very close optical copy of what the artist did. I played around with the plot-range to make it fit. {a, b, r} = doyle[3, 8]; {a, b} = Conjugate /@ {a, b}; spoints = {a*b^-1, a, b}; cols = {GrayLevel[0.1], RGBColor[0.078, 0.71, 0.964], RGBColor[0.95, 0.36, 0.09], RGBColor[0.77, 0.17, 0.12], RGBColor[0.07, 0.6, 0.25], RGBColor[.32, .24, .55]}; range = 5.585; Graphics[ Table[colorCircleParts[createCircleParts[spiral /@ spoints, i, j], cols], {i, -5, 2}, {j, 0, 7}], PlotRange -> {{-range, range}, {-range, range}} ] A: (Not an answer but an extended comment.) Simple mush-ups In view of question's main part: Furthermore, can the code be written to generate a parametrized version of the painting so that one could produce and enjoy an unlimited number of pieces of art? using halirutan's great answer we can do some mush-ups. Here is an example. AbsoluteTiming[ doyleSpiralImages = Flatten@ Table[(lcols = RandomSample[cols]; all = Table[colorCircleParts[ createCircleParts[spiral /@ spoints, i, j], lcols], {i, -5, 6}, {j, 0, 12}]; Image[Graphics[all, PlotRange -> {{-20, 20}, {-20, 20}}]]), {20}]; ] doyleSpiralImagesBW = ColorConvert[#, "Grayscale"] & /@ doyleSpiralImages; doyleSpiralImagesBWBin = Flatten@Table[ Binarize[#, b] & /@ doyleSpiralImagesBW, {b, {0.15, 0.45}}]; (* {31.5697, Null} *) AbsoluteTiming[ nc = 16; directBlendingImages = Table[ImageAdjust[ Blend[Colorize[#, ColorFunction -> RandomChoice[{"BrightBands", "FruitPunchColors", "AvocadoColors"}]] & /@ RandomChoice[doyleSpiralImagesBWBin, nc], RandomReal[1, nc]]], {25}]; ] (* {42.7025, Null} *) Multicolumn[ColorNegate /@ directBlendingImages, 6] Mush-ups with larger collections of images Ideally, we can use procedures in the spirit of the one above over a large collection of Doyle spiral images. Such images can be made from scratch or obtained from the Web. For example, if such an image collection is fed to the neural net functions in Mathematica / WL, in principle we will be able to obtain new spiral images by examining the layers.
{ "pile_set_name": "StackExchange" }
Q: my r program for counting missing data in files I have created my program for counting the missing data in a file with more than 10,000 rows (I have 1700 files like this). At the end the warning message says: :"Error in if ((b[i, 5] == NA) && (b[i, 1] > 1980)) { : missing value where TRUE/FALSE needed" The code is written below: rm(list=ls()) setwd("C:\\Users\\.......") a <- list.files(); n=0; j=1; mat <- matrix(data=NA,nrow=20000,ncol=8); colnames(mat)<-c("Station","S.Year","S.Month","S.Day","E.Year","E.Month","E.Day","Count"); d<-matrix(data=NA,nrow=3,ncol=1); for( k in 1:length(a) ) { b <- as.matrix(read.table(a[k],skip=7,header=F)); t<-gsub(".txt","",a[k]) for(i in 1:(length(b[,1])-1)) { if((b[i,5]==NA)&&(b[i,1]>1980)) {n=n+1; if(n==1) {d[1,1]=b[i,1] d[2,1]=b[i,2] d[3,1]=b[i,3]} if((b[i+1,5]!=NA)||(i==(length(b[,1])-1))) { if(n>10) {mat[j,1]=t; mat[j,2]=d[1,1] mat[j,3]=d[2,1] mat[j,4]=d[3,1] mat[j,5]=b[i,1] mat[j,6]=b[i,2] mat[j,7]=b[i,3] mat[j,8]=n; j=j+1;} n=0;} } } j=j+1; } write.csv(mat,"Count.csv", append = TRUE,row.names = FALSE) Any help why that error message? Maybe I am ignoring something? data are from a weather stations, therefore will have the following structure: YY MM DD Srad Tmax Tmin (Rain) 1980 1 1 3 2 -3 and goes on until Dec 31 2011 The expected output should be a csv file with the first Col the file name (each row would be a file), the second Col the Year when the first NA is encountered, the third Col the Month, the forth Col the Day when the the NA are found, the Fifth, sixth and seventh Cols the Ending years, Mm, and Dd when NA is last. The last col is the total number of NA for that time frame Therefore for one file (e.g. File1.txt) there could 3 days of missing data from 1981-1-13 to 1981-2-1 and I will have in the last col the number of NA for this period. For the same file I might have another NA period later on (e.g. in 1997) and therefore on the third row I will have again Filename, period of starting and ending time frame and how many NAs. I hope this is not too confusing... A: Nothing is ever "==" or "!=" to NA. Use is.na() or !is.na() instead. So the logical tests would be: if ( is.na( b[i,5]) && ( b[i,1]>1980 ) ) if( !is.na(b[i+1,5]) || (i==(length(b[,1])-1)))
{ "pile_set_name": "StackExchange" }
Q: Scanner with input and delimiter I would like to create a Scanner with a String, and I was just wondering if there's a constructor / static factory method to do this in one line. So far the only way I found is this: Scanner sc = new Scanner(inputString); sc.useDelimiter(Pattern.compile("\\D")); Is there a simpler way? A: You could do it in a single line: Scanner sc = new Scanner(inputString).useDelimiter(Pattern.compile("\\D")); useDelimiter returns this Scanner so you can use it to chain invocation. If you find yourself doing this often, you can build your own static factory for this, and reuse it.
{ "pile_set_name": "StackExchange" }
Q: Summarise grouping by varname I'm analysing some data, and I've come a difficulty - I don't know how to summarise my whole dataset using the variable names as the "group". A sample data: structure(list(x4 = c(3, 4, 7, 4, 5, 1, 5, 2, 7, 1), x5 = c(2, 4, 4, 4, 5, 3, 6, 1, 7, 1), x6 = c(3, 5, 4, 7, 5, 4, 6, 4, 6, 2), x7 = c(4, 1, 6, 4, 6, 4, 6, 2, 7, 2), x9 = c(5, 5, 4, 5, 6, 3, 7, 5, 6, 1), x10 = c(3, 6, 5, 4, 6, 5, 6, 3, 6, 1), x11 = c(6, 7, 7, 7, 6, 7, 7, 5, 7, 4), x12 = c(6, 7, 6, 7, 6, 4, 6, 6, 7, 5), x14 = c(5, 7, 5, 6, 4, 6, 6, 5, 6, 4), x15 = c(4, 7, 7, 7, 6, 4, 6, 5, 6, 1), x16 = c(4, 7, 7, 7, 6, 5, 7, 3, 6, 4), x17 = c(4, 5, 5, 7, 6, 6, 7, 4, 6, 2), x18 = c(3, 4, 7, 7, 6, 5, 6, 4, 6, 2), x19 = c(5, 7, 5, 7, 6, 6, 6, 3, 6, 1), x22 = c(4, 4, 5, 7, 6, 7, 6, 5, 6, 2), x26 = c(6, 7, 5, 4, 6, 7, 7, 4, 6, 4), x29 = c(4, 7, 2, 7, 6, 4, 7, 3, 6, 1), x33 = c(3, 7, 7, 7, 6, 5, 6, 3, 6, 3), x34 = c(5, 5, 4, 7, 6, 7, 7, 5, 6, 2), x35 = c(4, 4, 7, 7, 5, 7, 6, 4, 6, 2), x36 = c(4, 7, 6, 7, 6, 5, 5, 4, 6, 2), x37 = c(3, 4, 7, 4, 5, 4, 6, 3, 5, 2), x49 = c(4, 7, 7, 7, 6, 5, 5, 6, 6, 3), x50 = c(4, 7, 6, 5, 5, 5, 6, 5, 7, 4)), row.names = c(NA, -10L), class = "data.frame", .Names = c("x4", "x5", "x6", "x7", "x9", "x10", "x11", "x12", "x14", "x15", "x16", "x17", "x18", "x19", "x22", "x26", "x29", "x33", "x34", "x35", "x36", "x37", "x49", "x50")) I just want some statistics, like this: summary <- dados_afc %>% summarise_all(funs(mean, sd, mode, median)) But the result is a df with one observation and lots of variable. I wanted it to have 5 columns: varname, mean, sd, mode, median, but I'm not sure how to do it. Any tips? A: Note: I am not aware of a built-in way to get mode from R. See here for some discussion: Is there a built-in function for finding the mode? # From the top answer there: Mode <- function(x) { ux <- unique(x) ux[which.max(tabulate(match(x, ux)))] } To treat each column as a group, you can use tidyr::gather to convert your "wide" data into long form, and then dplyr::group_by to create groups with their own summary calculations: library(tidyverse) summary <- dados_afc %>% gather(group, value) %>% group_by(group) %>% summarise_all(funs(mean, sd, Mode, median)) > summary # A tibble: 24 x 5 group mean sd Mode median <chr> <dbl> <dbl> <dbl> <dbl> 1 x10 4.5 1.72 6 5 2 x11 6.3 1.06 7 7 3 x12 6 0.943 6 6 4 x14 5.4 0.966 6 5.5 5 x15 5.3 1.89 7 6 6 x16 5.6 1.51 7 6 7 x17 5.2 1.55 6 5.5 8 x18 5 1.70 6 5.5 9 x19 5.2 1.87 6 6 10 x22 5.2 1.55 6 5.5
{ "pile_set_name": "StackExchange" }
Q: How to read ISBN from eBooks on CHM or PDF files I'm doing a database for storing my eBook collection. Most of them have the ISBN within the text of the book itself. How can I access this contents? Is there any sourcecode or DLLs for doing that? A: I did it for eBook library app. First of all you need to extract text from chm or pdf file. There are a lot of utilities\libraries to do it. Here is an article on CodeProject on how to extract content from CHM files. For PDF files I used pdftotext utility. When you get plain text from eBook parse it using regular expression to find ISBN10/13 code.
{ "pile_set_name": "StackExchange" }
Q: How to hijack key combos in javascript? In Gmail, for example, when one presses Ctrl + B, instead of it getting passed to the browser (which would normally bring up some sort of bookmark manager), it hijacks it for formatting purposes, i.e. turn on bold formatting for the message ur in the middle of comoposing. Same for Ctrl+i, Ctrl+u. How is this done? A: You would attach an onkeydown or onkeyup event handler to the global document object. For example, if I wanted to make the title bar change to "asdf" each time Ctrl-M was pressed, I would register the event handler through window.onload, like this: window.onload = function() { document.onkeydown = function(event) { var keyCode; if (window.event) // IE/Safari/Chrome/Firefox(?) { keyCode = event.keyCode; } else if (event.which) // Netscape/Firefox/Opera { keyCode = event.which; } var keyChar = String.fromCharCode(keyCode).toLowerCase(); if (keyChar == "m" && event.ctrlKey) { document.title = "asdf"; return false; // To prevent normal minimizing command } }; }; W3Schools has more information on using these events: onkeydown and onkeyup. Also, I think I should note that there are some discrepancies across browsers in regards to the event properties (like, for example, in Firefox, you're supposed to access the keycode through event.which, while in IE it's event.keyCode, although Firefox may support event.keycode—confusing, isn't it?). Due to that, I'd recommend doing this stuff through a JavaScript framework, such as Prototype or jQuery, as they take care of all the icky compatibility stuff for you. A: Here is the source for an HTML page that uses jQuery and does what htw's solution does. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Hijack Example</title> <script type="text/javascript" src="../scripts/jquery-1.2.1.js"> </script> <script type="text/javascript"> $(function(){ document.title = "before keypress detected"; $(document).keydown(function(event) { // alert('stuff happened: ' + msg + " " + event.keyCode); var keyChar = String.fromCharCode(event.keyCode).toLowerCase(); if (keyChar == "m" && event.ctrlKey) { document.title = "ctrl-m pressed!"; } }); }); </script> </head> <body id="body"> <p>Change the path to jquery above as needed (search for ../scripts/jquery-1.2.1.js)</p> <p>Watch the title bar, then press control-M, then watch the title bar again!</p> </body> </html> Hope this helps somebody!
{ "pile_set_name": "StackExchange" }
Q: Can FileOutputStream() take a relative path as an argument I am creating a FileOutputStream object. It takes a file or String as an argument in its constructor. My question is, can I give it a relative URL as an argument for the location of a file, it doesn't seem to work, but I am trying to work out if this is possible at all (if not I will stop trying). If it is not possible, how can I (from a servlet) get the absolute path (on the filesystem, not the logical URL) to the current location in such a way that I can pass that to the constructor. Part of my problem is that my dev box is Windows but I will publish this to a Unix box, so the paths cannot be the same i.e. on Windows C:/.... and on unix /usr/... A: ServletContext.getRealPath(relativePath)
{ "pile_set_name": "StackExchange" }
Q: How to convert utf-8 encoded string to Turkish characters in Xcode? I have a webservis in php and I encoded the string in utf-8 like this : $str_output = mb_convert_encoding("MATEMATİK", "UTF-8"); $data_array = array('name' => $str_output); echo json_encode($data_array); I get this string from webservis in xcode : MATEMAT\u00ddK I couldn't convert this string to Turkish string. My json_dictionary is like this 2014-01-08 16:17:22.274 test_app[6432:70b] { name = "MATEMAT\U00ddK"; } I tried this encoding method, but it didn't work for me NSString * name = [json_dictionary objectForKey:@"name"]; NSString * correctString = [NSString stringWithCString:[baslik cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSWindowsCP1254StringEncoding]; I got null If I use NSUTF8StringEncoding MATEMATÝK Also I tried NSISOLatin1StringEncoding, NSISOLatin2StringEncoding ... Thanks... A: iOS is correctly decoding the \u00dd when you use NSUTF8StringEncoding (which is what you should be using). That's LATIN CAPITAL LETTER Y WITH ACUTE. The letter you want is LATIN CAPITAL LETTER I WITH DOT ABOVE, which is \u0130. That suggests the problem is on your php side. If I had to guess, I'd suspect that the İ in your source file is not itself in the encoding that php expects. You may need to pass to "from" encoding to mb_convert_encoding depending on what encoding your editor is using. I would strongly recommend that you stay in UTF-8 entirely if possible, and avoid creating a CP1254 (Turkish) string at all. UTF-8 is capable of encoding all the characters you need. In that case, you may be able to avoid the mb_convert_encoding entirely.
{ "pile_set_name": "StackExchange" }
Q: The procedure of delete node in the queue class This code is copied from the c++ primer plus. I think some steps in the dequeue function is unnecessary. But the book say it is important.I don't understand. I hope some one can show me more detail explanation.Here is the definition of the queue. typedef unsigned long Item; class Queue { private: struct Node{ Item item; struct Node * next; }; enum{ Q_SIZE = 10 }; Node * front; Node * rear; int items; // the number of item in the queue const int qsize; Queue(const Queue & q) :qsize(0){}; Queue & operator=(const Queue & q){ return *this; } Queue & operator=(const Queue & q){ return *this; } public: Queue(int qs = Q_SIZE); ~Queue(); bool isempty()const; bool isfull()const; int queuecount()const; bool enqueue(const Item & item); bool dequeue(Item & item); }; bool Queue::dequeue(Item & item) { if (isempty()) return false; item = front->item; Node * temp; temp=front; // is it necessary front = front->next; items--; delete temp; if (items == 0) rear = NULL; //why it is not front=rear=Null ; return true; } A: The nodes in this queue are stored as pointers. To actually create a node some code like Node* tmp = new Node() is probably somewhere in the enqueue-Function. With front = front->next; the pointer to the first element gets moved to the next element in the queue. But what about the previous front-node? By moving the pointer we "forget" its adress, but we don't delete the object or free the memory. We have to use delete to do so, which is why the adress is temporarily stored to call the delete. Not deleting it would cause a memory leak here. About your second question: The frontpointer has already been moved to front->next. What could that be if there was only one element inside the queue? Probably NULL, which should be ensured by the enqueue-function. ("Note: If you are managing this code, it is a good idea to replace NULL with nullptr). The only variable that didn't get updated yet is rear.
{ "pile_set_name": "StackExchange" }
Q: Função que ao clicar abrir uma respectiva em outra página ao clicar em uma categoria como na imagem abaixo, é redirecionado a outra página, que quando você está utilizando seu computador ela abre dessa maneira: Só que é preciso também utilizar em celulares, porém quando está responsivo é necessário clicar novamente em cima do nome da categoria para que ela abra e mostre as informações. Após clicar novamente: Não posso alterar nada no código fonte pois meu chefe não autorizou fazer isso :( , ele quer apenas uma função que ao escolher sua categoria e ser redirecionado, essa categoria ja esteja aberta para o usuário sem precisar clicar novamente para abrir. Abaixo uma parte do código fonte para ajudar a entender: index.html (Primeira imagem): <div class="main-content"> <div class="w3-categories"> <h3>Browse Categories</h3> <div class="container"> <div class="col-md-3"> <div class="focus-grid w3layouts-boder1"> <a class="btn-8" href="categories.html"> <div class="focus-border"> <div class="focus-layout"> <div class="focus-image"><i class="fa fa-mobile"></i></div> <h4 class="clrchg">Mobiles</h4> </div> </div> </a> </div> </div> <div class="col-md-3"> <div class="focus-grid w3layouts-boder2"> <a class="btn-8" href="categories.html#parentVerticalTab2"> <div class="focus-border"> <div class="focus-layout"> <div class="focus-image"><i class="fa fa-laptop"></i></div> <h4 class="clrchg"> Electronics & Appliances</h4> </div> </div> </a> </div> </div> <div class="col-md-3"> <div class="focus-grid w3layouts-boder3"> <a class="btn-8" href="categories.html#parentVerticalTab3"> <div class="focus-border"> <div class="focus-layout"> <div class="focus-image"><i class="fa fa-car"></i></div> <h4 class="clrchg">Cars</h4> </div> </div> </a> </div> </div> Categories.html (Segunda/terceira imagem): <div class="categories-section main-grid-border"> <div class="container"> <h2 class="w3-head">All Categories</h2> <div class="category-list"> <div id="parentVerticalTab"> <div class="agileits-tab_nav"> <ul class="resp-tabs-list hor_1"> <li>Mobiles</li> <li>Electronics & Appliances</li> <li>Cars</li> <li>Bikes</li> <li>Furniture</li> <li>Pets</li> <li>Books, Sports & Hobbies</li> <li>Fashion</li> <li>Kids</li> <li>Services</li> <li>Jobs</li> <li>Real Estate</li> </ul> <a class="w3ls-ads" href="all-classifieds.html">View all Ads</a> </div> <div class="resp-tabs-container hor_1"> <div> <div class="category"> <div class="category-img"> <img src="images/cat1.png" title="image" alt="" /> </div> <div class="category-info"> <h4>Mobiles</h4> <span>5,12,850 Ads</span> <a href="all-classifieds.html">View all Ads</a> </div> <div class="clearfix"></div> </div> <div class="sub-categories"> <ul> <li><a href="mobiles.html">mobile phones</a></li> <li><a href="mobiles.html">Tablets</a></li> <li><a href="mobiles.html">Accessories</a></li> </ul> </div> </div> <div> <div class="category"> <div class="category-img"> <img src="images/cat2.png" title="image" alt="" /> </div> <div class="category-info"> <h4>Electronics & Appliances</h4> <span>2,01,850 Ads</span> <a href="all-classifieds.html">View all Ads</a> </div> <div class="clearfix"></div> </div> <div class="sub-categories"> <ul> <li><a href="electronics-appliances.html">Computers & accessories</a></li> <li><a href="electronics-appliances.html">Tv - video - audio</a></li> <li><a href="electronics-appliances.html">Cameras & accessories</a></li> <li><a href="electronics-appliances.html">Games & Entertainment</a></li> <li><a href="electronics-appliances.html">Fridge - AC - Washing Machine</a></li> <li><a href="electronics-appliances.html">Kitchen & Other Appliances</a></li> </ul> </div> </div> <div> Desde já agradeço pela ajuda! :) A: Segue o link de referência: https://github.com/samsono/Easy-Responsive-Tabs-to-Accordion/blob/master/Index.html Consegui resolver utilizando esse script, segue abaixo caso alguém precise. Apenas foi necessário comentar clossed: 'accordion' <script type="text/javascript"> $(document).ready(function() { //Vertical Tab $('#parentVerticalTab').easyResponsiveTabs({ type: 'vertical', width: 'auto', fit: true, //closed: 'accordion', tabidentify: 'hor_1', // The tab groups identifier activate: function(event) { // Callback function if tab is switched var $tab = $(this); var $info = $('#nested-tabInfo2'); var $name = $('span', $info); $name.text($tab.text()); $info.show(); } }); }); </script>
{ "pile_set_name": "StackExchange" }
Q: Prove that $e$ exists and has a value of $2.71828$ We've been working on proving different mathematical formulas, statements and constants such as the existence of the $sin$ function. Now we need to prove that $\exp$ exists and has the value of $2.71828...$. Here we use $\exp$ and not $e$, as the solution to the unique problem of $f'(x)=f(x), f(0)=1$. I started of by stating that $$\exp(x)=\sum_{k=0}^n \frac{x^k}{k!} + R_n (x)$$ I got stuck right after that, but I assume first I state that $x∈[a,b]$. Then I need to work out the value of $R_n(x)$ as $$|R_n(x)|=|\exp(ζ)\frac{x^{n+1}}{(n+1)!}|≤\exp(b)\frac{|x|^{n+1}}{(n+1)!}\to \ 0$$ I need help continuing on from there. A: The problem with using Taylor's theorem to bound the error term is that you need to already have an estimate for how large $\exp(x)$ gets between $0$ and $1$. It is easier to estimate the error term directly by bounding the rest of the series by a geometric series: $$ \sum_{k\ge n} \frac{1}{k!} \le \frac{1}{n!} \sum_{h\ge 0}\Bigl(\frac{1}{n+1}\Bigr)^h = \frac{1}{n!} \cdot \frac{1}{1-1/(n+1)} = \frac1{n!} (1+1/n) $$ so just start summing the series, and you can stop as soon as the partial sum is at least $2.71828$ and the last term takes you at most $\frac{n}{n+1}$ of the way to $2.71829$. About 10 terms should be enough, so doing the calculations to 7 decimal places will be sufficient to prevent rounding errors from upsetting the result.
{ "pile_set_name": "StackExchange" }
Q: Help Configuring Synaptics Touchpad edit: I can achieve point 1 now. Still need a solution for point 2, though. I am having a hard time configuring my notebook's touchpad. The touchpad already works. It successfully responds to one-finger tap, two-finger tap and two-finger vertical scrolling. What I want to accomplish: change two-finger tap action from right-mouse click to middle-mouse click add three-finger tap functionality to yield right-mouse click action (i have checked that the three-finger tap is supported by my laptop's touchpad since it works on Windows) I read on a forum to use this as a guide. I have successfully accomplished point 1 with synclient TapButton2=2. However, I have to do it everytime I log in. I have tried to put that command on /etc/rc.local but the computer always boots and logins with the default configuration. Regarding point 2, I have tried synclient TapButton3=3 but it doesn't do anything when I three-finger tap the touchpad. I am running Ubuntu 11.10 on an Asus N82JV. /etc/X11/xorg.conf: nuno@mozart:~$ cat /etc/X11/xorg.conf Section "InputClass" Identifier "touchpad catchall" Driver "synaptics" MatchIsTouchpad "on" MatchDevicePath "/dev/input/event*" Option "TapButton1" "1" Option "TapButton2" "2" Option "TapButton3" "3" EndSection /usr/share/X11/xorg.conf.d/50-synaptics.conf: nuno@mozart:~$ cat /usr/share/X11/xorg.conf.d/50-synaptics.conf # Example xorg.conf.d snippet that assigns the touchpad driver # to all touchpads. See xorg.conf.d(5) for more information on # InputClass. # DO NOT EDIT THIS FILE, your distribution will likely overwrite # it when updating. Copy (and rename) this file into # /etc/X11/xorg.conf.d first. # Additional options may be added in the form of # Option "OptionName" "value" # Section "InputClass" Identifier "touchpad catchall" Driver "synaptics" MatchIsTouchpad "on" MatchDevicePath "/dev/input/event*" Option "TapButton1" "1" Option "TapButton2" "2" Option "TapButton3" "3" EndSection xinput list: nuno@mozart:~$ xinput list ⎡ Virtual core pointer id=2 [master pointer (3)] ⎜ ↳ Virtual core XTEST pointer id=4 [slave pointer (2)] ⎜ ↳ Microsoft Microsoft® Nano Transceiver v2.0 id=12 [slave pointer (2)] ⎜ ↳ Microsoft Microsoft® Nano Transceiver v2.0 id=13 [slave pointer (2)] ⎜ ↳ ETPS/2 Elantech Touchpad id=16 [slave pointer (2)] ⎣ Virtual core keyboard id=3 [master keyboard (2)] ↳ Virtual core XTEST keyboard id=5 [slave keyboard (3)] ↳ Power Button id=6 [slave keyboard (3)] ↳ Video Bus id=7 [slave keyboard (3)] ↳ Video Bus id=8 [slave keyboard (3)] ↳ Sleep Button id=9 [slave keyboard (3)] ↳ USB2.0 2.0M UVC WebCam id=10 [slave keyboard (3)] ↳ Microsoft Microsoft® Nano Transceiver v2.0 id=11 [slave keyboard (3)] ↳ Asus Laptop extra buttons id=14 [slave keyboard (3)] ↳ AT Translated Set 2 keyboard id=15 [slave keyboard (3)] A: This seems to work (for part 1) even when you hibernate or sleep. echo synclient TapButton2=2 TapButton3=3 >> ~/touchpad_settings.sh chmod +x ~/touchpad_settings.sh gsettings set org.gnome.settings-daemon.peripherals.input-devices hotplug-command "/home/YOUR USER NAME/touchpad_settings.sh" Make sure to replace YOUR USER NAME with your actual user name. This was pulled from http://tombuntu.com/index.php/2011/11/06/persistent-touchpad-configuration-in-ubuntu-11-10/
{ "pile_set_name": "StackExchange" }
Q: Format Java/JavaScript using JavaScript? I'm looking for a solution to format some code that's input through a form. Take the following code for example function whatever(){ var test=1; var test2=2;} Dose anyone know of a library that'll take this and turn it into function whatever() { var test = 1; var test2 = 2; } A: You could try a library like js-beautify, if you need to access it in node or otherwise programmatically.
{ "pile_set_name": "StackExchange" }
Q: Highcharts Export-data: Show notes in the data table In Highcharts, I want to show different symbols next to point values to indicate certain notes. I use an additional attribute for the point ("note") and I can then use it in tooltips and dataLabels, as shown here: Highcharts.chart('container', { title: { text: 'Title' }, tooltip: { formatter: function() { return "<strong>" + this.series.name + "</strong><br /><strong>" + Highcharts.numberFormat(this.y, 2) + '' + '<b><sup>' + this.point.note + '</sup></b></strong>'; } }, credits: { text: 'Source: thesolarfoundation.com' }, chart: { borderWidth: 1, borderColor: '#ccc', spacingBottom: 30 }, yAxis: { title: { text: 'Number of Employees' } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle' }, plotOptions: { series: { pointStart: 2010, dataLabels: { useHTML: true, enabled: true, allowOverlap: true, style: { fontWeight: 'normal', fontSize: '9px', zIndex: 5 }, formatter: function() { return Highcharts.numberFormat(this.y, 2) + "<sup>" + this.point.note.toLowerCase() + "</sup>"; } } } }, series: [{ name: 'Series 1', data: [{ id: "myID", note: "", y: 12.22, value: 12.22 }, { id: "myID", note: "", y: 13.11, value: 13.11 }, { id: "myID", note: "*", y: 14.99, value: 14.99 }] }], exporting: { showTable: true } }); https://jsfiddle.net/jmunger/o3bmyu5d/10/ Now I want to use the Export-data module to allow the user to see the data in table form. This works well, as shown in the jsFiddle above, but how could I add the same symbols/notes I show in tooltips and dataLabels in the table? A: You can define the keys (API) for the series, which is used when creating the table. For example, in your case you can set keys as follows (JSFiddle demo): series: [{ name: 'Series 1', keys: ['y', 'note'], data: [...] }]
{ "pile_set_name": "StackExchange" }
Q: geom layer to set two categorical axes with points as count I am completing the exercises in Hadley Wickham's book ggplot2. There is a picture that the book asks to re-create: Here is my code: library(tidyverse) count <- mpg %>% group_by(drv, cyl) %>% summarise(n = n()) count ggplot(mpg, aes(x = cyl, y = drv)) + geom_point(aes(size = n), data = count, position = "jitter") But it doesn't show the same picture. I cannot figure out which geom this plot is. But one thing is that the points in the plot could mean the count of observations that matches cyl and drv. The data is mpg, which is included in tidyverse package. A: You should use geom_jitter instead of geom_point: library(ggplot2) ggplot(mpg, aes(cyl, drv)) + geom_jitter(position = position_jitter(0.05, 0.05)) By default jitter in geom_jitter is too large and we need to specify our own height and width of jitter by using position_jitter function.
{ "pile_set_name": "StackExchange" }
Q: How to convert rows to column in T-SQL, and write it in a temp table? This is a question maybe already asked. My query is SELECT Year, Month, Line, SUM(value) as total FROM myTable I've the following query result table: Year Month Line Total ------------------------------------------- 2011 2 B1 5203510.00 2011 3 B1 2228850.00 2011 4 B1 7258075.00 2011 5 B1 6305370.00 2011 6 B1 5540180.00 2011 7 B1 7624430.00 2011 8 B1 4042300.00 2011 9 B1 3308870.00 2011 10 B1 4983875.00 2011 11 B1 4636500.00 2011 12 B1 3987350.00 2012 1 B1 518400.00 I would like the following: Year Line Jan Feb Mar Apr ..... December 2011 B1 0 52035 2228 725 ..... 3987350 2012 B1 51840 ... ... .... Please, can you help me how to translate query SQL from rows to columns? A: Essentially, you need to PIVOT your data. There are several examples on SO on how to do this. The tricky part is to convert the month number to a month name. This is accomplished in the example with DATENAME(month, DateAdd(month, [Month], 0)-1) SQL Statement SELECT * FROM ( SELECT Year, Line, Total, mnt = DATENAME(month, DateAdd(month, [Month], 0)-1) FROM myTable ) mt PIVOT (MAX(Total) FOR [mnt] IN ([January],[February],[March],[April],[May],[June],[July],[August],[September],[October],[November],[December])) AS PVT Test script ;WITH myTable AS ( SELECT * FROM (VALUES (2011 , 2 , 'B1', 5203510.00) , (2011 , 3 , 'B1', 2228850.00) , (2011 , 4 , 'B1', 7258075.00) , (2011 , 5 , 'B1', 6305370.00) , (2011 , 6 , 'B1', 5540180.00) , (2011 , 7 , 'B1', 7624430.00) , (2011 , 8 , 'B1', 4042300.00) , (2011 , 9 , 'B1', 3308870.00) , (2011 , 10 , 'B1', 4983875.00) , (2011 , 11 , 'B1', 4636500.00) , (2011 , 12 , 'B1', 3987350.00) , (2012 , 1 , 'B1', 518400.00) ) AS myTable (Year, Month, Line, Total) ) SELECT * FROM ( SELECT Year, Line, Total, mnt = DATENAME(month, DateAdd(month, [Month], 0)-1) FROM myTable ) mt PIVOT (MAX(Total) FOR [mnt] IN ([January],[February],[March],[April],[May],[June],[July],[August],[September],[October],[November],[December])) AS PVT
{ "pile_set_name": "StackExchange" }
Q: how to get CREATESTRUCT of a window? I am trying to make a windows GUI application. I declared some static variables in my window procedure function and initialized it in the WM_CREATE whose lParam is a pointer to the CREATESTRUCT. However, since these values are static, I can only make one instance of my window; if I make more the previous instances' data will be changed to the new datas. Is there a way to access the CREATESTRUCT of a window after the WM_CREATE message so that I can solve this problem? A: Save a pointer to a user-defined structure in WM_CREATE using either SetWindowLongPtr or SetProp, and retrieve it with the matching functions. e.g. case WM_CREATE: SetWindowLongPtr(hWnd, GWLP_USERDATA, ((LPCREATESTRUCT)lParam)->lpCreateParams); break; case <other messages>: MyData* pData = (MyData*)GetWindowLongPtr(hWnd, GWLP_USERDATA). Some will argue that you shouldn't use GWLP_USERDATA and instead should reserve storage space in your window class; this is up to you. Using SetProp/GetProp is also a valid alternative.
{ "pile_set_name": "StackExchange" }
Q: lag/lead entire dataframe in R I am having a very hard time leading or lagging an entire dataframe. What I am able to do is shifting individual columns with the following attempts but not the whole thing: require('DataCombine') df_l <- slide(df, Var = var1, slideBy = -1) using colnames(x_ret_mon) as Var does not work, I am told the variable names are not found in the dataframe. This attempt shifts the columns right but not down: df_l<- dplyr::lag(df) This only creates new variables for the lagged variables but then I do not know how to effectively delete the old non lagged values: df_l<-shift(df, n=1L, fill=NA, type=c("lead"), give.names=FALSE) A: Use dplyr::mutate_all to apply lags or leads to all columns. df = data.frame(a = 1:10, b = 21:30) dplyr::mutate_all(df, lag) a b 1 NA NA 2 1 21 3 2 22 4 3 23 5 4 24 6 5 25 7 6 26 8 7 27 9 8 28 10 9 29 A: I don't see the point in lagging all columns in a data.frame. Wouldn't that just correspond to rbinding an NA row to your original data.frame (minus its last row)? df = data.frame(a = 1:10, b = 21:30) rbind(NA, df[-nrow(df), ]); # a b #1 NA NA #2 1 21 #3 2 22 #4 3 23 #5 4 24 #6 5 25 #7 6 26 #8 7 27 #9 8 28 #10 9 29 And similarly for leading all columns.
{ "pile_set_name": "StackExchange" }
Q: Need help about "Get Attachment File Name" Tutorial from Java2s.com i try the tutorial Get Attachment File Name from Java2s.com. What i'm doing is to read email from the Outlook Web Access Light. If i put the url address of the Outlook Web Access Light, i have the error: Exception in thread "main" javax.mail.NoSuchProviderException: No provider for http at javax.mail.Session.getProvider(Session.java:455) at javax.mail.Session.getStore(Session.java:530) at javax.mail.Session.getFolder(Session.java:602) at MainClass.main(MainClass.java:19) Java Result: 1 I don't understand the line : ("protocol://username@host/foldername"); here is the code: import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Part; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.URLName; import javax.mail.internet.InternetAddress; public class MainClass { public static void main(String[] args) throws Exception { URLName server = new URLName("protocol://username@host/foldername"); Session session = Session.getDefaultInstance(new Properties(), new MailAuthenticator()); Folder folder = session.getFolder(server); if (folder == null) { System.out.println("Folder " + server.getFile() + " not found."); System.exit(1); } folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); for (int i = 0; i < messages.length; i++) { System.out.println(messages[i].getSize() + " bytes long."); System.out.println(messages[i].getLineCount() + " lines."); String disposition = messages[i].getDisposition(); if (disposition == null){ ; // do nothing }else if (disposition.equals(Part.INLINE)) { System.out.println("This part should be displayed inline"); } else if (disposition.equals(Part.ATTACHMENT)) { System.out.println("This part is an attachment"); String fileName = messages[i].getFileName(); System.out.println("The file name of this attachment is " + fileName); } String description = messages[i].getDescription(); if (description != null) { System.out.println("The description of this message is " + description); } } folder.close(false); } } class MailAuthenticator extends Authenticator { public MailAuthenticator() { } public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username", "password"); } } Thank you for your support have a nice day A: Given the error message I really think javaMail is expecting for protocol one of "smtp:" or "imap:" or "pop3:", because it is the way it constructs its session. I don't think it will ever work with a web access, you have to get the address of the pop3/imp/smtp server the web interface connects to.
{ "pile_set_name": "StackExchange" }
Q: how to modify a function's definition graciously Assume there is a sample function defined in a library (this question's precondition is all definitions in this library cannot be modified, something like "read only"): (defun sample () (foo) (bar) (baz)) I want to use this library, but the function sample cannot match my request, what I want is: (defun sample () (foo) (when condition (bar)) (baz)) Someone told me to use defadvice, but I noticed that defadvice can only insert code before or after the invocations of sample, like: (before-advice ...) (sample) (after-advice ...) it cannot modify the definition of sample itself. So, how can I achieve this graciously? Should I have to rewrite a sample myself, called my-sample or sample2? A: sds's answer works, except that you presumably only want to be advising bar when sample is executing, so you'd need to advise sample as well in order to activate and deactivate the advice for bar. My with-temporary-advice macro facilitates this: (defmacro with-temporary-advice (function class name &rest body) "Enable the specified advice, evaluate BODY, then disable the advice." `(unwind-protect (progn (ad-enable-advice ,function ,class ,name) (ad-activate ,function) ,@body) (ad-disable-advice ,function ,class ,name) (ad-activate ,function))) (defadvice bar (around my-conditional-bar disable) ;; This advice disabled by default, and enabled dynamically. (when condition ad-do-it)) (defadvice sample (around my-sample-advice activate) "Make execution of `bar' conditional when running `sample'." (with-temporary-advice 'bar 'around 'my-conditional-bar ad-do-it)) Note that if bar is also called in other ways while sample is executing, the advice will apply for those calls as well, so you should account for that if it's a possibility. Alternatively, you may prefer to use flet to redefine bar when required. This is subject to the same caveat as the first solution, of course. (defadvice sample (around my-sample-advice activate) "Make execution of `bar' conditional when running `sample'." (if condition ad-do-it (flet ((bar () nil)) ad-do-it))) That's much simpler to read, but for reasons I don't understand flet is, as of Emacs 24.3, no longer in favour. Its docstring suggests using cl-flet instead, but as cl-flet uses lexical binding, that won't actually work. As best I could tell, it sounded like flet isn't actually going away, however the current recommendation seems to be to use advice instead. Also note that if, inside bar, the unwanted behaviour depended on some variable, then it would be preferable to use a let binding on that variable instead of the flet binding on the function. Edit: These approaches do make it harder to see what is happening, of course. Depending upon the exact situation, it may well be preferable to simply redefine the sample function to do what you want (or to write a my-sample function to call in its place, as you suggested). A: Others have already provided good answers, but since some complain about flet's disgrace, I'll show what I'd use: (defvar my-inhibit-bar nil) (defadvice bar (around my-condition activate) (unless my-inhibit-bar ad-do-it)) (defadvice sample (around my-condition activate) (let ((my-inhibit-bar (not condition))) ad-do-it)) Look ma! No flet and no ugly activate/deactive! And when you C-h f bar it will clearly tell you that there's more than meets the eye. Also I'd actually use the new advice-add instead: (defvar my-inhibit-bar nil) (defun my-bar-advice (doit &rest args) (unless my-inhibit-bar (apply doit args))) (advice-add :around 'bar #'my-bar-advice) (defun my-sample-advice (doit &rest args) (let ((my-inhibit-bar (not condition))) (apply doit args))) (advice-add :around 'sample #'my-sample-advice) A: You should advise function bar instead, using an around advice: (defadvice bar (around my-condition) (when condition ad-do-it))
{ "pile_set_name": "StackExchange" }
Q: Printing nested list as string for display I have this code: data = [["apple", 2], ["cake", 7], ["chocolate", 7], ["grapes", 6]] I want to nicely put it on display when running my code so that you won't see the speech marks,or square brackets, have it displayed like so: apple, 2 cake, 7 chocolate, 7 grapes, 6 I looked on this site to help me: http://www.decalage.info/en/python/print_list However they said to use print("\n".join), which only works if values in a list are all strings. How could I solve this problem? A: In general, there are things like pprint which will give you output to help you understand the structure of objects. But for your specific format, you can get that list with: data=[["apple",2],["cake",7],["chocolate",7],["grapes",6]] for (s,n) in data: print("%s, %d" % (s,n)) # or, an alternative syntax that might help if you have many arguments for e in data: print("%s, %d" % tuple(e)) Both output: apple, 2 cake, 7 chocolate, 7 grapes, 6
{ "pile_set_name": "StackExchange" }
Q: Are $10^{10}$-digit-numbers too big for Lenstra's elliptic curve method (ECM)? I would like to search prime factors of the numbers $$10^{10^{10}}-113$$ and $$10^{10^{10}}+13$$ Both numbers have no prime factor below $10^9$. Are these numbers still too big for ECM ? I also tried an improved (?) version of the trial division to find a factor of n : Produce a long array of random numbers $a_1,...,a_k$. Check, if there are $i\ne j$ such that $\gcd(a_i-a_j,n) \ne 1$, but did not find a factor of one of the above numbers with this method. A: On my desktop machine as of 2006, a single ECM curve run on a $10^4$-decimal-digits number with $B_1=11000$ (good for $20$-digit factors) takes more than a minute on a $2.5$-GHz core. Modmul complexity is worse than $\operatorname{O}(n\log n)$ where $n$ is the digit-count of the operands. Therefore, my runtime estimate for a $10^{10}$-digit-number gets to more than $2.5\cdot10^6$ minutes per curve on a single core. That's roughly $5$ years. Decide for yourself. Edit: Nowadays memory bandwidth has increased considerably, but that speedup still leaves the above runtime in the order of several months.
{ "pile_set_name": "StackExchange" }
Q: jQuery - restrict the amount of checkboxes checked I have a bunch of checkboxes, that I'd really like to make the user only able to select upto 5. Once selected 5, then the others are then disabled. The HTML markup is: <ul class="options-list"> <li> <input type="checkbox" value="259" name="bundle_option[9][]" id="bundle-option-9-259" class="change-container-classname checkbox bundle-option-9"> <span class="label"><label for="bundle-option-9-259">1 x Test 1</label></span> </li> <li> <input type="checkbox" value="260" name="bundle_option[9][]" id="bundle-option-9-260" class="change-container-classname checkbox bundle-option-9"> <span class="label"><label for="bundle-option-9-260">1 x Test 1</label></span> </li> <li> <input type="checkbox" value="261" name="bundle_option[9][]" id="bundle-option-9-261" class="change-container-classname checkbox bundle-option-9"> <span class="label"><label for="bundle-option-9-261">1 x Test 1</label></span> </li> <li> <input type="checkbox" value="262" name="bundle_option[9][]" id="bundle-option-9-262" class="change-container-classname checkbox bundle-option-9"> <span class="label"><label for="bundle-option-9-262">1 x Test 1</label></span> </li> <li> <input type="checkbox" value="263" name="bundle_option[9][]" id="bundle-option-9-263" class="change-container-classname checkbox bundle-option-9"> <span class="label"><label for="bundle-option-9-263">1 x Test 1</label></span> </li> <li> <input type="checkbox" value="264" name="bundle_option[9][]" id="bundle-option-9-264" class="change-container-classname checkbox bundle-option-9"> <span class="label"><label for="bundle-option-9-264">1 x Test 1</label></span> </li> </ul> My main problem is targeting the checkboxes. Can I target them using the name value of bundle_option[9][]? Thanks A: Yes you can, but because you have [ and ]'s in the name (which have a special meaning in jQuery selectors), you have to escape them with \\; (taken from API docs); If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \. $(':checkbox[name="bundle_option\\[9\\]\\[\\]"]'); See http://jsfiddle.net/G9JCw/
{ "pile_set_name": "StackExchange" }