date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/21
567
2,113
<issue_start>username_0: I am new in the Android programming I need to know How do I add two columns to a listview like this. [![enter image description here](https://i.stack.imgur.com/uCeea.png)](https://i.stack.imgur.com/uCeea.png) What is called? Do I need to modify the XML file only or will I need to modify the Java file too? This is my Code! ``` xml version="1.0" encoding="utf-8"? ```<issue_comment>username_1: For that you have to set your LayoutManager as grid layout manager. * <https://developer.android.com/guide/topics/ui/layout/gridview.html> * <https://www.androidhive.info/2012/02/android-gridview-layout-tutorial/][1]> Upvotes: -1 <issue_comment>username_2: you can try using below code for xml changes and Use the Gridview ``` xml version="1.0" encoding="utf-8"? ``` Upvotes: 0 <issue_comment>username_3: you can also use recycler view to show your layout in two columns using Recyclerview set with layout manager as - ``` public class YourClass extends AppCompatActivity { RecyclerView rv; RecyclerView.LayoutManager lm; // Create custom adapter MyRecyclerView extends to RecyclerView.Adapter implements all methods and bind the data inside OnBindView() method on custom design MyRecyclerView adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_your_activity); rv =(RecyclerView) findViewById(R.id.rv_id); rv .setHasFixedSize(true) lm = new GridLayoutManager(context, 2); rv .setLayoutManager(lm); // get the data of content to be bind on recyclerview with adapter adapter = new MyRecyclerView(context, data); rv.setAdapter(adapter); adapter.notifyDataSetChanged(); } } ``` Upvotes: 0 <issue_comment>username_4: Use Row Layout and gridview for better result you can follow the step from following website,it is a best, <https://www.tutorialspoint.com/android/android_grid_view.htm> Upvotes: 0 <issue_comment>username_5: You can fix this by making use of a Recyclerview where its LayoutManager is set as grid layout manager. Upvotes: 0
2018/03/21
392
1,392
<issue_start>username_0: I'm having a frustrating problem trying to toggle checkboxes in React. When I check the box, the state updates, and the state, previous state, and checked display `true` when I `console.log` them, which is weird in itself. But the checkbox doesn't check. **State** ``` this.state = { type: { prop1: false, prop2: false } } ``` **Handling event change** ``` handleCheckbox(e) { const name = e.target.name; const checked = e.target.checked; this.setState((prevState) => { this.state.type[name] = !prevState.type[name]; }); } ``` **Checkbox** ``` ```<issue_comment>username_1: update your handleCheckbox old state you will find as this.state ``` handleCheckbox(e) { const name = e.target.name; const checked = e.target.checked; const d = this.state.type; d[name] = !d[name]; this.setState({ type : d }); } ``` Upvotes: 0 <issue_comment>username_2: From your functional setState, you need to return the state to be updated and not mutate the original state ``` handleCheckbox(e) { const name = e.target.name; const checked = e.target.checked; this.setState((prevState) => { return { type: { ...prevState.type, [name]: !prevState.type[name] } } }); } ``` Upvotes: 3 [selected_answer]
2018/03/21
400
1,571
<issue_start>username_0: I have done all the steps to link my app with fb login. I have made my app live on Facebook Developers. Also I generated the developers key & release key and added it to fb developers site. **Problem:** When I log into my app using fb for the first time, it logs in successfully. But now if I logout and try to login again it shows the "Invalid key hash" error on the phone. I know that if I add the key hash shown in the phone to fb developers site, it will work. But what if it shows same error on other phones and adding the key hashes for all the phones is not efficient. So my question is **Do I have to add key hashes for all the phones to avoid such error? or Is there any other solutions?** p.s. I have looked the related questions in the StackOverflow but can't find the solution for my problem.<issue_comment>username_1: update your handleCheckbox old state you will find as this.state ``` handleCheckbox(e) { const name = e.target.name; const checked = e.target.checked; const d = this.state.type; d[name] = !d[name]; this.setState({ type : d }); } ``` Upvotes: 0 <issue_comment>username_2: From your functional setState, you need to return the state to be updated and not mutate the original state ``` handleCheckbox(e) { const name = e.target.name; const checked = e.target.checked; this.setState((prevState) => { return { type: { ...prevState.type, [name]: !prevState.type[name] } } }); } ``` Upvotes: 3 [selected_answer]
2018/03/21
426
1,430
<issue_start>username_0: I am using `laravel` 5.6. I want to create a project and add tasks of project. I write the following code for routing a file. ``` Route::resource('project/{pid}/tasks','TaskController'); ``` If I write a static URL like `example.com/project/1/tasks` I am getting the task list of project 1. On project list page, I used the following code: ``` $pid=$project->id; [Tasks]({{ route('project/{$pid}/tasks') }}) ``` but It is showing a routing error. How to get project id on task controller?<issue_comment>username_1: You should use url(), you can use route() by calling the name of the route. ``` [Tasks]({{ url('project/'.$pid.'/tasks') }}) ``` Upvotes: 2 <issue_comment>username_2: Try this : ``` @php $pid=$project->id; @endphp [Tasks]({{ url('project/'.$pid.'/tasks') }}) ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: ``` [Tasks]({{ url('project')}}/{{$pid}}/tasks) ``` Upvotes: 0 <issue_comment>username_4: You should try this: ``` [Tasks]({{ url('project/tasks', $pid) }}) ``` Upvotes: 0 <issue_comment>username_5: ``` {{ url('/project/tasks/', [$pid]) }} ``` i think its is bad practice to use relative path. i recommend to you always use link to route because any time if you want to change url .you will need to change it manually.urls could be 100 or 1000 to change.which is dangers for app ``` {{ route('route name', ['id' => $pid]) }} ``` Upvotes: 1
2018/03/21
747
2,505
<issue_start>username_0: I have 3 tables 1) Users(userId, age) 2) Purchases (purchaseId, userId, itemId, date) 3) Items (itemId, price). Goal is to write a query to show average sum of purchase for each user grouped by month. I'm currently not sure if I even need the first table, so far I have smth like this: ``` SELECT Purchases.userid, Purchases.date, Purchases.itemId Items.itemId, AVG(SUM(Items.price)) FROM Purchases INNER JOIN Purchases.itemId ON Items.itemId GROUP BY (somehow group by month) ``` And I'm stuck. Could you please explain, how to write such a query. Sorry that I don't have examples of tables, or correct output example, since it is a test task. Thanks!<issue_comment>username_1: In SQL Server: ``` SELECT p.userid, itm.itemId, YEAR(p.date), MONTH(p.date), AVG(itm.price) FROM Purchases p INNER JOIN Items itm ON p.itemId = itm.itemId GROUP BY p.userid, itm.itemId, YEAR(p.date), MONTH(p.date) ``` Upvotes: 1 <issue_comment>username_2: You can try this. ``` SELECT Purchases.userid, MONTH(Purchases.date), AVG(Items.price) FROM Purchases INNER JOIN Items ON Purchases.itemId = Items.itemId GROUP BY Purchases.userid, MONTH(Purchases.date) ``` Upvotes: 1 <issue_comment>username_3: Grouping by month requires placing a date into "buckets" for the year and month related to that date. Each database type has it's own unique set of functions for this, e.g. ``` --MS SQL Server SELECT Purchases.userid, Purchases.itemId, year(Purchases.date), month(Purchases.date), AVG(Items.price) FROM Purchases GROUP BY Purchases.userid, Purchases.itemId, year(Purchases.date), month(Purchases.date) --Oracle SELECT Purchases.userid, Purchases.itemId, trunc(Purchases.date,'YYYYMM'), AVG(Items.price) FROM Purchases GROUP BY Purchases.userid, Purchases.itemId, trunc(Purchases.date,'YYYYMM') ``` Upvotes: 1 <issue_comment>username_4: You can't use double aggregate like `AVG(SUM(Items.price))` So you might be a subquery to get `SUM` then use `AVG` In SQL Server: ``` SELECT Purchases.userid, YEAR(Purchases.date), MONTH(Purchases.date), Purchases.itemId Items.itemId, AVG(Items.SumPrice) FROM Purchases INNER JOIN Users T2 ON Purchases.userId = T2.userId INNER JOIN (SELECT itemId, SUM(price) AS SumPrice FROM Items GROUP BY itemId) AS Items ON Items.itemId GROUP BY Purchases.userid, Purchases.itemId, YEAR(Purchases.date), MONTH(Purchases.date), Items.itemId ``` Upvotes: 2
2018/03/21
1,668
5,093
<issue_start>username_0: This is my query , ``` var id = [1,2]; var oparr = [{ "off": [{ id: 1, val: "aaa" }, { id: 3, val: "bbb" } ] }, { "off1": [{ id: 2, val: "cccc" }] } ]; ``` from the above `oparr` array I need to find with `id` array, I need this result ``` var arr = { finalval: [ { id: 1, off: true, off1: false }, { id: 2, off: false, off1: true }] } ``` If the id is in `off[0]` I need set `off1` as true and `off2` as false. I tried with underscore js `indexof` , `find` , `findWhere` but I didn't get the desired result format.<issue_comment>username_1: ```js var id = [1,2]; var oparr = [ { "off": [ { id: 1, val: "aaa" }, { id: 3, val: "bbb" } ] }, { "off1": [ { id: 2, val: "cccc" } ] } ]; var arr = { finalval: [ { id: 1, off: true, off1: false }, { id: 2, off: false, off1: true } ] } var arr = {}; arr.finalval = id.map((i) => { return { id : i, off : oparr.find(object => "off" in object)["off"].some(object => object.id == i), off1: oparr.find(object => "off1" in object)["off1"].some(object => object.id == i), } }); console.log(arr.finalval); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Try this ```js var id = [1, 2]; var oparr = [{ "off": [{ id: 1, val: "aaa" }, { id: 3, val: "bbb" } ] }, { "off1": [{ id: 2, val: "cccc" }] } ]; var b = id.map((x) => { return oparr.reduce((a, data) => { var key = Object.keys(data)[0]; Object.assign(a, data[key].reduce((obj, ele) => { if (!obj[key]) obj[key] = (ele.id == x); return obj; }, { id: x })); return a; }, {}) }) console.log(b); ``` Upvotes: 2 <issue_comment>username_3: You can try the following with Array's `forEach()`: ```js var id = [1,2]; var oparr = [ { "off": [ { id: 1, val: "aaa" }, { id: 3, val: "bbb" } ] }, { "off1": [ { id: 2, val: "cccc" } ] }]; var arr = {finalval: []}; oparr.forEach(function(item){ for(var key in item){ item[key].forEach(function(i){ if(id.includes(i.id) && key == 'off') arr.finalval.push({id: i.id, off: true, off1: false}); else if(id.includes(i.id) && key == 'off1') arr.finalval.push({id: i.id, off: false, off1: true}); }); } }); console.log(arr); ``` Upvotes: 2 <issue_comment>username_4: This solution handles the case where you might have more than `off` and `off1` (e.g. `off, off1, off2, off3` etc.). ```js var id = [1, 2]; var oparr = [{ "off": [{ id: 1, val: "aaa" }, { id: 3, val: "bbb" } ] }, { "off1": [{ id: 2, val: "cccc" }] } ]; // get the off options (off, off1, off2 etc.) var offOptions = oparr.map(op => Object.keys(op)).reduce((a, c) => a.concat(c), []); var arr = { finalval: id.map(x => { var result = { id: x }; // iterate through off options offOptions.forEach(op => { // iterate through oparr oparr.forEach(o => { var vals = o[op]; if (vals) // check if off option exists result[op] = vals.some(i => i.id === x); // check if index exists }); }); return result; }) }; console.log(arr); ``` Upvotes: 2 <issue_comment>username_5: ```js var oparr = [ { "off":[ { id:1, val:"aaa" }, { id:3, val:"bbb" } ] }, { "off1":[ { id:2, val:"cccc" } ] } ]; var offs = []; var finalval = []; for(var i=0; i ``` Upvotes: 2 <issue_comment>username_6: I hope this will help. Thank you. ```js var id = [1, 2]; var oparr = [{ "off": [{ id: 1, val: "aaa" }, { id: 3, val: "bbb" } ] }, { "off1": [{ id: 2, val: "cccc" }] } ]; var test=[]; for (var i = 0; i < oparr.length; i++) { for (var j = 0; j < Object.keys(oparr[i]).length; j++) { for (var k = 0; k < id.length; k++) { if(oparr[i][Object.keys(oparr[i])[j]][j].id==id[k]){ test.push(oparr[i][Object.keys(oparr[i])[j]][j]); } } } } console.log(test); ``` Upvotes: 1
2018/03/21
3,710
12,019
<issue_start>username_0: I have a trivial Maven project: ``` src └── main └── java └── module-info.java pom.xml ``` pom.xml: ``` org.example example 1.0-SNAPSHOT jar example org.apache.maven.plugins maven-compiler-plugin 3.7.0 10 ``` When I build the project via `mvn -X install -DskipTests=true`, it fails: ``` org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:testCompile (default-testCompile) on project example: Execution default-testCompile of goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:testCompile failed. at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81) 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:309) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:194) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:107) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:993) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:345) at org.apache.maven.cli.MavenCli.main(MavenCli.java:191) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:564) 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) Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default-testCompile of goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:testCompile failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208) ... 20 more Caused by: java.lang.IllegalArgumentException at org.objectweb.asm.ClassReader.(Unknown Source) at org.objectweb.asm.ClassReader.(Unknown Source) at org.objectweb.asm.ClassReader.(Unknown Source) at org.codehaus.plexus.languages.java.jpms.AsmModuleInfoParser.parse(AsmModuleInfoParser.java:80) at org.codehaus.plexus.languages.java.jpms.AsmModuleInfoParser.getModuleDescriptor(AsmModuleInfoParser.java:54) at org.codehaus.plexus.languages.java.jpms.LocationManager.resolvePaths(LocationManager.java:83) at org.apache.maven.plugin.compiler.TestCompilerMojo.preparePaths(TestCompilerMojo.java:281) at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:762) at org.apache.maven.plugin.compiler.TestCompilerMojo.execute(TestCompilerMojo.java:176) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134) ... 21 more ``` Is there a way to fix this?<issue_comment>username_1: UPDATE ------ **The answer is now obsolete. See [this answer](https://stackoverflow.com/a/51586202/706317).** --- `maven-compiler-plugin` depends on the old version of ASM which does not support Java 10 (and Java 11) yet. However, it is possible to explicitly specify the right version of ASM: ``` org.apache.maven.plugins maven-compiler-plugin 3.7.0 10 org.ow2.asm asm 6.2 ``` You can find the latest at <https://search.maven.org/search?q=g:org.ow2.asm%20AND%20a:asm&core=gav> Upvotes: 7 <issue_comment>username_2: As of 30Jul, 2018 to fix the above issue, one can configure the java version used within maven to any up to JDK/11 and make use of the **[`maven-compiler-plugin:3.8.0`](https://maven.apache.org/plugins/maven-compiler-plugin/download.cgi)** to specify a release of either 9,10,11 *without any explicit dependencies*. ``` org.apache.maven.plugins maven-compiler-plugin 3.8.0 11 ``` ***Note***:- The default value for source/target has been lifted from 1.5 to 1.6 with this version. -- [release notes.](https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12317225&version=12341563) --- ***Edit [30.12.2018]*** In fact, you can make use of the same version of `maven-compiler-plugin` while compiling the code against JDK/12 as well. More details and a sample configuration in how to [Compile and execute a JDK preview feature with Maven](https://stackoverflow.com/questions/52232681/compile-a-jdk12-preview-feature-with-maven). Upvotes: 9 [selected_answer]<issue_comment>username_3: Boosting your `maven-compiler-plugin` to `3.8.0` seems to be necessary but not sufficient. If you're still having problems, you should also make sure your `JAVA_HOME` environment variable is set to Java 10 (or 11) if you're running from the command line. (The error message you get won't tell you this.) Or if you're running from an IDE, you need to make sure it is set to run maven with your current JDK. Upvotes: 5 <issue_comment>username_4: Specify maven.compiler.source and target versions. 1) Maven version which supports jdk you use. In my case JDK 11 and maven 3.6.0. 2) pom.xml ``` 11 11 ``` As an alternative, you can fully specify maven compiler plugin. See previous answers. It is shorter in my example :) ``` org.apache.maven.plugins maven-compiler-plugin 3.8.0 11 ``` 3) rebuild the project to avoid compile errors in your IDE. 4) If it still does not work. In Intellij Idea I prefer using terminal instead of using terminal from OS. Then in Idea go to file -> settings -> build tools -> maven. I work with maven I downloaded from apache (by default Idea uses bundled maven). Restart Idea then and run `mvn clean install` again. Also make sure you have correct **Path**, **MAVEN\_HOME**, **JAVA\_HOME** environment variables. I also saw this one-liner, but it does not work. ``` 11 ``` I made some quick starter projects, which I re-use in other my projects, feel free to check: * <https://github.com/yan-khonski-it/mvn-pmd-java11> * <https://github.com/yan-khonski-it/pmd-java-14> Upvotes: 5 <issue_comment>username_5: It might not exactly be the same error, but I had a similar one. **Check Maven Java Version** Since Maven is also runnig with Java, check first with which version your Maven is running on: ``` mvn --version | grep -i java ``` It returns: > > Java version 1.8.0\_151, vendor: Oracle > Corporation, runtime: C:\tools\jdk\openjdk1.8 > > > **Incompatible version** Here above my maven is running with `Java Version 1.8.0_151`. So even if I specify maven to compile with `Java 11`: ``` 11 ${java.version} ${java.version} ``` It will logically print out this error: > > [ERROR] Failed to execute goal > org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile > (default-compile) on project efa-example-commons-task: Fatal error > compiling: invalid target release: 11 -> [Help 1] > > > **How to set specific java version to Maven** The logical thing to do is to set a higher Java Version to Maven (e.g. Java version 11 instead 1.8). Maven make use of the environment variable `JAVA_HOME` to find the Java Version to run. So change this variable to the JDK you want to compile against (e.g. OpenJDK 11). **Sanity check** Then run again `mvn --version` to make sure the configuration has been taken care of: ``` mvn --version | grep -i java ``` yields > > Java version: 11.0.2, vendor: Oracle Corporation, runtime: C:\tools\jdk\openjdk11 > > > Which is much better and correct to compile code written with the Java 11 specifications. Upvotes: 5 <issue_comment>username_6: Alright so for me nothing worked. I was using spring boot **with** hibernate. The spring boot version was ~2.0.1 and I would keep get this error and null pointer exception upon compilation. The issue was with hibernate that needed a version bump. But after that I had some other issues that seemed like the annotation processor was not recognised so I decided to just bump spring from 2.0.1 to 2.1.7-release and everything worked as expected. You still need to add the above plugin tough Hope it helps! Upvotes: 0 <issue_comment>username_7: If you are using spring boot then add these tags in pom.xml. ``` org.springframework.boot spring-boot-maven-plugin ``` and ``` UTF-8 UTF-8 ``10 ``` You can change java version to 11 or 13 as well in tag. Just add below tags in pom.xml ``` UTF-8 UTF-8 11 ``` You can change the 11 to 10, 13 as well to change java version. I am using java 13 which is latest. It works for me. Upvotes: 3 <issue_comment>username_8: In my case, I had to explicitly set **JAVA\_HOME** to JDK-11 in my script though the terminal shows Java 11 version. This was because, I'm executing `mvn` through shell script and `mvn` was using default JDK of my machine which was JDK8. I confirmed which JDK version is being used by `mvn` in script & set to JDK-11 as below: ``` #!/bin/bash echo $(java -version) echo $(mvn --version | grep -i java ) export JAVA_HOME="/opt/jdk11/" export PATH=$JAVA_HOME/bin:$PATH echo $(java -version) echo $(mvn --version | grep -i java ) ``` Upvotes: 1 <issue_comment>username_9: If nothing else works and even after you set JAVA\_HOME to a *correct* path, check if there is no override of the JAVA\_HOME path in `/.mavenrc`! Upvotes: 0 <issue_comment>username_10: In my case, * "echo $JAVA\_HOME" shows version 11 * "java -version" shows version 11 * However, "mvn -version" shows "Java version" is NOT 11 I paste this on the top of .bash\_profile and source it. It works. ``` export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8) export JAVA_11_HOME=$(/usr/libexec/java_home -v11) alias java8='export JAVA_HOME=$JAVA_8_HOME;export PATH=$HOME/bin:$JAVA_HOME/bin:$PATH' alias java11='export JAVA_HOME=$JAVA_11_HOME;export PATH=$HOME/bin:$JAVA_HOME/bin:$PATH' java11 ``` Upvotes: 0 <issue_comment>username_11: `mvn` may be using `JAVA_HOME`, but if setting it doesn't work, there may be overrides in the actual mvn scripts For example, on my system (mac), which mvn points to `/usr/local/bin/mvn` which actually points to `/usr/local/Cellar/maven/3.8.6/bin/mvn`, which is a bash script pointing to `/usr/local/Cellar/maven/3.8.6/libexec/bin/mvn` and that script reads like this at the top: ```bash if [ -z "$MAVEN_SKIP_RC" ] ; then if [ -f /usr/local/etc/mavenrc ] ; then . /usr/local/etc/mavenrc fi if [ -f /etc/mavenrc ] ; then . /etc/mavenrc fi if [ -f "$HOME/.mavenrc" ] ; then . "$HOME/.mavenrc" fi fi ``` So it shows it's looking in 3 different places for env, unless `MAVEN_SKIP_RC` is set. If I run `MAVEN_SKIP_RC=1 mvn -version`, now the JAVA\_HOME is taken into account. but the real fix is to find the culprit in the mavenrc files In my case, the only file present was `/etc/mavenrc` and it read: ```bash JAVA_HOME=$(/usr/libexec/java_home -v 1.8) ``` So it was setting java 1.8 as the default, overriding the original JAVA\_HOME. change that to -v 11 and it works as expected. Or simply remove the /etc/mavenrc altogether to restore the default to the JAVA\_HOME value. Upvotes: 1
2018/03/21
627
2,790
<issue_start>username_0: When I upload file from Nexus 6 using amazon s3 SDK some time it throws me com.amazonaws.AmazonClientException: More data read (4567265) than expected (4561427) exception. But when I upload image from Moto G4 plus with same code it will uploaded every time. Please help me in solving this issue. Here is my code for reference: ``` private void uploadingScreenshot(String filePath) { File file = new File(filePath); if (file.exists()) { final String serverPath = S3Util.getMediaPath(Utility.MediaType.SCREENSHOT, false, ""); ObjectMetadata meta = new ObjectMetadata(); meta.setContentLength(file.length()); S3Util.uploadMedia(SharedFolderDetailActivity.this, file, serverPath, meta, new TransferListener() { @Override public void onStateChanged(int id, TransferState state) { switch (state) { case COMPLETED: { String path = S3Constants.BUCKET_URL + serverPath; callTookScreenshotNotifierWS(path); } break; } } @Override public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) { } @Override public void onError(int id, Exception ex) { if (ex != null) Log.e(TAG, ex.getMessage()); } }); } } ``` This function is used to upload file on amazon s3 server. ``` public class S3Util { public static TransferObserver uploadMedia(final Context context, File file, String s3Path, ObjectMetadata objectMetadata, TransferListener l) { TransferObserver observer = getTransferUtility(context).upload(S3Constants.BUCKET_NAME, s3Path, file,objectMetadata); observer.setTransferListener(l); return observer; } } ```<issue_comment>username_1: try this answer [AmazonClientException: Data read has a different length than the expected](https://stackoverflow.com/questions/27798825/amazonclientexception-data-read-has-a-different-length-than-the-expected) I have also faced this problem previously, hopefully, this may help you Upvotes: 1 <issue_comment>username_2: My opinion is, that there is something compatibility problem with aws-sdk and android sdk. The best way, is try to downgrade your aws-version and find out more stable version with your android sdk. Maybe I'm wrong.. Also, I recommend you to write issue in <https://github.com/aws/aws-sdk-android/issues> I hope that you will be able to solve your problem. Good Luck!) Upvotes: 0
2018/03/21
388
1,528
<issue_start>username_0: I have been successfully using commonfinders to get a single element in flutter driver but when it comes to multiple elements which may have the same type, it always throws up an error. I understand this is by design. I would be grateful if someone could suggest a way to get multiple elements and store them in an array/list, So I can access them through their index. A similar functionality would be, in selenium, where it lets you use findElements(...) for multiple elements in contrast to findElement(...) which lets you search a single element.<issue_comment>username_1: The finders in flutter\_driver are currently quite limited, in contrast to the finders provided by flutter\_test. This is a known issue that will presumably be addressed someday: see <https://github.com/flutter/flutter/issues/12810> In the meantime, as the ticket suggests, if you can assign a predictable key to your elements (e.g. `my-el-01`, `my-el-02`, `my-el-03`) then you can write a helper (`findMyEl(String prefix, int maxEls)`) that will try to find all the elements named per that scheme, and return as a list. :/ Upvotes: 2 <issue_comment>username_2: This is how to get first of elements by its type ``` find.descendant( of: find.byValueKey(parentWidgetKey), matching: find.byType('CheckBox'), firstMatchOnly: true, ); ``` If you have multiple checkboxes, just assign a key to their parent, get the parent by key, get the checkbox by type and set the `firstMatchOnly` flag to `true` Upvotes: 3
2018/03/21
578
2,657
<issue_start>username_0: I have one question in my code I am using server and client session obj. like this ``` Session serverSession=HibernateUtilServer.getSession(); Session clientSession=HibernateUtilLocal.getSession(); ``` // some database operation here .... ``` serverSession.beginTransaction().commit(); clientSession.beginTransaction().commit(); ``` But problem is that `serverSession.beginTransaction().commit();` **after this line if I am getting some network issue means some exception**. I cant commit my clientSession data this is ok means I can `clientSession.beginTransaction().rollBack();`. So I want to rollBack serverSession data also how to do this please help me.. **Note: Here serverSession and clientSession both have different database connection and different configurations file** thank you..<issue_comment>username_1: It depends on use of hibernate & spring. I see that you used very good framework . it has already very good transaction management support. I suggest you that don't do this things manually. use its core transaction support. Just example: @Transaction Annotation which you marked at method level, class level etc Just read how it works!!. you will get better idea. Refer link : <https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/transaction.html> **EDIT** If you are not using spring then you need to catch exception. And you need to rollback transaction there. if you want to add framework layer then add supper class or common method to rollback transaction. call into catch block. Upvotes: 1 <issue_comment>username_2: The session-per-request pattern uses one JDBC connection per session if you run local transactions. For JTA, the connections are aggressively released after each statement only to be reacquired for the next statement. The Hibernate transaction API delegates the begin/commit/rollback to the JDBC Connection for local transactions and to the associated UserTransaction for JTA. Therefore, you can run multiple transactions on the same Hibernate Session, but there's a catch. Once an exception is thrown you can no longer reuse that Session. My advice is to divide-and-conquer. Just split all items, construct a Command object for each of those and send them to an ExecutorService#invokeAll. Use the returned List to iterate and call Future#get() to make sure the original thread waits after all batch jobs to complete. The ExecutorService will make sure you run all Commands concurrently and each Command should use a Service that uses its own @Transaction. Because transactions are thread-bound you will have all batch jobs run in isolation. Upvotes: 2
2018/03/21
743
2,447
<issue_start>username_0: ``` $document = new Document(); $document->title = $request['title']; $document->description = $request['description']; ``` When i try to output the above code using `echo $document;` i get this result: ``` {"title":"asdfasdf","description":"asdfasdfsadf"} ``` What i want is to create my own array of data and output the same format. This is the code i am trying to experiment but it does not work: ``` $data = array( "title" => "hello", "description" => "test test test" ); echo $data; ``` Any Help would be appreciated. Thanks.<issue_comment>username_1: All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays: ``` foreach ($document as $data) { echo $data->title; echo $data->description; } ``` There is no difference while using a PHP framework. You may refer the official [PHP Arrays Manual](http://php.net/manual/en/language.types.array.php) page to work with the language construct. If you need to convert JSON to array, use: > > **$data->toArray();** > > > OR > > ***json\_decode($data);*** > > > Here is your code: ``` $data = array( "title" => "hello", "description" => "test test test" ); ``` // may also declare ``` $data = ["title" => "hello", "description" => "test test test"]; ``` Use: > > **var\_dump($data);** > > > OR > > **print\_r($data);** > > > // and the output will be ``` ["title" => "hello", "description" => "test test test",] ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: foreach is also possible to traverse other structures and not just arrays: * List item * Properties of any type of object * Classes that extend or implement iterator in PHP Functions and methods that use generators in PHP As we can see in the example below, the use of foreach to traverse the properties of the Local class object: ``` class Local { public string $country; public string $state; public string $city; public int $zipCode; public function __construct(string $country, string $state, string $city, int $zipCode) { $this->country = $country; $this->state = $state; $this->city = $city; $this->zipCode = $zipCode; } } $eduGouveia = new Local("Brasil", "São Paulo", "São Paulo", 2996180); foreach ($eduGouveia as $property => $value) { echo $property . " - " . $value . PHP_EOL; } ``` Upvotes: 0
2018/03/21
753
3,226
<issue_start>username_0: Recently, I am working on an application based on Pasteboard. I want to find out that copied text is not stored in pasteboard from the selected running application. Anyone have idea?<issue_comment>username_1: There's no API to retrieve the application responsible for putting data on the Pasteboard. If it's your own app you want to know about then you have to handle it yourself, otherwise you're out of luck. Upvotes: 0 <issue_comment>username_2: Although your question is a bit unclear, what I understand is that you want to know which application just added something to the pasteboard (and of course you also want the content of the pasteboard). While there is no API, there's a way. It's kind of a hack but that's how Apple does it themselves in their examples, so I guess it's ok. The main idea is to regularly poll the pasteboard with a timer, and to observe `.NSWorkspaceDidActivateApplication` at the same time: this way we can know which application is active when something new appears in the pasteboard. Here's an example of a class that does this: ``` class PasteboardWatcher { private let pasteboard = NSPasteboard.general() // Keep track of the changes in the pasteboard. private var changeCount: Int // Used to regularly poll the pasteboard for changes. private var timer: Timer? private var frontmostApp: (name: String, bundle: String)? init() { // On launch, we mirror the pasteboard context. self.changeCount = pasteboard.changeCount // Registers if any application becomes active (or comes frontmost) and calls a method if it's the case. NSWorkspace.shared().notificationCenter.addObserver(self, selector: #selector(activeApp(sender:)), name: .NSWorkspaceDidActivateApplication, object: nil) if let types = pasteboard.types { print("Available pasteboards: \(types)") } } // Start polling for changes in pasteboard. func startPolling() { self.timer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(checkForChangesInPasteboard), userInfo: nil, repeats: true) } // Called by NSWorkspace when any application becomes active or comes frontmost. @objc private func activeApp(sender: NSNotification) { if let info = sender.userInfo, let content = info[NSWorkspaceApplicationKey] as? NSRunningApplication, let name = content.localizedName, let bundle = content.bundleIdentifier { frontmostApp = (name: name, bundle: bundle) } } @objc private func checkForChangesInPasteboard() { if pasteboard.changeCount != changeCount { changeCount = pasteboard.changeCount if let copied = pasteboard.string(forType: NSStringPboardType), let app = frontmostApp { print("Copied string is: '\(copied)' from \(app.name) (\(app.bundle))") } } } } ``` Use it simply like this: ``` let watcher = PasteboardWatcher() watcher.startPolling() ``` And it prints the copied string in the console, with also the name and bundle of the app. Upvotes: 3 [selected_answer]
2018/03/21
1,844
7,312
<issue_start>username_0: I have this line in some code I want to copy into my controller, but the compiler complains that > > The name 'Server' does not exist in the current context > > > ``` var UploadPath = Server.MapPath("~/App_Data/uploads") ``` How can I achieve the equivalent in ASP.NET Core?<issue_comment>username_1: **UPDATE: IHostingEnvironment is deprecated. See update below.** In Asp.NET Core 2.2 and below, the hosting environment has been abstracted using the interface, [IHostingEnvironment](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.ihostingenvironment?view=aspnetcore-2.0) The [ContentRootPath](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.ihostingenvironment.contentrootpath?view=aspnetcore-2.0#Microsoft_AspNetCore_Hosting_IHostingEnvironment_ContentRootPath) property will give you access to the absolute path to the application content files. You may also use the property, [WebRootPath](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.ihostingenvironment.webrootpath?view=aspnetcore-2.0#Microsoft_AspNetCore_Hosting_IHostingEnvironment_WebRootPath) if you would like to access the web-servable root path (www folder by default) You may inject this dependency into your controller and access it as follows: ``` public class HomeController : Controller { private readonly IHostingEnvironment _hostingEnvironment; public HomeController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } public ActionResult Index() { string webRootPath = _hostingEnvironment.WebRootPath; string contentRootPath = _hostingEnvironment.ContentRootPath; return Content(webRootPath + "\n" + contentRootPath); } } ``` **UPDATE - .NET CORE 3.0 and Above** IHostingEnvironment has been marked obsolete with .NET Core 3.0 as pointed out by @[amir133](https://stackoverflow.com/users/9076865/amir133). You should be using [IWebHostEnvironment](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.iwebhostenvironment?view=aspnetcore-3.1) instead of [IHostingEnvironment](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.ihostingenvironment?view=aspnetcore-2.0). Please refer to that answer [below](https://stackoverflow.com/a/55934673/7960700). Microsoft has neatly segregated the host environment properties among these interfaces. Please refer to the interface definition below: ``` namespace Microsoft.Extensions.Hosting { public interface IHostEnvironment { string EnvironmentName { get; set; } string ApplicationName { get; set; } string ContentRootPath { get; set; } IFileProvider ContentRootFileProvider { get; set; } } } namespace Microsoft.AspNetCore.Hosting { public interface IWebHostEnvironment : IHostEnvironment { string WebRootPath { get; set; } IFileProvider WebRootFileProvider { get; set; } } } ``` Upvotes: 8 [selected_answer]<issue_comment>username_2: .NET 6 (.NET Core 3 and above) ------------------------------ For example I want to locate `~/wwwroot/CSS` ``` public class YourController : Controller { private readonly IWebHostEnvironment _webHostEnvironment; public YourController (IWebHostEnvironment webHostEnvironment) { _webHostEnvironment= webHostEnvironment; } public IActionResult Index() { string webRootPath = _webHostEnvironment.WebRootPath; string contentRootPath = _webHostEnvironment.ContentRootPath; string path =""; path = Path.Combine(webRootPath , "CSS"); //or path = Path.Combine(contentRootPath , "wwwroot" ,"CSS" ); return View(); } } ``` --- Some Tricks ----------- Also if you don't have a controller or service,follow last Part and register it's class as a singleton. Then, in `Startup.ConfigureServices`: ``` services.AddSingleton(); ``` Finally, inject `your_class_Name` where you need it. --- .NET Core 2 ----------- For example I want to locate `~/wwwroot/CSS` ``` public class YourController : Controller { private readonly IHostingEnvironment _HostEnvironment; //diference is here : IHostingEnvironment vs I*Web*HostEnvironment public YourController (IHostingEnvironment HostEnvironment) { _HostEnvironment= HostEnvironment; } public ActionResult Index() { string webRootPath = _HostEnvironment.WebRootPath; string contentRootPath = _HostEnvironment.ContentRootPath; string path =""; path = Path.Combine(webRootPath , "CSS"); //or path = Path.Combine(contentRootPath , "wwwroot" ,"CSS" ); return View(); } } ``` --- MoreDetails ----------- Thanks to @Ashin but `IHostingEnvironment` is obsoleted in MVC Core 3!! according to [this](https://github.com/aspnet/AspNetCore/issues/7749) : Obsolete types (warning): ``` Microsoft.Extensions.Hosting.IHostingEnvironment Microsoft.AspNetCore.Hosting.IHostingEnvironment Microsoft.Extensions.Hosting.IApplicationLifetime Microsoft.AspNetCore.Hosting.IApplicationLifetime Microsoft.Extensions.Hosting.EnvironmentName Microsoft.AspNetCore.Hosting.EnvironmentName ``` New types: ``` Microsoft.Extensions.Hosting.IHostEnvironment Microsoft.AspNetCore.Hosting.IWebHostEnvironment : IHostEnvironment Microsoft.Extensions.Hosting.IHostApplicationLifetime Microsoft.Extensions.Hosting.Environments ``` So you must use `IWebHostEnvironment` instead of `IHostingEnvironment`. Upvotes: 7 <issue_comment>username_3: use for example: `var fullPath = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");` Upvotes: 3 <issue_comment>username_4: The accepted answer's suggestion is good enough in most scenarios, however - since it depends on *Dependency Injection* - is limited to Controllers and Views: in order to have a proper `Server.MapPath` replacement that can be accessed from non-singleton helper classes we can add the following line(s) of code at the end of the `Configure()` method of the app's `Startup.cs` file: ``` // setup app's root folders AppDomain.CurrentDomain.SetData("ContentRootPath", env.ContentRootPath); AppDomain.CurrentDomain.SetData("WebRootPath", env.WebRootPath); ``` This way we'll be able to retrieve them from within any class (including, yet not limiting to, Controllers and Views) in the following way: ``` var contentRootPath = (string)AppDomain.CurrentDomain.GetData("ContentRootPath"); var webRootPath = (string)AppDomain.CurrentDomain.GetData("WebRootPath"); ``` This can be further exploited to create a static helper method that will allow us to have the same functionality as the good old `Server.MapPath`: ``` public static class MyServer { public static string MapPath(string path) { return Path.Combine( (string)AppDomain.CurrentDomain.GetData("ContentRootPath"), path); } } ``` Which can be used it in the following way: ``` var docPath = MyServer.MapPath("App_Data/docs"); ``` For additional info regarding this approach and a bit of background, take a look at [this post](https://www.ryadel.com/en/asp-net-core-server-mappath-equivalent-absolute-path/) on my blog. Upvotes: 6
2018/03/21
1,141
4,291
<issue_start>username_0: I am trying to get all the data from `firestore` - `collection` and `subcollection` into an `observable` form of `array` and display it with `async` pipe. ``` availableCategoriesCollection: AngularFirestoreCollection; availableCategories$: Observable; lstCategories: Observable; this.availableCategoriesCollection = this.httpDataService.getAllCategories(); this.availableCategories$ = this.availableCategoriesCollection.snapshotChanges().map(data => { return data.map(record => { const rec = record.payload.doc.data() as Category; const cId = record.payload.doc.id; return {cId, ...rec}; }); }); this.lstCategories = this.availableCategories$.mergeMap(data => { const observables = data.map((rec: CategoryId) => { if (rec.hasSubCat) { return this.httpDataService.getSubCategory(rec.cId).snapshotChanges().map(d => { return d.map(r => { const arr: any = {}; arr.id = r.payload.doc.id; arr.itemName = (r.payload.doc.data() as Category).categoryName; arr.category = rec.categoryName; return Observable.of(arr); }); }); }else { const arr: any = {}; arr.id = rec.id; arr.itemName = rec.categoryName; arr.category = 'All'; return Observable.of(arr); } }); return Observable.forkJoin(observables); }); ``` and I've used ```` {{lstCategories | async | json}} ```` to display the data, but it is always null. When I `console.log(observables)` before `forkJoin` I get `(9) [ScalarObservable, Observable, Observable, ScalarObservable, ScalarObservable, ScalarObservable, ScalarObservable, ScalarObservable, Observable]` out of which 3 of them which are `Observable` are subcategories and 6 of them which are `ScalarObservable` are main categories. In spite of this data, the lstCategories doesn't get updated via `async`. I've also tried to subscribe to `lstCategories` like ``` this.lstCategories.subscribe(data => { console.log(data); }); ``` but the above log never happens which means it is not getting subscribed. My knowledge on `rxjs` is very weak. Hope to find some help here.<issue_comment>username_1: It seems that you are returning `Observable` of `Observable` of some array at following code block ``` map(d => ... arr.id = r.payload.doc.id; arr.itemName = (r.payload.doc.data() as Category).categoryName; arr.category = rec.categoryName; return Observable.of(arr); ... ``` This block is already inside a map function of an Observable. When you return another Observable your whole return object looks like `Observable>` Just change return line to `return arr;` Upvotes: 1 <issue_comment>username_2: When you use map, you transform the response of a request. You needn't return an Observalbe ``` this.httpDataService.getSubCategory(rec.cId).snapshotChanges().map(d => { return d.map(r => { const arr: any = {}; arr.id = r.payload.doc.id; arr.itemName = (r.payload.doc.data() as Category).categoryName; arr.category = rec.categoryName; return arr //<--simply return arr // return Observable.of(arr); <--I think it's WORNG }); ``` Upvotes: 0 <issue_comment>username_3: Try this way ``` this.lstCategories = this.availableCategoriesCollection.snapshotChanges().map(changes => { return changes.map(a => { const data = a.payload.doc.data() as Category; if(data.hasSubCat){ const signupId = a.payload.doc.id; return this.httpDataService.getSubCategory(signupId).snapshotChanges().map(actions => { return actions.map(d => { return d; }); }).map(signup => { return signup.map(md => { const arr: any = {}; arr.id = md.payload.doc.id; arr.itemName = (md.payload.doc.data() as Category).categoryName; arr.category = data.categoryName; return arr; }); }); }else { const arr: any = {}; arr.id = a.payload.doc.id; arr.itemName = data.categoryName; arr.category = 'All'; return Observable.of(arr); } }); }).flatMap(records => Observable.combineLatest(records)).map(data => { return [].concat(...data).map(d => { return d; }) }); ``` Upvotes: 2 [selected_answer]
2018/03/21
803
2,274
<issue_start>username_0: I have created a calculator using `if` statement in `PHP` and I was able to get the output i needed. I am stuck with switch case. I'm not getting the output I want. This is my code: ``` Untitled Document php $num1 = ""; $num2 = ""; $calc = ""; if (isset($\_POST['submit'])) { $num1 = $\_POST['n1']; $num2 = $\_POST['n2']; function calculate($num1,$num2,$calc){ switch ($\_POST['submit']) { case 'addition': $calc = $n1 + $n2; break; case 'sub': $calc = $n1 - $n2; break; } } } ? NO 1 : NO 2: total: ```<issue_comment>username_1: You have lot of bugs in your code. like 1) You have declared function but never call it. 2) Variable names issue. 3) Submit button value and switch case never match etc... You need to change your code as below: ``` Untitled Document php $num1 = ""; $num2 = ""; $calc = ""; if (isset($\_POST['submit'])) { $num1 = $\_POST['n1']; $num2 = $\_POST['n2']; function calculate($num1,$num2){ $calc = ""; switch ($\_POST['submit']) { case 'addition': $calc = $num1 + $num2; break; case 'sub': $calc = $num1 - $num2; break; } return $calc; } $calc = calculate($num1,$num2); } ? NO 1 : NO 2: total: ``` Upvotes: -1 [selected_answer]<issue_comment>username_2: 1) You have given submit value `+` & `-`. 2) Whenever you submit your form it takes the value `+` & `-` in `POST` value. 3) In switch case you mentioned cases : `addition` & `sub`, where your post value having `+` & `-`. Which not satisfying any cases. 4) Just replace your `+` & `-` with `addition` & `sub` respectively in your form input value like this ``` ``` Upvotes: 1 <issue_comment>username_3: You are passing "+" and "-" into the switch and the case is "addition" and "sub". They are not matching. Upvotes: -1 <issue_comment>username_4: ``` Untitled Document php $num1 = 0; $num2 = 0; $calc = 0; if (isset($\_POST['submit'])) { $num1 = $\_POST['n1']; $num2 = $\_POST['n2']; $calc = calculate($num1, $num2, $\_POST['submit']); } function calculate($num1,$num2,$op) { $calc = 0; switch ($op) { case '+': $calc = $num1 + $num2; break; case '-': $calc = $num1 - $num2; break; } return $calc; } ? NO 1 : NO 2: total: ``` Upvotes: 0
2018/03/21
359
1,320
<issue_start>username_0: I have this demo site made by Wordpress having the [particles.js](https://vincentgarreau.com/particles.js/) script based slide in hero section. But the particles won't appear until I resize the window. After resizing the window particles appears correctly... Any way to fix this?? Thanks in advance!<issue_comment>username_1: Looks there are some errors in the console > > Uncaught TypeError: $ is not a function > at custom.js:1 (index):406 Uncaught TypeError: $ is not a function > at HTMLDocument.onLoad ((index):406) > > > Upvotes: 0 <issue_comment>username_2: Your particles are loading only via `resize`, because in your custom JS you trigger the `resize` manually, but there are JavaScript errors. ``` $(window).load(function(){window.dispatchEvent(new Event('resize'));$(window).resize()}) ``` The jQuery `$` alias hasn't been defined for your `custom.js` file to use, so replace that code with this: ``` jQuery(window).load(function($){window.dispatchEvent(new Event('resize'));$(window).resize()}) ``` same with your `index.php` file, the following JS has the same issue: ``` $(window).trigger('resize'); $(window).resize(); }; ``` You could probably just remove those two lines since you have your `custom.js` file loaded, once you fix it. Upvotes: 2 [selected_answer]
2018/03/21
498
1,561
<issue_start>username_0: i'm trying to display a while loop depending on the parameters in my for loop. for example, my for loop says to loop through 5 times, the data inside while loop should also be displayed 5 times. however, when i tested my code, the data inside while loop only displays once. i'm not sure if i did the iteration correctly. here is a snippet of my nested loop. ``` for($i=0; $i<$count; $i++){ echo "COUNT: ".$i." "; while($data=mysqli_fetch_array($res)) { echo "INSIDE WHILE".$i." "; } } ``` so if my $count = 3, the output of this code is ``` 0 INSIDE WHILE0 INSIDE WHILE0 INSIDE WHILE0 INSIDE WHILE0 INSIDE WHILE0 INSIDE WHILE0 INSIDE WHILE0 1 2 ``` and what i want is for "INSIDE WHILE" to also be displayed between 1 and 2.<issue_comment>username_1: Just add [mysqli\_data\_seek](http://php.net/manual/en/mysqli-result.data-seek.php) after the while loop: ``` for($i=0; $i<$count; $i++){ echo "COUNT: ".$i." "; while($data=mysqli_fetch_array($res)) { echo "INSIDE WHILE".$i." "; } mysqli_data_seek($res, 0); } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` $data=mysqli_fetch_array($res, MYSQLI_ASSOC); for($i=0; $i<$count; $i++){ echo "COUNT: ".$i." "; foreach ($data as $current_data){ echo "INSIDE WHILE".$i." "; echo $current_data[name]; //name is the field name. } } ``` You can move the fetch on top, so you don't have to reset the cursor of the fetch. Upvotes: 0
2018/03/21
998
3,398
<issue_start>username_0: ``` public ArrayList Numbers(int upper, int lower) { ArrayList primeNumbers = new ArrayList(); boolean decider; for(int x = lower; x <= upper; x++) { decider = true; for(int y = 2; y < upper; y ++) { if(x % y == 0) decider = false; } if(decider == true) primeNumbers.add(x); } return primeNumbers; } ``` I wrote the following code to determine if a number is prime. My thinking is if i default a boolean to true and a number divided by another number has a remainder of 0, then the boolean is set to false. ``` for(int x = lower; x <= upper; x++) { decider = true; for(int y = 2; y < upper; y ++) { if(x % y == 0) decider = false; } if(decider == true) primeNumbers.add(x); } ``` For this section here, that is what I attempted to do. Every number between the upper and lower bounds is checked to see if any division has a remainder of 0. If it does, the boolean is false and it is not added to my array. For some reason the array is recieving no numbers between the upper and lower bounds. I cannot spot the problem. Can anyone else? Edit- I edited this post after finding another error because the program went from returning all values to none at all.<issue_comment>username_1: The issue is that you are writing the wrong arguments when scanning through y. Observe: ``` public ArrayList Numbers(int upper, int lower) { ArrayList primeNumbers = new ArrayList(); boolean decider; for(int x = lower; x <= upper; x++) { decider = true; for(int y = 2; y < x; y ++) { if(x % y == 0) decider = false; } if(decider = true) primeNumbers.add(x); } return primeNumbers; } ``` Of course you could improve your code by keeping the upper bound of y as the sqrt(x) + 1 and adding y by increments of 2 instead of 1. You need to check the base case of the number 2 separately. Upvotes: 0 <issue_comment>username_2: Here is the logical problem I see with your code. Your inner `for` loop in `y` will cover most of the time a range which *includes* the value of `x`, since the loop's upper bound is also `upper`. So, in most cases, you would be counting a number divisible only by itself as being not prime, when in fact it is. You should stop that loop before reaching the target `x`. And also, you may break if you find a divisor. ``` for(int x = lower; x <= upper; x++) { decider = true; for (int y = 2; y < x; y ++) { // can probably make this bound even tighter if (x % y == 0) { decider = false; break; } } if (decider) primeNumbers.add(x); } return primeNumbers; ``` Here is a demo showing that the above logic works correctly: [Demo ----](http://rextester.com/XLYF41397) Upvotes: 2 [selected_answer]<issue_comment>username_3: This is where the problem is: ``` for(int x = lower; x <= upper; x++) ``` When you iterate until <=upper, it also divides the number by itself, and messes up your results. Change it to "<" and it'll work; ``` public ArrayList Numbers(int upper, int lower) { ArrayList primeNumbers = new ArrayList(); boolean decider; for(int x = lower; x < upper; x++) { decider = true; for(int y = 2; y < upper; y ++) { if(x % y == 0) decider = false; } if(decider == true) primeNumbers.add(x); } return primeNumbers; } ``` Upvotes: 0
2018/03/21
2,614
8,720
<issue_start>username_0: I have some custom order statuses (made with WooCommerce Order Status Manager). But when I use a custom paid status, the booking status is not updated to "paid". I've cobbled together some code from various references but it results in a fatal error. Or maybe I am missing something where custom statuses are supposed to update the booking paid status without extra code? My code: ``` add_action('woocommerce_order_status_pool-payment-rec','auto_change_booking_status_to_paid', 10, 1); function auto_change_booking_status_to_paid($booking_id) { $booking = new WC_Booking( $booking_id ); $order_id = $booking->get_order_id(); $booking->update_status('paid', 'order_note'); exit; } ``` The error: ``` [20-Mar-2018 23:32:05 UTC] PHP Fatal error: Uncaught Exception: Invalid booking. in /home/ahbc/public_html/wp-content/plugins/woocommerce-bookings/includes/data-stores/class-wc-booking-data-store.php:83 Stack trace: #0 /home/ahbc/public_html/wp-content/plugins/woocommerce/includes/class-wc-data-store.php(149): WC_Booking_Data_Store->read(Object(WC_Booking)) #1 /home/ahbc/public_html/wp-content/plugins/woocommerce-bookings/includes/data-objects/class-wc-booking.php(149): WC_Data_Store->read(Object(WC_Booking)) #2 /home/ahbc/public_html/wp-content/plugins/ahbc-website-tweaks/ahbc-website-tweaks.php(104): WC_Booking->__construct(2223) #3 /home/ahbc/public_html/wp-includes/class-wp-hook.php(288): auto_change_booking_status_to_paid(2223) #4 /home/ahbc/public_html/wp-includes/class-wp-hook.php(310): WP_Hook->apply_filters('', Array) #5 /home/ahbc/public_html/wp-includes/plugin.php(453): WP_Hook->do_action(Array) #6 /home/ahbc/public_html/wp-content/plugins/woocommerce/includes/class-wc-order.php(327): do_action('woocommerce_ord...', 2223, Object(WC_Order)) # in /home/ahbc/public_html/wp-content/plugins/woocommerce-bookings/includes/data-stores/class-wc-booking-data-store.php on line 83 ``` I've also tried this but it seemingly does nothing: ``` function sv_wc_order_statuses_needs_payment( $statuses, $order ) { // use your custom order status slug here $statuses[] = 'pool-payment-rec'; return $statuses; } add_filter( 'woocommerce_valid_order_statuses_for_payment_complete', 'sv_wc_order_statuses_needs_payment', 10, 2 ); ``` My references: [woocommerce booking status changes woocommerce order status](https://stackoverflow.com/questions/41553619/woocommerce-booking-status-changes-woocommerce-order-status) [Change Woocommerce order status for Cash on delivery](https://stackoverflow.com/questions/40421330/change-woocommerce-order-status-for-cash-on-delivery) <https://gist.github.com/bekarice/e922e79bc40eb0729095abc561cfe621> EDIT: Have also tried several variations on the following: ``` add_action( 'woocommerce_order_status_changed', 'auto_change_booking_status_to_paid' ); function auto_change_booking_status_to_paid( $order_id ) { if( ! $order_id ) return; $order = wc_get_order($order_id); $booking = get_wc_booking($booking_id); if( $order->get_status() == 'test' ) // $order_id = $booking->get_order_id(); $booking->update_status('confirmed', 'order_note'); } ```<issue_comment>username_1: Ok here is the solution not needing any custom written queries but using the appropriate methods available in the WooCommerce Booking plugin. ``` add_action('woocommerce_order_status_pool-payment-rec', 'auto_change_booking_status_to_paid', 20, 2 ); function auto_change_booking_status_to_paid( $order_id, $order ) { if( $order->get_status() === 'pool-payment-rec' ) { foreach( $order->get_items() as $item_id => $item ) { $product = wc_get_product($item['product_id']); if( $product->get_type() === 'booking' ) { $booking_ids = WC_Booking_Data_Store::get_booking_ids_from_order_item_id( $item_id ); foreach( $booking_ids as $booking_id ) { $booking = new WC_Booking($booking_id); if( $booking->get_status() != 'paid' ) $booking->update_status( 'paid', 'order_note' ); } } } } } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You need to **get first the Booking ID from the order ID** in this hook. Then you will be able to update the booking status to 'paid' without any error. I have tested with another custom status than your custom one and it works… If I use your code I get the same error than you. In the code below I use a very light query to get the booking ID from the order ID, just as `WC_Order` methods do… The code: ``` // Utility function to get the booking ID from the Order ID function get_The_booking_id( $order_id ){ global $wpdb; return $wpdb->get_var("SELECT ID FROM {$wpdb->prefix}posts WHERE post_parent = '$order_id'"); } // On custom order status change, update booking status to "paid" add_action('woocommerce_order_status_pool-payment-rec', 'auto_change_booking_status_to_paid', 20, 2 ); function auto_change_booking_status_to_paid( $order_id, $order ) { // Get the booking ID from the order ID $booking_id = get_The_booking_id( $order_id ); if( empty($booking_id) ) return; // Exit // Get an instance of the WC_Booking object $booking = new WC_Booking( $booking_id ); // Update status if( $booking->get_status() != 'paid' ) $booking->update_status( 'paid', 'order_note' ); } ``` *Code goes in function.php file of your active child theme (or theme).* Tested and works. Upvotes: 2 <issue_comment>username_3: ``` add_action('init', 'change_order_status'); function change_order_status() { global $wpdb; // Query for orders with a status of "wc-processing" $my_query = "SELECT * FROM wp_wc_order_stats WHERE STATUS='wc-processing'"; $result = $wpdb->get_results($my_query); // Iterate through the results foreach ($result as $order) { $order_id = $order->order_id; $order_date = $order->date_created_gmt; // Get the current date $current_date = date("Y-m-d h:i:s"); // Calculate the difference in days between the order date and the current date $dteStart = new DateTime($order_date); $dteEnd = new DateTime($current_date); $dteDiff = $dteStart->diff($dteEnd); $diff_in_days = $dteDiff->format("%d"); // Compare the difference in days to 1 if ($diff_in_days >= 1) { $order = new WC_Order($order_id); if (!empty($order)) { // Change the order status to "wc-accepted" $order->update_status('wc-accepted'); } } } // Query for orders with a status of "wc-accepted" $my_query = "SELECT * FROM wp_wc_order_stats WHERE STATUS='wc-accepted'"; $result = $wpdb->get_results($my_query); // Iterate through the results foreach ($result as $order) { $order_id = $order->order_id; $order_date = $order->date_created_gmt; // Get the current date $current_date = date("Y-m-d h:i:s"); // Calculate the difference in days between the order date and the current date $dteStart = new DateTime($order_date); $dteEnd = new DateTime($current_date); $dteDiff = $dteStart->diff($dteEnd); $diff_in_days = $dteDiff->format("%d"); // Compare the difference in days to 5 if ($diff_in_days >= 5) { $order = new WC_Order($order_id); if (!empty($order)) { // Change the order status to "wc-preparing" $order->update_status('wc-preparing'); } } } // Query for orders with a status of "wc-preparing" $my_query = "SELECT * FROM wp_wc_order_stats WHERE STATUS='wc-preparing'"; $result = $wpdb->get_results($my_query); // Iterate through the results foreach ($result as $order) { $order_id = $order->order_id; $order_date = $order->date_created_gmt; // Get the current date $current_date = date("Y-m-d h:i:s"); // Calculate the difference in days between the order date and the current date $dteStart = new DateTime($order_date); $dteEnd = new DateTime($current_date); $dteDiff = $dteStart->diff($dteEnd); $diff_in_days = $dteDiff->format("%d"); // Compare the difference in days to 6 if ($diff_in_days >= 6) { $order = new WC_Order($order_id); if (!empty($order)) { // Change the order status to "wc-ready-to-ship" $order->update_status('wc-ready-to-ship'); } } } } ``` Upvotes: 1
2018/03/21
849
3,075
<issue_start>username_0: I am starting to learn about Vue.js. I would like to know how to pass the blade variables into Vue.js? Like ``` return view('user.profile', ['locations' => $allLocations); ``` In which i can manipulate it through Vue.js? Because I am planning on implementing a dynamic dropdown. Actually, there are two dropddowns. So whatever the user selects on the first dropdown, the second dropdown will display only specific options. I already tried to implement it by 1.) hiding an elements an retrieving it through Javascript, or by 2.) using an HTTP AJAX request after page load to initialize the elements but I found this method a little bit messy or somewhat a resource hog. Is there any other implementations aside from what I mentioned above? Thanks!<issue_comment>username_1: i tried using the method to check my subscription and found it handy you:- ``` Vue.component('subscribe', require('./components/Subscribe.vue')); const app = new Vue({ el: '#app' }); ``` Try by going to the link :- [enter link description here](https://laracasts.com/discuss/channels/vue/pass-a-variable-from-blade-to-vue-component) Upvotes: -1 <issue_comment>username_2: You can either implement these two ways to pass down the variables: 1. Pass the variables to view with JSON format ``` var app = <?=json\_encode($locations)?> ``` See also: [Displaying Data](https://laravel.com/docs/5.6/blade#displaying-data) 2. Pass the variables by ajax request **JS snippet** (can place inside Vue mounted / created method) ``` $.ajax({ method: 'GET', url: '/api/locations', success: function (response) { // response.locations } }); ``` **API Route** (routes/api.php) ``` Route::get('locations', 'LocationController@getLocations'); ``` **LocationController** ``` public function getLocations() { ... return response()->json($locations); } ``` Upvotes: 4 [selected_answer]<issue_comment>username_3: You can use **Vue, Vuex, Axios** When use .vue, I think you don't need .blade **With Vue + Laravel:** 1. Create App.vue in assets/js 2. Import App.vue in app.js (folder assets with Laravel 5.6) 3. You would like to pass the blade variables into Vue.js? Use JSON or XML. I love Json. So in Laravel Controller -> return json 4. In App.vue, you can use axios call to API (Use Laravel create 1 API in controller + route...) and You have all variables, you want :) Help it help you. Thanks Upvotes: 0 <issue_comment>username_4: The easiest way to do it is to pass it to your views(where you have the vue component), and receiving it as a prop. ``` return view('user.profile', ['locations' => $allLocations]); ``` and in your view: ``` <your-component :data="{{$allLocations}}> ``` and the vue component, along the line of this: ``` --your HTML here-- export default{ props:['data'], data(){ return{ somethig:this.data.something } } } ``` This should get you started. furthermore, i would suggest you to learn more in the laravel docs, vue docs, laracasts etc. Best of coding to you! Upvotes: 1
2018/03/21
1,587
4,948
<issue_start>username_0: I'm writing in C and have to return a char\* I am trying to replicate the strcpy function. I have the following code ``` int main() { char tmp[100]; char* cpyString; const char* cPtr = &tmp[0]; printf("Enter word:"); fflush(stdin); scanf("%s", &tmp); cpyString = strcpy("Sample", cPtr); printf("new count is %d\n", strlen(cpyString)); } int strlen(char* s) { int count = 0; while(*(s) != 0x00) { count++; s = s+0x01; } return count; } char* strcpy(char* dest, const char* src) { char* retPtr = dest; int i =0; int srcLength = strlen(src); for(i = 0; i< srcLength; i++) { *(dest) = *(src); //at this line program breaks dest = dest + 0x01; src = src + 0x01; } *(dest) = 0x00; //finish with terminating null byte return retPtr; } ``` Q1: How can I assign the dereferenced value at the src to the destination without the program crashing? Q2: If I need to copy the `tmp` string entered into a new string, how would I do that? I can't seem pass `tmp` as the second parameter<issue_comment>username_1: Your program is crashing because you cant modify the pointer to a constant. Please find the corrected code below: ``` char * mstrcpy (char *dest, const char *src) { char *retPtr = dest; int i = 0; int srcLength = strlen (src); for (i = 0; i < srcLength; i++) { *(dest) = *(src); //now doesn't break at this line dest = dest + 1; src = src + 1; } *(dest) = 0x00; //finish with terminating null byte return retPtr; } int main () { //char a = "abc"; // will cause crash char a[] = "abc"; // won't crash char *b = "xyz"; mstrcpy(a,b); //works fine !!!! return 0; } ``` Note that in the main function if you use `char a = "abc"` , then it will cause problem because its a pointer to a constant Upvotes: -1 <issue_comment>username_2: Here ``` cpyString = strcpy("Sample", cPtr); ^^^^^^^ const ``` you have swapped the arguments. The first argument is a string literal ("sample") that you are not allowed to write to. See <https://stackoverflow.com/a/4493156/4386427> Try ``` cpyString = strcpy(cPtr, "Sample"); ``` I'm not sure that the second line is exactly what you want but at least it is legal. Maybe you really want: ``` cpyStringBuffer[100]; cpyString = strcpy(cpyStringBuffer, cPtr); ``` In general your code in `main` is more complicated than needed. Try: ``` int main() { char input[100] = {0}; char dest[100]; printf("Enter word:"); scanf("%99s", input); // notice the 99 to avoid buffer overflow strcpy(dest, input); printf("new count is %d\n", strlen(dest)); return 0; } ``` Upvotes: 3 <issue_comment>username_3: I think you used non initialized destination and literal string pointer. You have to declare your destination as a buffer like ``` char dest[const_size] ``` So ``` char* strcpy(char* dest, const char* src) { char* retPtr = dest; int i =0; int srcLength = strlen(src); for(i = 0; i< srcLength; i++) { *(dest) = *(src); //at this line program breaks dest = dest + 0x01; src = src + 0x01; } *(dest) = 0x00; //finish with terminating null byte return retPtr; } int main() { char *arr="xxxxxx"; char *dest="fffff"; // this won't work because you can not modify const string char *dest_1; // this won't work because it is uninitialized pointer char dest_2[50]; // this will work fine strcpy(x, y); printf("%s",x); //x still the same as point pointer return 0; } ``` Upvotes: 0 <issue_comment>username_4: I guess you might have wanted to code like below. ``` #include int strlen(char\* s); char\* strcpy(char\* dest, char\* src); int main() { char tmp[100]; char cpyString[100]; printf("Enter word:"); fflush(stdin); scanf("%s", &tmp); strcpy(cpyString, tmp); printf("new count is %d\n", strlen(cpyString)); } int strlen(char\* s) { int count = 0; while(\*(s) != 0x00) { count++; s = s+0x01; } return count; } char\* strcpy(char\* dest, char\* src) { char\* retPtr = dest; int i =0; int srcLength = strlen(src); for(i = 0; i< srcLength; i++) { \*(dest) = \*(src); //at this line program breaks dest = dest + 0x01; src = src + 0x01; } \*(dest) = 0x00; //finish with terminating null byte return retPtr; } ``` 1. When you invoke your **strcpy()** in the main function, arguments src and dest are reversed. 2. if you want to use the variable cpyString, then you are supposed to determine which to allocate pieces of memory from either static or dynamic. * In my example, I declared **cpyString** as an array of characters. Which means that the variable will occupy static memory partly. * You can also alternatively allocate bytes of dynamic memory to it by calling **malloc()** or **calloc()** function. Upvotes: 1
2018/03/21
1,488
5,661
<issue_start>username_0: I am developing a library for video/photo processing (add filters like Instagram/Snapchat). So far the core features work very well. However, I am finding the processing of a video (re-encoding an input video) to be hugely frustrating. There seem to be a number of edge cases and device specific issues that prevent the library from working 100% of the time. I would like to know how to select/create a MediaFormat that will work on a device. Currently, I'm setting up the MediaFormat that will be used to encode a video as follows: ``` // assume that "extractor" is a media extractor wrapper, which holds a // reference to the MediaFormat of the input video fun getOutputVideoFormat(): MediaFormat { val mimeType = MediaFormat.MIMETYPE_VIDEO_H263 var width = -1 var height = -1 var frameRate = 30 var bitrate = 10_000_000 val colorFormat = MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface if (extractor.videoFormat.containsKey(MediaFormat.KEY_WIDTH)) { width = extractor.videoFormat.getInteger(MediaFormat.KEY_WIDTH) } if (extractor.videoFormat.containsKey(MediaFormat.KEY_HEIGHT)) { height = extractor.videoFormat.getInteger(MediaFormat.KEY_HEIGHT) } if(extractor.videoFormat.containsKey(MediaFormat.KEY_FRAME_RATE)){ frameRate = extractor.videoFormat.getInteger(MediaFormat.KEY_FRAME_RATE) } if(extractor.videoFormat.containsKey(MediaFormat.KEY_BIT_RATE)){ bitrate = extractor.videoFormat.getInteger(MediaFormat.KEY_BIT_RATE) } val format = MediaFormat.createVideoFormat(mimeType, width, height) format.setInteger(MediaFormat.KEY_COLOR_FORMAT, colorFormat) format.setInteger(MediaFormat.KEY_BIT_RATE, bitrate) format.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate) format.setInteger(MediaFormat.KEY_CAPTURE_RATE, frameRate) // prevent crash on some Samsung devices // http://stackoverflow.com/questions/21284874/illegal-state-exception-when-calling-mediacodec-configure?answertab=votes#tab-top format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, width * height) format.setInteger(MediaFormat.KEY_MAX_WIDTH, width) format.setInteger(MediaFormat.KEY_MAX_HEIGHT, height) format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 0) return format } ``` So far this works on all major devices that I have tested with, but there are some devices like the Samsung A5 that have been reported to fail silently using this format, and simply create corrupted output videos using an input video that works correctly on all other devices. How can I tell if a MediaFormat will actually succeed on a given device? --- The only logs I have from the Samsung A5 device indicate that when the MediaCodec sends through the "INFO\_OUTPUT\_FORMAT\_CHANGED" signal, the following media format is returned: ``` csd-1=java.nio.ByteArrayBuffer[position=0,limit=8,capacity=8], mime=video/avc, frame-rate=30, remained_resource=2549760, height=480, width=480, max_capacity=3010560, what=1869968451, bitrate=10000000, csd-0=java.nio.ByteArrayBuffer[position=0,limit=17,capacity=17] ``` This format seems invalid to me, given the fact the input video has a resolution of 1280x720<issue_comment>username_1: You can use the [MediaCodecList](https://developer.android.com/reference/android/media/MediaCodecList.html) API to query and list what codecs are available and what formats they support. Also for your code example, are you really using `MediaFormat.MIMETYPE_VIDEO_H263` or is that a typo? That's a very old format. (Not old in the "well supported and reliable" way but in the "old, untested and possibly broken" way.) The safest thing would be to use `MediaFormat.MIMETYPE_VIDEO_AVC` which is the one that gets the most testing, both by the Android compatibility testsuite and by third party applications. Upvotes: 2 <issue_comment>username_2: It turns out that my problem had nothing to do with the video codecs available on the device. The problem didn't come from MediaCodec or MediaFormat, but from MediaMuxer. I was processing video and audio by reading them out through a MediaExtractor, pushing that through a MediaCodec configured for decoding, processing that data, and then pushing processed data through a MediaCodec configured for encoding. Then I was pushing the encoded data to a MediaMuxer (and eventually writing it to a file). This is very similar to the `DecodeEditEncodeTest` found on `https://bigflake.com/mediacodec/`. I was only doing processing on the video track, but I was using a similar decode/encode method to take the audio from the input file and put it into the output file. I initially thought the problem was device specific, but it turns out that the issue was actually with the input. The video that was causing the issue with processing was very short - less than 2 seconds long. Decoding and re-encoding the audio was not working correctly with such a short video, and the MediaMuxer was not registering any audio frames. This is what was causing the final output to be corrupted. I found the following CTS test: `https://android.googlesource.com/platform/cts/+/jb-mr2-release/tests/tests/media/src/android/media/cts/MediaMuxerTest.java`, and its `cloneMediaUsingMuxer` method, which shows how to copy audio directly from a MediaExtractor into a MediaMuxer. I modified my processing method to (continue to) use the decode/edit/encode method for video, and to use the passthrough method demonstrated by the CTS test for writing audio. This solved the issue, and I was able to process the short video correctly. Upvotes: 1 [selected_answer]
2018/03/21
414
1,592
<issue_start>username_0: I have created new jenkins job, in which I want to execute a Jenkins file from a particular folder. I have created one folder in my project named `pipelinescript`, in which I have placed my `Jenkinsfile`. But when I am executing that job the file has not been detected. In script path I have also give `/pipelinescript/Jenkinsfile`, but it is not working.<issue_comment>username_1: Instead of mentioning /pipelinescript/Jenkinsfile please use the entire absolute path. It will resolve the issue. Upvotes: 0 <issue_comment>username_2: First of all jenkins whichever files are picking up, all are workspace related. If you refer a path with no `/` in front of it, then it will load it from `workspace` only. To load a jenkins file from a custom location, you have to do like this by adding this line to the script. ``` load "//Jenkinsfile" ``` For more info, please [refer this](https://stackoverflow.com/a/40441425/5003256). Upvotes: 0 <issue_comment>username_3: A few things to consider: 1. Is your new job a freestyle job? If so, you may have some trouble calling the Jenkinsfile at all. You should be using a Pipeline job to use the Jenkinsfile approach. 2. When you define your Pipeline job, the path the to Jenkinsfile is relative to the workspace. So to reference the Jenkinsfile in the subdirectory, you would need to configure the path like 'pipelinescript/Jenkinsfile'. Here's a screenshot of the Pipeline job configuration form: [![enter image description here](https://i.stack.imgur.com/WV9H7.png)](https://i.stack.imgur.com/WV9H7.png) Upvotes: 1
2018/03/21
812
2,861
<issue_start>username_0: I was trying to make a binary tree with the help of `struct` as given below: ``` struct BinaryTree { var value: Int var left: BinaryTree var right: BinaryTree } ``` But I am getting error `error: value type 'BinaryTree' cannot have a stored property that recursively contains it`. Here struct is value type so I can't create same struct object in it. How can I achieve this???<issue_comment>username_1: You can use class for this structure, structs do not allow to reference itself. ``` class BinaryTree { var value: Int? var left: BinaryTree? var right: BinaryTree? init(value: Int) { self.value = value } } let node = BinaryTree.init(value: 1) node.left = BinaryTree(value: 2) ``` > > The reason for this compile error is memory allocation: Value types > are fixed structures and they occupy a fixed space in memory, in > registers and the stack, depending on its size. That space is > pre-determined by the type and must be known at compile time. > > > <https://medium.com/@leandromperez/bidirectional-associations-using-value-types-in-swift-548840734047> Upvotes: 2 <issue_comment>username_2: `Structs` are value types that's the reason why recursion won't work. You have to use `Class` instead, because they are reference types. But as you said you want a solution with value types. Here is a solution for you using `enum` Enums with `indirect` cases are allocated on the heap and thus contain only pointers to the recursive children. Without pointer indirection, the type would otherwise be infinitely large, since it contains infinitely many times. ``` enum BinaryTree { case empty indirect case node(value: Element, left: BinaryTree, right: BinaryTree) } extension BinaryTree { func addNode(\_ newValue: Element) -> BinaryTree { switch self { case .empty: return BinaryTree.node(value: newValue, left: .empty, right: .empty) case let .node(value, left, right): if newValue < value { return BinaryTree.node(value: value, left: left.addNode(newValue), right: right) } else { return BinaryTree.node(value: value, left: left, right: right.addNode(newValue)) } } } } let tree = BinaryTree.empty.addNode(2) ``` **OR** You simply just use `Class` You can use class for this structure, structs do not allow to reference itself. ``` class BinaryTree { var value: Int var left: BinaryTree? var right: BinaryTree? init(value: Int) { self.value = value } } ``` I hope this will work for you. Upvotes: 4 [selected_answer]<issue_comment>username_3: To construct the tree using value types, you need to add protocols into the mix. Here is an example: ``` protocol Node { var value: Int {get} } struct Tree: Node { var value: Int var left: Node var right: Node } struct Leaf: Node { var value: Int } ``` Upvotes: 0
2018/03/21
863
2,918
<issue_start>username_0: I have done the dynamic inputs now my problem is getting the values of each inputs but its a multiple inputs? how can I achieve this. here is the jsfiddle. ``` perRow() { return this.state.values.map((el,i) => | **Total hours:** 0:00 **Total pay:** $0.00 Remove employee | Monday | | | | 0:00 | $0.00 | ) } ``` <https://jsfiddle.net/zd208m1a/2/?utm_source=website&utm_medium=embed&utm_campaign=zd208m1a><issue_comment>username_1: First of all, create `constructor` and we will create an onChange function so we need to bind it inside the constructor ``` constructor(props){ super(props); this.state = { username: '', password: '', }; this.onChange = this.onChange.bind(this); } ``` Then we need to create `onChange` function it will handle by the name ``` onChange(e){ this.setState({ [e.target.name] : e.target.value }); } ``` Finally, call the onChange function with a name attribute, you need to define the input name in the state to avoid any troubles. ``` | | ``` 2\_ **Alternative way instead of binding the `onChange` function in the constructor you can use an anonymous arrow function like so** ``` onChange = (e) => { this.setState({ [e.target.name] : e.target.value }); } ``` 3\_ **Another Alternative way, you can bind it like so** ``` onChange(e){ this.setState({ [e.target.name] : e.target.value }); } ``` 4\_ **Another Alternative way with passing data** ``` onChange(e,data){ console.log(data); // result is "something" this.setState({ [e.target.name] : e.target.value }); } this.onChange(e, 'something')} /> ``` Upvotes: 2 <issue_comment>username_2: Yes you can get your input values like `this.state.values.join(', ')` since you got your input values in state values as as array ``` handleChange(i, event) { let values = [...this.state.values]; values[i] = event.target.value; this.setState({ values }); console.log(this.state.values) } ``` Checck the below example , this will help you for sure [Demo done by mayankshukla](https://jsfiddle.net/mayankshukla5031/ezdxg224/) Upvotes: 1 [selected_answer]<issue_comment>username_3: Here are the implement using react hook, hope this helps, too. ``` const [value, setValue] = useState([]) const handleChange = (i, event) => { let values = [...value]; values[i] = e.target.value; setValue(values) console.log(values) } ``` Step to get value inside multiple input text : 1. Create state with empty element array. 2. When onChange is runiing... 3. Copy `value` state into variable mutable. Example in es6 `let values = [...value]` 4. When `e.target.value` is getting done 5. Based on index total, `value` is saved inside `values` variable 6. Then, save final `values` inside `value` using `setValue` Upvotes: 0
2018/03/21
689
2,784
<issue_start>username_0: I want to be able to display the ViewBag on view on button click event, this is my code: ``` [HttpPost] public ActionResult SpecificWorkflowReport(Report2ListViewModel wf) { var getSpRecord = db.Mworkflow().ToList(); var getRecord = (from u in getSpRecord select new Report2ListViewModel { WorkFlowType = u.WorkFlowType, WorkflowInstanceId = u.WorkflowInst, WorkFlowDescription = u.WorkFlowDesc, }).ToList(); ViewBag.WorkflowType = wf.WorkFlowType; ViewBag.WorkflowInstanceId = wf.WorkflowInst; ViewBag.WorkFlowDescription = wf.WorkFlowDesc var data = Newtonsoft.Json.JsonConvert.SerializeObject(getRecord); return Json(data); } ``` i have tried this: ``` Worflow Type: @ViewBag.WorkflowType Workflow Instance Id: @ViewBag.WorkflowInstanceId Workflow Description: @ViewBag.WorkFlowDescription ``` My Javascript and json Call:<issue_comment>username_1: @UwakPeter your code snippets is ok, but you are returning Json, may be you are calling this method via javascript, so the view is not updating, you need to **reload the view**, by the submit button. If you are using javascript, you can pass your data list and model data as anonymous object, so that you don't need to use ViewBag. in client side by ajax success function you can grab them (**WorkflowType, WorkflowInstanceId, WorkFlowDescription, Result**) ``` [HttpPost] public ActionResult SpecificWorkflowReport(Report2ListViewModel wf) { var getSpRecord = db.Mworkflow().ToList(); var getRecord = (from u in getSpRecord select new Report2ListViewModel { WorkFlowType = u.WorkFlowType, WorkflowInstanceId = u.WorkflowInst, WorkFlowDescription = u.WorkFlowDesc, }).ToList(); var data = Newtonsoft.Json.JsonConvert.SerializeObject(getRecord); return Json(new{ WorkflowType = wf.WorkFlowType, WorkflowInstanceId = wf.WorkflowInst, WorkFlowDescription = wf.WorkFlowDesc, Result= data }, JsonRequestBehaviour.AllowGet); } ``` **JS** ``` $.ajax({ url: url, type: "POST", data: str, cache: false, dataType: "json", success: function (_data) { var workflowType=_data.WorkflowType; //set it to HTML control var workflowInstanceId =_data.WorkflowInstanceId; var workFlowDescription = _data.WorkFlowDescription; $('#reportTable').dataTable({ data: _data.Result }); } )}; ``` Upvotes: 0 <issue_comment>username_2: Try this, ``` @{ Layout = null; ProjectMVC.Models.Record record= (ProjectMVC.Models.Record)ViewBag.Recorddetails; } ... Worflow Type: @record.WorkflowType ``` Upvotes: -1
2018/03/21
799
2,762
<issue_start>username_0: I have been trying to develop screen mentioned below: For that I have created below component: ``` import React, {Component} from 'react'; import {View, Text, StyleSheet, ImageBackground, Image} from 'react-native'; import Balance from './Balance.js' class AccountHeader extends React.Component{ render(){ return( My Account <NAME> +14155552671 ); } } const styles = StyleSheet.create({ container: { backgroundColor:'red', opacity: 0.6 }, overlay: { backgroundColor:'transparent', opacity: 0.6 }, avatarStyle: { width:100, height: 100, marginTop: 10, borderRadius: 50, alignSelf: 'center', }, textStyle: { marginTop: 10, fontSize: 18, color: "#FFFFFF", fontWeight: 'bold', alignSelf: 'center', }, balanceContainer:{ padding:10, } }); export default AccountHeader; ``` Now here are two issues: 1. Changing the opacity of `ImageBackground` also change the opacity of its children 2. Not able to change the color of opacity Any help appreciated! > > **Design screen:** > > > [![enter image description here](https://i.stack.imgur.com/YxKd2.png)](https://i.stack.imgur.com/YxKd2.png) > > **Developed Screen** > > > [![enter image description here](https://i.stack.imgur.com/k8HvU.png)](https://i.stack.imgur.com/k8HvU.png)<issue_comment>username_1: Try changing the container's style to ``` container: { backgroundColor: 'rgba(255,0,0,.6)' }, ``` Upvotes: 3 <issue_comment>username_2: Use this code, it's working, I just made a minor change ``` import React, {Component} from 'react'; import {View, Text, StyleSheet, ImageBackground, Image,Dimensions} from 'react-native'; class AccountHeader extends React.Component{ render(){ return( My Account <NAME> +14155552671 ); } } const styles = StyleSheet.create({ container: { }, overlay: { backgroundColor:'rgba(255,0,0,0.5)', }, avatarStyle: { width:100, height: 100, marginTop: 10, borderRadius: 50, alignSelf: 'center', }, textStyle: { marginTop: 10, fontSize: 18, color: "#FFFFFF", fontWeight: 'bold', alignSelf: 'center', }, balanceContainer:{ padding:10, } }); export default AccountHeader; ``` Upvotes: 6 [selected_answer]<issue_comment>username_3: Try this : ``` ``` it works Upvotes: 6 <issue_comment>username_4: For me worked just applying some opacity to the ImageBackground component and at the same time a background color like this: ``` ``` Upvotes: 4
2018/03/21
628
1,867
<issue_start>username_0: There's a whole bunch of answers to the similar questions here on Stack and in Google, but all of those seems irrelevant. I'm afraid that problem is in the question but still do need a solution nonetheless. The code: ``` print(type(comment)) print(comment) ``` Results in: ``` \u041d\u0435 \u0443\u043a\u0430\u0437\u0430\u043d\u043e ``` How do I convert this to plain text? upd. ``` print(comment[0]) ``` Returns ``` \ ```<issue_comment>username_1: Two answers in one: If you really want to get it parsed quickly, you can do something like this: ``` import ast s = ast.literal_eval('"' + comment.replace('"', '\\"') + '"') ``` `s` will contain what you want - it will process the string, as if you wrote it in your code this way. (this is safer than actual eval, because it will not allow comment to execute any functions - but you can still break it by including a `\"` in the comment) To process it correctly though, you'd have to write a proper lexer/parser to analyse it character by character. But really, if you ended up with that string, something is wrong somewhere before. You ended up with a string with escaped unicode instead of actual contents. If it comes from somewhere in your application, the best way would be to trace back to where it originates and ensure you don't end up in this situation in the first place. Upvotes: 1 <issue_comment>username_2: If you started with a `str` in Python 3, you need to encode to bytes then decode using the `unicode-escape` codec to translate those literal escape codes to Unicode: ``` comment = r'\u041d\u0435 \u0443\u043a\u0430\u0437\u0430\u043d\u043e' print(type(comment)) print(comment) print(comment.encode('ascii').decode('unicode-escape')) ``` Output: ``` \u041d\u0435 \u0443\u043a\u0430\u0437\u0430\u043d\u043e Не указано ``` Upvotes: 1 [selected_answer]
2018/03/21
947
3,624
<issue_start>username_0: I am trying to execute a python function on AWS Lambda. In my function I am trying to import the mysql.connector module. But an error is throwing up : > > errorMessage": "No module named 'mysql.connector'" > > > I had written my python code initially in my EC2 Instance. I installed mysql-connector there in my python file directory using pip. ``` pip install mysql-connector -t /path/to/file/dir ``` I uploaded the zip file of the only the file and not any folder containing the file.<issue_comment>username_1: Lambda is just like an EC2 instance with only python installed. You need to include all the packages that are required to run the python code with the deployment package itself. None of the packages will be pre-installed when you run the code. Upvotes: 1 <issue_comment>username_2: Pattern that I have been using to deploy Python libs to lambda is following Firstly, prior to packaging lambda function install all of the requirements into `$SOURCE_ROOT/lib` folder ``` pip install -r requirements.txt -t ./lib ``` Secondly, dd automatic import of this folder in your lambda entrypoint (that is lambda handler) ``` import os import sys # if running in lambda if 'LAMBDA_TASK_ROOT' in os.environ: sys.path.append(f"{os.environ['LAMBDA_TASK_ROOT']}/lib") # this will render all of your packages placed as subdirs available sys.path.append(os.path.dirname(os.path.realpath(__file__))) ``` Extending `sys.path` with your own packaged path is the crucial for this to work. **Note on native compiled extensions** Note that if you are packaging any natively compiled extensions, their compilation should be done on linux-compatible O/S, ideally on EC2 instance created from Amazon Linux AMIs Lambda is running from (currently `amzn-ami-hvm-2017.03.1.20170812-x86_64-gp2`, but up to date information can be always obtained from [Amazon Official Docs](https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html). According to my experience, extensions built from official Docker python container worked on lambda, without need to compile on actual EC2 instance created from AMIs, but there is no guarantee as offical docs state that > > If you are using any native binaries in your code, make sure they are compiled in this environment. Note that only 64-bit binaries are supported on AWS Lambda. > > > **MySQL Connector** Quick look at [MySQL connector for Python](https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html) gives impression that by default package will use native Python implementation, so no C extension is loaded Upvotes: 3 <issue_comment>username_3: There are two ways to pack python dependencies with Lambda. 1. Pack it with the function itself. To do this you just go to the root folder of your function, and install dependencies in that folder itself, not into any other folder. ``` $ pip install -t . ``` Then zip that folder from root and upload, your zip should look something like this: ``` . ├── lambda_function.py ├── pymysql │ └── ... └── PyMySQL-0.9.3.dist-info └── ... ``` 2. Second method is a standard that I always follow,I never ship libraries or external packages with my lambda function, I always create Layers. > > A layer is a ZIP archive that contains libraries, a custom runtime, or > other dependencies. With layers, you can use libraries in your > function without needing to include them in your deployment package. > > > Learn More about Lambda Layers in the [docs](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) Upvotes: 0
2018/03/21
1,042
3,771
<issue_start>username_0: I am currently stuck on trying to solve this issue I am having. I am trying to use egrep to find either 5 digit consecutive numbers or 9 digit consecutive numbers. Right now I am getting only the 5 digit number that appears on one line and nothing else after that. I currently have... ``` egrep '^[[:digit:]]{5} | [[:digit:]]{9}$' file.txt ``` For example if my file.txt had ``` 123456789 24 12345 642 94363 ``` What will be found is **12345** 642 How can I make it so that it will check every line and see the other 5 and 9 digit numbers? **Edit:Using parentheses around the expression finds...** 1234**56789** 4 **12345** 642<issue_comment>username_1: Lambda is just like an EC2 instance with only python installed. You need to include all the packages that are required to run the python code with the deployment package itself. None of the packages will be pre-installed when you run the code. Upvotes: 1 <issue_comment>username_2: Pattern that I have been using to deploy Python libs to lambda is following Firstly, prior to packaging lambda function install all of the requirements into `$SOURCE_ROOT/lib` folder ``` pip install -r requirements.txt -t ./lib ``` Secondly, dd automatic import of this folder in your lambda entrypoint (that is lambda handler) ``` import os import sys # if running in lambda if 'LAMBDA_TASK_ROOT' in os.environ: sys.path.append(f"{os.environ['LAMBDA_TASK_ROOT']}/lib") # this will render all of your packages placed as subdirs available sys.path.append(os.path.dirname(os.path.realpath(__file__))) ``` Extending `sys.path` with your own packaged path is the crucial for this to work. **Note on native compiled extensions** Note that if you are packaging any natively compiled extensions, their compilation should be done on linux-compatible O/S, ideally on EC2 instance created from Amazon Linux AMIs Lambda is running from (currently `amzn-ami-hvm-2017.03.1.20170812-x86_64-gp2`, but up to date information can be always obtained from [Amazon Official Docs](https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html). According to my experience, extensions built from official Docker python container worked on lambda, without need to compile on actual EC2 instance created from AMIs, but there is no guarantee as offical docs state that > > If you are using any native binaries in your code, make sure they are compiled in this environment. Note that only 64-bit binaries are supported on AWS Lambda. > > > **MySQL Connector** Quick look at [MySQL connector for Python](https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html) gives impression that by default package will use native Python implementation, so no C extension is loaded Upvotes: 3 <issue_comment>username_3: There are two ways to pack python dependencies with Lambda. 1. Pack it with the function itself. To do this you just go to the root folder of your function, and install dependencies in that folder itself, not into any other folder. ``` $ pip install -t . ``` Then zip that folder from root and upload, your zip should look something like this: ``` . ├── lambda_function.py ├── pymysql │ └── ... └── PyMySQL-0.9.3.dist-info └── ... ``` 2. Second method is a standard that I always follow,I never ship libraries or external packages with my lambda function, I always create Layers. > > A layer is a ZIP archive that contains libraries, a custom runtime, or > other dependencies. With layers, you can use libraries in your > function without needing to include them in your deployment package. > > > Learn More about Lambda Layers in the [docs](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) Upvotes: 0
2018/03/21
611
2,232
<issue_start>username_0: I have this backup code that I want to execute monthly, I am familiar with using the job or maintenance plan in sql server management studio but I would like to code it instead of using the sql server job or maintenance plan. .aspx ``` ``` aspx.cs ``` protected void Button111_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString()); string backupDIR = "C:\backup"; if (!System.IO.Directory.Exists(backupDIR)) { System.IO.Directory.CreateDirectory(backupDIR); } try { con.Open(); sqlcmd = new SqlCommand("backup database iporma to disk= '" + backupDIR + "\" + DateTime.Now.ToString("ddMMyy_HHss") + ".Bak'", con); sqlcmd.ExecuteNonQuery(); con.Close(); lblError.Text = "Completed"; } catch (Exception ex) { lblError.Text = "Error" + ex.ToString(); } } ``` please go easy on me I'm still new to this.<issue_comment>username_1: Create windows service or windows scheduled task to execute this code.You will find good articles on Google explaining how to create windows services. Upvotes: 1 <issue_comment>username_2: Your code is correct little change in query: you take month then you should use only MMM or mMm: ``` sqlcmd = new SqlCommand("backup database iporma to disk= '" + backupDIR + "\" + DateTime.Now.ToString("MMM") + ".Bak'", con); ``` Upvotes: -1 <issue_comment>username_2: ``` protected void Button111_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ToString()); string month=System.DateTime.Now.toString("dd-MMM");// every month it has to be changed.. string backupDIR = "C:\backup"; if(month!="") { if (!System.IO.Directory.Exists(backupDIR)) { System.IO.Directory.CreateDirectory(backupDIR); } try { con.Open(); sqlcmd = new SqlCommand("backup database iporma to disk= '" + backupDIR + "\" + "Month.ToString()" + ".Bak'", con); sqlcmd.ExecuteNonQuery(); con.Close(); lblError.Text = "Completed"; } catch (Exception ex) { lblError.Text = "Error" + ex.ToString(); } } } ``` Upvotes: -1
2018/03/21
1,683
5,290
<issue_start>username_0: This code works ``` max_elem :: (Ord a) => [a] -> a max_elem [x] = x max_elem [] = error "No elements" max_elem (x:xs) |x > max_elem xs = x |otherwise = max_elem xs ``` I want to have it so it returns Nothing if their are no elements and Just x for the maximum element I tried the following ``` max_elem :: (Ord a) => [a] -> Maybe a max_elem [x] = Just x max_elem [] = Nothing max_elem (x:xs) |x > max_elem xs = Just x |otherwise = max_elem xs ``` I got the following error. Recommendations to fix this please. ``` • Couldn't match expected type ‘a’ with actual type ‘Maybe a’ ‘a’ is a rigid type variable bound by the type signature for: max_elem :: forall a. Ord a => [a] -> Maybe a at :208:13 • In the second argument of ‘(>)’, namely ‘max\_elem xs’ In the expression: x > max\_elem xs In a stmt of a pattern guard for an equation for ‘max\_elem’: x > max\_elem xs • Relevant bindings include xs :: [a] (bound at :211:13) x :: a (bound at :211:11) max\_elem :: [a] -> Maybe a (bound at :209:1) ```<issue_comment>username_1: The error message was clear enough to solve your problem. ``` |x > max_elem xs = Just x ``` The problem is that you compare `x` which is `a` with `max_elem` which is `Maybe a`. That's why you got such error message. You can solve the problem with this code below. ``` max_elem :: (Ord a) => [a] -> Maybe a max_elem [] = Nothing max_elem (x:xs) = case (max_elem xs) of Nothing -> Just x Just y -> if x > y then Just x else Just y ``` Upvotes: 2 <issue_comment>username_2: You get your error because of this line: `x > max_elem xs`. `max_elem xs` has type `Maybe a` where `a` is an element of a list. It has type `a`. You can't compare values of different types. `a` and `Maybe a` are different types. See Haskell equality table: * <https://htmlpreview.github.io/?https://github.com/quchen/articles/blob/master/haskell-equality-table.html> Replace `==` operator with `>` and you will get the same table. You can solve problem in your code by replacing `x > max_elem xs` with `Just x > max_elem xs`. Does it make sense to you? As you can see, `Maybe a` data type has `Ord a => Ord (Maybe a)` instance which is actually really handy! So you can implement your function in even more concise way to utilize this `Ord` instance: ``` max_elem :: Ord a => [a] -> Maybe a max_elem = foldr max Nothing . map Just ``` Though, this probably won't be the most efficient solution if you care about performance. Upvotes: 2 <issue_comment>username_3: We can generalize this task and work with all `Foldable`s. Here we thus use the [**`foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b`**](http://hackage.haskell.org/package/base-4.11.0.0/docs/Prelude.html#v:foldr) function that folds a certain `Foldable` structure. We can do this with the function `max . Just`, and as initial element `Nothing`: ``` max_elem :: (Ord a, Foldable f) => f a -> Maybe a max_elem = foldr (max . Just) Nothing ``` Note that this works since Haskell defines `Maybe a` to be an instance of `Ord`, given `a` is an instance of `Ord`, and it implements it in a way that `Nothing` is smaller than any `Just` element. This makes the above definition perhaps a bit "unsafe" (in the sense that we here rely on the fact that from the moment we have a `Just x`, the `max` will select such `Just x` over a `Nothing`). When we would use `min`, this would not work (not without using some tricks). We can also use pattern guards and thus solve the case where the list is empty in a different way, like: ``` max_elem :: Ord a => [a] -> Maybe a max_elem [] = Nothing max_elem l = Just (maximum l) ``` Upvotes: 1 <issue_comment>username_4: The problem is `x > max_elem xs`; `max_elem xs` is `Maybe a`, not `a`, meaning that it might return `Nothing`. However, you do know that it will only return `Nothing` if `xs` is empty, but you know `xs` won't be empty because you matched the case where it would `using [x]`. You can take advantage of this fact by writing a "non-empty" maximum: ``` max_elem_ne :: Ord a => a -> [a] -> a max_elem_ne m [] = m max_elem_ne m (x:xs) | m > x = max_elem m xs | otherwise = max_elem x xs ``` Or, alternatively, using `max`: ``` max_elem_ne :: Ord a => a -> [a] -> a max_elem_ne m [] = m max_elem_ne m (x:xs) = max_elem (max m x) xs ``` You can think of the first argument as the maximum value seen "so far", and the second list argument as the list of other candidates. In this last form, you might have noticed that `max_elem_ne` is actually a just left fold, so you could even just write: ``` max_elem_ne :: Ord a => a -> [a] -> a max_elem_ne = foldl' max ``` Now, with `max_elem_ne`, you can write your original `max_elem`: Then you can write: ``` max_elem :: Ord a => [a] -> Maybe a max_elem [] = Nothing max_elem (x:xs) = Just (max_elem_ne x xs) ``` So you don't have to do any extraneous checks (like you would if you redundantly pattern matched on results), and the whole thing is type-safe. You can also use the `uncons :: [a] -> Maybe (a,[a])` utility function with `fmap` and `uncurry` to write: ``` max_elem :: Ord a => [a] -> Maybe a max_elem = fmap (uncurry max_elem_ne) . uncons ``` Upvotes: 0
2018/03/21
508
2,343
<issue_start>username_0: I was trying to search the following case using BoolQueryBuilder in elasticsearch ``` select * from students where (name = "XXX" and rollno = 1) or (name = "YYY" and rollno = 2) ``` I have to build query builder for it. Can anyone suggest me the BoolQueryBuilder to build the query. ElasticSearch 6.1.2 Any help really appreciated.<issue_comment>username_1: Here it is: ``` GET students/_search { "query": { "bool": { "should": [ { "bool": { "must": [ { "term": { "name": { "value": "XXX" } } }, { "term": { "rollno": { "value": "1" } } } ] } }, { "bool": { "must": [ { "term": { "name": { "value": "YYY" } } }, { "term": { "rollno": { "value": "2" } } } ] } } ] }}} ``` Basically, bool compound query can apply into deeper level. The rest is about how you use in case of `OR` or `AND` operation. In this case, `should` map to `OR`, and `must` map to `AND`. Cheers, Upvotes: 1 [selected_answer]<issue_comment>username_2: This is java api to build the BooleanQueryBuilder condition ``` BoolQueryBuilder booleanQuery = QueryBuilders.boolQuery(); booleanQuery.must(QueryBuilders.termQuery("name", "XXX")); booleanQuery.must(QueryBuilders.termQuery("rollno", 1)); BoolQueryBuilder booleanQuery2 = QueryBuilders.boolQuery(); booleanQuery2.must(QueryBuilders.termQuery("name", "YYY")); booleanQuery2.must(QueryBuilders.termQuery("rollno", 2)); BoolQueryBuilder boolQueryBuilder3 = QueryBuilders.boolQuery(); boolQueryBuilder3.should(booleanQuery2); boolQueryBuilder3.should(booleanQuery); ``` Upvotes: 1
2018/03/21
650
2,689
<issue_start>username_0: for example: i have many documents like this: ``` email status <EMAIL> open <EMAIL> click <EMAIL> open <EMAIL> open ``` i will query all documents with unique status value :"open", due to the record "<EMAIL>" contains "click" status, so "<EMAIL>" don't expect! i tried this below,but not my expect: ``` { "aggs": { "hard_bounce_count": { "filter": { "term": { "actionStatus": "open" } }, "aggs": { "email_count": { "value_count": { "field": "email" } } } ``` my expect response like this: ``` <EMAIL> open <EMAIL> open ``` How can i do this,thanks..<issue_comment>username_1: Here it is: ``` GET students/_search { "query": { "bool": { "should": [ { "bool": { "must": [ { "term": { "name": { "value": "XXX" } } }, { "term": { "rollno": { "value": "1" } } } ] } }, { "bool": { "must": [ { "term": { "name": { "value": "YYY" } } }, { "term": { "rollno": { "value": "2" } } } ] } } ] }}} ``` Basically, bool compound query can apply into deeper level. The rest is about how you use in case of `OR` or `AND` operation. In this case, `should` map to `OR`, and `must` map to `AND`. Cheers, Upvotes: 1 [selected_answer]<issue_comment>username_2: This is java api to build the BooleanQueryBuilder condition ``` BoolQueryBuilder booleanQuery = QueryBuilders.boolQuery(); booleanQuery.must(QueryBuilders.termQuery("name", "XXX")); booleanQuery.must(QueryBuilders.termQuery("rollno", 1)); BoolQueryBuilder booleanQuery2 = QueryBuilders.boolQuery(); booleanQuery2.must(QueryBuilders.termQuery("name", "YYY")); booleanQuery2.must(QueryBuilders.termQuery("rollno", 2)); BoolQueryBuilder boolQueryBuilder3 = QueryBuilders.boolQuery(); boolQueryBuilder3.should(booleanQuery2); boolQueryBuilder3.should(booleanQuery); ``` Upvotes: 1
2018/03/21
685
2,465
<issue_start>username_0: My salesforce res apis were working fine until. When suddenly I started getting authentication errors. **retry your request.** **Salesforce.Common.AuthenticationClient.d\_\_1.MoveNext()**. salesforce informed that it would use from now TLS .1.2. How can I enforce my asp.net core 2.0 to use TLS 1.2 in Startup.cs. below is my code for login. ``` private async Task GetValidateAuthentication() { RestApiSetting data = new RestApiSetting(Configuration); var auth = new AuthenticationClient(); var url = data.IsSandBoxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase) ? "https://test.salesforce.com/services/oauth2/token" : "https://login.salesforce.com/services/oauth2/token"; try { //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; await auth.UsernamePasswordAsync(data.ConsumerKey, data.ConsumerSecret, data.Username, data.Password, url); return auth; } catch (Exception ex) { throw new Exception(ex.ToString()); } } ```<issue_comment>username_1: .net framework prior to version 4.7 makes outbound connections using TLS 1.0 by default. You can upgrade to a newer version to fix the problem, or alternatively, you can set the default and fallback versions for outbound calls using the ServicePointManager, or passing the setting into the HttpClient if you have the source code for the library. Add the following somewhere early in your pipeline, such as your `startup.cs` or `global.asax`: ``` ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; ``` You can find a good description on the topic here: <https://social.msdn.microsoft.com/Forums/en-US/8db54c83-1329-423b-8d55-4dc6a25fe826/how-to-make-a-web-client-app-use-tls-12?forum=csharpgeneral> And if you want to specify it only for some requests instead of application-wide, then you can customize the `HttpClientHandler` of your `HttpClient`: ``` var handler = new HttpClientHandler { SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls }; HttpClient client = new HttpClient(handler); ... ``` Upvotes: 4 <issue_comment>username_2: According to the following <https://github.com/dotnet/corefx/issues/29452> > > In .NET Core, ServicePointManager affects only HttpWebRequest. It does not affect HttpClient. You should be able to use HttpClientHandler.ServerCertificateValidationCallback to achieve the same. > > > Upvotes: 3
2018/03/21
513
1,842
<issue_start>username_0: HTML code ``` threshold is required. threshold value should be number. maximum three digits. ``` ts code ``` this.editThreshold = new FormGroup({ threshold: new FormControl('', [Validators.required, Validators.pattern(/[0-9]/),Validators.maxLength(3)]), }); ``` I want to restrict pattern to only accepting the number and from range 1 - 3<issue_comment>username_1: .net framework prior to version 4.7 makes outbound connections using TLS 1.0 by default. You can upgrade to a newer version to fix the problem, or alternatively, you can set the default and fallback versions for outbound calls using the ServicePointManager, or passing the setting into the HttpClient if you have the source code for the library. Add the following somewhere early in your pipeline, such as your `startup.cs` or `global.asax`: ``` ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; ``` You can find a good description on the topic here: <https://social.msdn.microsoft.com/Forums/en-US/8db54c83-1329-423b-8d55-4dc6a25fe826/how-to-make-a-web-client-app-use-tls-12?forum=csharpgeneral> And if you want to specify it only for some requests instead of application-wide, then you can customize the `HttpClientHandler` of your `HttpClient`: ``` var handler = new HttpClientHandler { SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls }; HttpClient client = new HttpClient(handler); ... ``` Upvotes: 4 <issue_comment>username_2: According to the following <https://github.com/dotnet/corefx/issues/29452> > > In .NET Core, ServicePointManager affects only HttpWebRequest. It does not affect HttpClient. You should be able to use HttpClientHandler.ServerCertificateValidationCallback to achieve the same. > > > Upvotes: 3
2018/03/21
1,239
4,121
<issue_start>username_0: I've been working on a program for my Computer Programming class and I'm having a little trouble. Truthfully, I'm on the verge of insanity... Its a calendar program and the part I'm having trouble with is the Calendar object in java. Here is my code for one of methods: ``` public static void calendarGet(){ String md = getInput("What date would you like to look at?(mm/dd)"); int slash = md.indexOf('/'); MDFromDate(md); cal.set(cal.MONTH, MONTH - 1); cal.set(cal.DATE, DAY); TARGET_DAY = DAY; MAX_DAY = cal.getActualMaximum(cal.DAY_OF_MONTH); WEEKS_IN_MONTH = MAX_DAY / 7; System.out.println(cal.MONTH + 1); System.out.println(cal.DAY_OF_MONTH); System.out.println(cal.getTime()); drawMonth(cal.MONTH); } ``` And the output for this is: ``` What date would you like to look at?(mm/dd)12/12 3 5 Wed Dec 12 22:47:32 PST 2018 ``` As you can see, if I use getTime(); it returns the right month and day but cal.MONTH and cal.DAY\_OF\_MONTH do not. Also, when I use the debugger and look in cal, none of the variables had changed. I'm incredibly confused, I would appreciate some help! :D EDIT: ``` public static String getInput(String prompt){ System.out.print(prompt); Scanner inScan = new Scanner(System.in); return inScan.nextLine(); } public static void MDFromDate(String md){ Scanner getMD = new Scanner(md).useDelimiter("/"); MONTH = getMD.nextInt(); DAY = getMD.nextInt(); } ```<issue_comment>username_1: So... ``` System.out.println(cal.MONTH + 1); System.out.println(cal.DAY_OF_MONTH); ``` is printing the constant values assigned to `Calendar.MONTH` and `Calendar.DAY_OF_MONTH`, this are not the values contained within the `Calendar` instance, they are simply values you can use to set/get values of the `Calendar` So, if instead we use `Calendar#get`, for example... ``` Calendar cal = Calendar.getInstance(); int month = 12; int day = 12; cal.set(cal.MONTH, month - 1); cal.set(cal.DATE, day); System.out.println(cal.get(Calendar.MONTH)); System.out.println(cal.get(Calendar.DATE)); ``` It will print... ``` 11 12 ``` But wait, why `11`, because the months are zero indexed (ie January is `0`) Part of the confusion is down to the fact that you're not using the [standard coding conventions for the Java Language](http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html), which states variable names which all all uppercase (`MONTH`/`DAY`) are constants, which they aren't in your code And, yes, as I'm sure some is bound to point out, you shouldn't be using `Calendar` but instead the newer `java.time` API, but if your teacher wants you to use it, who are we to contradict them :/ Upvotes: 1 <issue_comment>username_2: In [a very well-explained answer](https://stackoverflow.com/a/49400535/5772882) username_1 asks: > > And, yes, as I'm sure some is bound to point out, you shouldn't be > using `Calendar` but instead the newer `java.time` API, but if your > teacher wants you to use it, who are we to contradict them :/ > > > I am taking the chance. If only for other readers that are not under the same restrictions. Teachers are different. When I was teaching, I certainly appreciated whenever students found a different solution from what I had imagined. You know your teacher better, so I hope you know what is right in your situation, I certainly don’t. ``` private static final DateTimeFormatter monthDayFormatter = DateTimeFormatter.ofPattern("M/d"); public static void calendarGet(){ String md = getInput("What date would you like to look at?(mm/dd)"); LocalDate date = MonthDay.parse(md, monthDayFormatter) .atYear(Year.now(ZoneId.of("America/Los_Angeles")).getValue()); int targetDay = date.getDayOfMonth(); int maxDay = date.lengthOfMonth(); System.out.println(date.getMonth()); System.out.println(date.getDayOfMonth()); } ``` When I entered `04/05`, this printed ``` APRIL 5 ``` IMHO the code using `java.time` is clearer to read and what should be taught in schools. Upvotes: 0
2018/03/21
683
2,187
<issue_start>username_0: what I wanted is to add another condition using case statement or something. I tried: ``` SELECT * FROM tblcust WHERE cust_id = :p_cust_id CASE WHEN :p_first_name IS NOT NULL THEN AND first_name = :p_first_name WHEN :p_last_name IS NOT NULL THEN AND last_name = :p_last_name WHEN :p_first_name IS NULL AND :p_last_name IS NULL THEN NULL END; ```<issue_comment>username_1: I am not sure what you want logically , but you can do case inside a case like ``` With a as ( Select 1 id , NULL col1 union all Select 2,10 union all Select 3,Null ) Select * from a where id =1 OR Case When col1 is not null then id=2 End ``` Upvotes: 0 <issue_comment>username_2: You may not be able to use a `CASE` expression here to represent your logic, but it can certainly be reworded: ``` SELECT * FROM tblcust WHERE cust_id = :p_cust_id AND ((:p_first_name IS NOT NULL AND first_name = :p_first_name) OR (:p_last_name IS NOT NULL AND last_name = :p_last_name) OR (:p_first_name IS NULL AND :p_last_name IS NULL)); ``` But this is ugly, and we might able to use a `COALESCE` trick here to make it simpler: ``` SELECT * FROM tblcust WHERE cust_id = :p_cust_id AND (COALESCE(:p_first_name, first_name || ' ') = first_name) OR COALESCE(:p_last_name, last_name || ' ') = last_name) OR (:p_first_name IS NULL AND :p_last_name IS NULL)); ``` The reason your `CASE` expression is structured incorrectly is because you are making it generate logical *expressions*, when it is only allowed to generate *values*. But, in this case, we don't even need a `CASE` expression to handle your logic. Upvotes: 3 [selected_answer]<issue_comment>username_3: To make theses "mutually exclusive" sets of conditons use parentheses plus OR ``` SELECT * FROM tblcust WHERE (:p_first_name IS NOT NULL AND first_name = :p_first_name) OR (:p_last_name IS NOT NULL AND last_name = :p_last_name) OR (:p_FIRST_name IS NULL AND :p_last_name IS NULL AND cust_id = :p_cust_id) ``` If there are still more conditions to add the be careful to contain all the sets within an "catch all" pair of parentheses Upvotes: 0
2018/03/21
1,112
3,040
<issue_start>username_0: I got the following XML: ``` xml version="1.0" encoding="UTF-8"? 782 true 1.0 true thr6UhEw5bER6Cjt8uKOCg Briefpapier false thr6UhEw5bER6Cjt8uRUiA Briefpapier false true thr6UhEw5bER6Cjt8uSxgA Blanco false thr6UhEw5bER6Cjt8uSCCg Blanco false thr6UhEw5bER6Cjt8uKOCg Briefpapier false thr6UhEw5bER6Cjt8uUH-A Briefpapier false 00000782\_000001.rtf `thr6UhEw5bER6Cjt8uKOCg` false RTF 00000782\_000002.rtf `thr6UhEw5bER6Cjt8uRUiA` false RTF 00000782\_000003.rtf `thr6UhEw5bER6Cjt8uSCCg` false RTF 00000782\_000004.rtf `thr6UhEw5bER6Cjt8uSxgA` false RTF 00000782\_000005.rtf `thr6UhEw5bER6Cjt8uUH-A` false RTF 29 75 58 ``` and the following XSLT: ``` ``` Somehow I cant dynamicly select the "naam" node. when i do a specific xpath select example ``` //document/naam[../code='thr6UhEw5bER6Cjt8uSCCg']/text() ``` It works fine but as soon as I replace it with `current()/document` or `./document` it doenst retrieve anything anymore... when I use a static xpath it just works fine and retrieve the information for every foreach loop. How can I make the xpath dynamicly inside de xslt? Currently trying to figure out xslt although I cant really get it to work properly...<issue_comment>username_1: I am not sure what you want logically , but you can do case inside a case like ``` With a as ( Select 1 id , NULL col1 union all Select 2,10 union all Select 3,Null ) Select * from a where id =1 OR Case When col1 is not null then id=2 End ``` Upvotes: 0 <issue_comment>username_2: You may not be able to use a `CASE` expression here to represent your logic, but it can certainly be reworded: ``` SELECT * FROM tblcust WHERE cust_id = :p_cust_id AND ((:p_first_name IS NOT NULL AND first_name = :p_first_name) OR (:p_last_name IS NOT NULL AND last_name = :p_last_name) OR (:p_first_name IS NULL AND :p_last_name IS NULL)); ``` But this is ugly, and we might able to use a `COALESCE` trick here to make it simpler: ``` SELECT * FROM tblcust WHERE cust_id = :p_cust_id AND (COALESCE(:p_first_name, first_name || ' ') = first_name) OR COALESCE(:p_last_name, last_name || ' ') = last_name) OR (:p_first_name IS NULL AND :p_last_name IS NULL)); ``` The reason your `CASE` expression is structured incorrectly is because you are making it generate logical *expressions*, when it is only allowed to generate *values*. But, in this case, we don't even need a `CASE` expression to handle your logic. Upvotes: 3 [selected_answer]<issue_comment>username_3: To make theses "mutually exclusive" sets of conditons use parentheses plus OR ``` SELECT * FROM tblcust WHERE (:p_first_name IS NOT NULL AND first_name = :p_first_name) OR (:p_last_name IS NOT NULL AND last_name = :p_last_name) OR (:p_FIRST_name IS NULL AND :p_last_name IS NULL AND cust_id = :p_cust_id) ``` If there are still more conditions to add the be careful to contain all the sets within an "catch all" pair of parentheses Upvotes: 0
2018/03/21
401
1,440
<issue_start>username_0: I have a situation like there will be one hidden div ``` ``` I have hidden the div using hide() function using jquery ``` $('#div_id').hide(); ``` Now my problem is how can I add values to above input field and display the values when I show the div. ``` $(document).ready(function(){ $("select#po_pos").change(function() { var stateId = $("#po_pos option:selected").val(); $('#input_id').val($('#').val() + stateId); } }); ``` can anyone help on this please??thanks<issue_comment>username_1: You were missing the input box id. This may help you ```js $(document).ready(function(){ $("#po_pos").change(function() { var stateId = $("#po_pos option:selected").val(); $('#input_id').val($('#input_id').val() + stateId); }); $("#btn1").click(function() { $('#div_id').show(); }); $("#btn2").click(function() { $('#div_id').hide(); }); }); ``` ```html Volvo Saab Mercedes Audi ``` Upvotes: 1 <issue_comment>username_2: I think you are looking for this : ``` $('#div\_id').hide(); $(document).ready(function(){ $("select#po\_pos").change(function() { var stateId = $("#po\_pos option:selected").val(); var inputVal = $('#'+stateId).val(); $('#input\_id').val(inputVal); $('#div\_id').show(); } }); ``` Upvotes: 0
2018/03/21
370
1,344
<issue_start>username_0: [![](https://i.stack.imgur.com/5eLrF.png)](https://i.stack.imgur.com/5eLrF.png) I was looking for framework which provides left sidemenu that is open either by clicking left arrow button or by swiping in right direction and once swiping begun homeview gets blurred(using gaussian blur effect) as shown in image. It will be great help if anyone can suggest framework supportive with objective c which provide expected behaviour?<issue_comment>username_1: You were missing the input box id. This may help you ```js $(document).ready(function(){ $("#po_pos").change(function() { var stateId = $("#po_pos option:selected").val(); $('#input_id').val($('#input_id').val() + stateId); }); $("#btn1").click(function() { $('#div_id').show(); }); $("#btn2").click(function() { $('#div_id').hide(); }); }); ``` ```html Volvo Saab Mercedes Audi ``` Upvotes: 1 <issue_comment>username_2: I think you are looking for this : ``` $('#div\_id').hide(); $(document).ready(function(){ $("select#po\_pos").change(function() { var stateId = $("#po\_pos option:selected").val(); var inputVal = $('#'+stateId).val(); $('#input\_id').val(inputVal); $('#div\_id').show(); } }); ``` Upvotes: 0
2018/03/21
1,196
3,772
<issue_start>username_0: How can I read the following JSON structure to spark dataframe using PySpark? My JSON structure ``` {"results":[{"a":1,"b":2,"c":"name"},{"a":2,"b":5,"c":"foo"}]} ``` I have tried with : ``` df = spark.read.json('simple.json'); ``` I want the output a,b,c as columns and values as respective rows. Thanks.<issue_comment>username_1: **Json string variables** If you have *json strings as variables* then you can do ``` simple_json = '{"results":[{"a":1,"b":2,"c":"name"},{"a":2,"b":5,"c":"foo"}]}' rddjson = sc.parallelize([simple_json]) df = sqlContext.read.json(rddjson) from pyspark.sql import functions as F df.select(F.explode(df.results).alias('results')).select('results.*').show(truncate=False) ``` which will give you ``` +---+---+----+ |a |b |c | +---+---+----+ |1 |2 |name| |2 |5 |foo | +---+---+----+ ``` **Json strings as separate lines in a file (sparkContext and sqlContext)** If you have *json strings as separate lines in a file* then you can *read it using sparkContext into rdd[string]* as above and the rest of the process is same as above ``` rddjson = sc.textFile('/home/anahcolus/IdeaProjects/pythonSpark/test.csv') df = sqlContext.read.json(rddjson) df.select(F.explode(df['results']).alias('results')).select('results.*').show(truncate=False) ``` **Json strings as separate lines in a file (sqlContext only)** If you have *json strings as separate lines in a file* then you can just use `sqlContext` only. But the process is complex as *you have to create schema* for it ``` df = sqlContext.read.text('path to the file') from pyspark.sql import functions as F from pyspark.sql import types as T df = df.select(F.from_json(df.value, T.StructType([T.StructField('results', T.ArrayType(T.StructType([T.StructField('a', T.IntegerType()), T.StructField('b', T.IntegerType()), T.StructField('c', T.StringType())])))])).alias('results')) df.select(F.explode(df['results.results']).alias('results')).select('results.*').show(truncate=False) ``` which should give you same as above result I hope the answer is helpful Upvotes: 5 [selected_answer]<issue_comment>username_2: ``` !pip install findspark !pip install pyspark import findspark import pyspark findspark.init() sc = pyspark.SparkContext.getOrCreate() from pyspark.sql import SparkSession spark = SparkSession.builder.appName('abc').getOrCreate() ``` Let's Generate our own JSON data This way we don't have to access the file system yet. ``` stringJSONRDD = sc.parallelize((""" { "id": "123", "name": "Katie", "age": 19, "eyeColor": "brown" }""", """{ "id": "234", "name": "Michael", "age": 22, "eyeColor": "green" }""", """{ "id": "345", "name": "Simone", "age": 23, "eyeColor": "blue" }""") ) ``` Then Create DataFrame ``` swimmersJSON = spark.read.json(stringJSONRDD) ``` Create temporary table ``` swimmersJSON.createOrReplaceTempView("swimmersJSON") ``` Hope this helps you. For complete code you can refer to this [GitHub repository](https://github.com/drabastomek/learningPySpark/blob/master/Chapter03/LearningPySpark_Chapter03.ipynb). Upvotes: 0 <issue_comment>username_3: ``` from pyspark.sql import SparkSession from pyspark.sql.functions import col from pyspark.sql.functions import explode spark = SparkSession.builder.getOrCreate() sc = spark.sparkContext json_data = '{"results":[{"a":1,"b":2,"c":"name"},{"a":2,"b":5,"c":"foo"}]}' json_rdd = sc.parallelize([json_data]) df = spark.read.json(json_rdd) df =df.withColumn("results", explode(df.results)).select( col("results.a").alias("a"), col("results.b").alias("b"), col("results.c").alias("c") ) df.show() ``` Upvotes: 0
2018/03/21
782
2,821
<issue_start>username_0: In my application,the home page fetches the Json response from my rest API.Then I add the products into the cart array.Initially,my store values are.. ``` const DEFAULT_STATE_TRENDING = { data:{}, specialoffdata:[], banner:[], offerstitle:[], cart:[], cartcount:0, isFetching:false, dataFetched:false, error:false, } ``` After i added the products the cart array and cart count becomes.. ``` cart:[{...},{...}], cartcount:cart.length ``` Now, i close my app.After reloading the app,the cart array becomes empty.How to persist the store values here?<issue_comment>username_1: The best way to persist the store values is by using this awesome library. [**Redux Persist**](https://github.com/rt2zz/redux-persist) It contains various `methods` and `levels` of `persistance`, with the ease of use. `Installation` and `basic usage` is well documented on their [github docs](https://github.com/rt2zz/redux-persist). Upvotes: 4 [selected_answer]<issue_comment>username_2: The simplest approach is to use AsyncStorage ``` let response = await AsyncStorage.getItem('count'); //Read AsyncStorage.setItem('count', this.state.count + ''); ``` This way, you can access the 'count' in every component. --- The most modern way is to use react's new context api, you define the context provider and consume it everywhere: ``` const ThemeContext = React.createContext('light') class ThemeProvider extends React.Component { state = {theme: 'light'} render() { return ( //<--- 'light' is exposed here {this.props.children} ) } } class App extends React.Component { render() { return ( {item => {item}} //<-- you consume the value ('light') here ) } } ``` Either way, it is much lighter and easier than Redux or MobX. Upvotes: 1 <issue_comment>username_3: I used the AsyncStorage.In this way i persisted my store state values even after reloading,closing and opening app. configureStore.js: --- ``` import {createStore, applyMiddleware,compose} from 'redux'; import thunk from 'redux-thunk'; import { autoRehydrate } from 'redux-persist'; import allReducers from './reducers'; import { AsyncStorage } from 'react-native'; const middleware = [ thunk, ]; export default function configureStore() { let store= createStore( allReducers, {}, compose(applyMiddleware(...middleware),autoRehydrate()) ); console.log("Created store is"+store);debugger return store; } ``` App.js: --- ``` const store = configureStore(); export default class App extends Component { componentDidMount() { console.log("App.js started and its store value is"+store);debugger SplashScreen.hide() persistStore( store, { storage : AsyncStorage, whitelist : ['trending'] } ); } render() { return ( ); } } ``` Upvotes: 0
2018/03/21
613
2,360
<issue_start>username_0: I want to make a `POST` on button click by adding an event listener to it, but with ajax I can make the call but I do not have any data or success, error criteria for the same. one way I found was using form submit event, but I guess it is not the right way to do it, I should be making a POST call on button click. ``` {{[loc-signin-google]}} ``` If I do something like this in my `onclick` function, its not working as desired, neither am getting any error. ``` $.ajax({ url: '/connect/google', type: 'POST' }); ``` And after this, I have my code to open the new window. How can I make a post call and mark its target as the `google-auth-window` which I have defined in my code? or using the form is the correct way?<issue_comment>username_1: The default behaviour of a button of type `submit` in a form is to submit it, so you have to prevent the default behaviour first by using `event.preventDefault()` and followed by what you desire to do on click of the button (ex: validations etc.). In your case you can call the function that makes the AJAX call (`makeAjaxRequest`). Your code will look something like this: ``` $("#signin-login-google-button").click(function(event){ event.preventDefault(); makeAjaxRequest(); }); function makeAjaxRequest() { $.ajax({ url: '/connect/google', type: 'POST', success: function(data){ //code to open in new window comes here } }); } ``` On success of the ajax call you can write code to open it in a new window. You can refer to this [answer](https://stackoverflow.com/a/27030686/4445511) for the same. Upvotes: 3 <issue_comment>username_2: I guess your problem is not about how to handle `Ajax` calls, rather how to integrate google user login with user and not doing by submitting the form but should be done async. (Correct me I am wrong :) ) I think the if you follow google documentation [here](https://developers.google.com/identity/sign-in/web/sign-in), you might see that google already provides a library in (`platform.js`) for handling it via ajax and also opens it in a seperate form. With it you can have a google login button with only ``` ``` and it opens a window for login and return backs to your callback url provided in you configuration on Google APIs. Let me know if you get stuck anywhere. :) Upvotes: 0
2018/03/21
524
1,532
<issue_start>username_0: The below code is to populate a drop down select option with json data provided. BUt it is not populating. **this is not populating a dropdrop with json data in the fucntion** ``` var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.values ={ names :["Emil", "Tobias", "Linus"] places :["hyd","tnd","sec"] } }); This example shows how to fill a dropdown list using the ng-options directive. ```<issue_comment>username_1: Your JSON should be corrected as, ``` { "names": [ "Emil", "Tobias", "Linus" ], "places": [ "hyd", "tnd", "sec" ] }; ``` **DEMO** ```js var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.values= { "names": [ "Emil", "Tobias", "Linus" ], "places": [ "hyd", "tnd", "sec" ] }; }); ``` ```html ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: try using this method to populate your fields:- ``` Select Account Select Account var app = angular.module('main', []); app.controller('myCtrl', function($scope) { $scope.values =[ { names :1, name: "Email"}, { names :2, name: "Tobias"}, { names :3, name: "Linus"}, {place :1, p:"hyd"}, {place :2, p:"tnd"}, {place :3, p:"sec"} ]; // $scope.places=[ // {place :1, p:"hyd"}, // {place :2, p:"tnd"}, // {place :3, p:"sec"} // ]; $scope.selectedname=$scope.values[0].names; $scope.selectedname=$scope.values[0].place; }); ``` Upvotes: 0
2018/03/21
878
2,651
<issue_start>username_0: This is a sample markup ``` | Group Name | Object Name | | --- | --- | | Animal | Snake | | Animal | Dog | | Place | Antarctica | | Fruit | Mango | ``` **Need to do:** Find the number of times each class is used for a particular "Group Name". For example: > > Animal : {c1 = 1, c2 = 1, c3 = 0} > > > Place : {c1 = 0, c2 = 1, c3 = 0} > > > Fruit : {c1 = 0, c2 = 0, c3 = 1} > > > I plan on creating a column chart with the data. **Progress:** I am able to get the groups and find the number of times each class is used(not group-wise) separately. However, I can't think of a way to merge both in a way so that I can get the desired result. ``` var numc1=0, numc2=0, numc3=0; var groupNames = []; columnTh = $("table th:contains('Group Name')"); columnIndex = columnTh.index() + 1; $('table tr td:nth-child(' + columnIndex + ')').each(function(){ var groupName = $(this).text() if(groupNames.indexOf(groupName)=== -1) { groupNames.push(groupName); // Gets all the group names } switch($(this).closest('tr').attr("class")){ //Gets the number of tr with specified classes. case "c1": // gets the number of ALL occurances of class values instead of Group numc1++; break; case "c2": numc2++; break; case "c3": numc3++; break; } }); ``` **Problems**: 1. Get the number of classes according to the "group name". 2. Store all the information in an object.<issue_comment>username_1: Your JSON should be corrected as, ``` { "names": [ "Emil", "Tobias", "Linus" ], "places": [ "hyd", "tnd", "sec" ] }; ``` **DEMO** ```js var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.values= { "names": [ "Emil", "Tobias", "Linus" ], "places": [ "hyd", "tnd", "sec" ] }; }); ``` ```html ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: try using this method to populate your fields:- ``` Select Account Select Account var app = angular.module('main', []); app.controller('myCtrl', function($scope) { $scope.values =[ { names :1, name: "Email"}, { names :2, name: "Tobias"}, { names :3, name: "Linus"}, {place :1, p:"hyd"}, {place :2, p:"tnd"}, {place :3, p:"sec"} ]; // $scope.places=[ // {place :1, p:"hyd"}, // {place :2, p:"tnd"}, // {place :3, p:"sec"} // ]; $scope.selectedname=$scope.values[0].names; $scope.selectedname=$scope.values[0].place; }); ``` Upvotes: 0
2018/03/21
2,257
7,335
<issue_start>username_0: I have function where i can save new specification to my database while I'm creating products, It is working just fine but it has one issue: > > It has to refresh my page, while i filled my product data some of > them will be lost during this refresh. > > > So I thought it would be better if I use ajax function for it, here is my codes: `blade` ``` {{ Form::open(array('route' => 'addnewsupspecinprodcreat')) }} {{ Form::label('specification_id', 'Parent Specification') }} @foreach($specifications as $specification) {{ $specification->title }} @endforeach {{ Form::label('title', 'Name') }} {{ Form::text('title', null, array('class' => 'form-control')) }} {{ Form::label('status_id', 'Include filters?') }} @foreach($statuses as $status) {{ $status->title }} @endforeach Save {{ Form::close() }} ``` `controller` ``` public function addnewsupspecinprodcreat(Request $req) { Subspecification::create([ 'title' => $req->title, 'specification_id' => $req->specification_id, 'status_id' => $req->status_id, ]); Session::flash('success', 'Your Sub-specification saved successfully.'); return redirect()->back(); } ``` `route` ``` Route::post('/addnewsupspecinprodcreat', 'ProductController@addnewsupspecinprodcreat')->name('addnewsupspecinprodcreat'); ``` Question ======== What should I change to convert my function to Ajax? UPDATE ====== I changed my data like: `blade form` ``` {{Form::open()}} {{ Form::label('spac_id', 'Parent Specification') }} @foreach($specifications as $specification) {{ $specification->title }} @endforeach {{ Form::label('spectitle', 'Name') }} {{ Form::text('spectitle', null, array('id' => 'spectitle', 'class' => 'form-control')) }} {{ Form::label('stat_id', 'Include filters?') }} @foreach($statuses as $status) {{ $status->title }} @endforeach Save {{Form::close()}} ``` added `script` ``` $( document ).ready( function() { $("#modalsave").click(function(e){ e.preventDefault(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="\_token"]').attr('content') } }); $.ajax({ type: "post", url: "{{ url('admin/addnewsupspecinprodcreat') }}", dataType: 'json', data: { title: $("#spectitle").val(), specification\_id: $("i#spac\_id").val(), status\_id: $("#stat\_id").val(), }, success: function (data) { console.log(data); }, error: function (data) { console.log('Error:', data); } }); }); }); ``` changed `function` to: ``` public function addnewsupspecinprodcreat(Request $req) { $add = Subspecification::create([ 'title' => $req->spectitle, 'specification_id' => $req->spac_id, 'status_id' => $req->stat_id, ]); if($add){ Session::flash('success', 'Your Sub-specification saved successfully.'); }else{ Session::flash('danger', 'Your Sub-specification saved successfully.'); } } ``` Issue: I'm getting `419` error on my Ajax which is related to my `token` code but interesting part is that I have ``` $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') } }); ``` in my script, really not sure why i get `419` error. any idea? `my error` ``` Error: {…} ​ abort: function abort() ​ always: function always() ​ complete: function add() ​ done: function add() ​ error: function add() ​ fail: function add() ​ getAllResponseHeaders: function getAllResponseHeaders() ​ getResponseHeader: function getResponseHeader() ​ overrideMimeType: function overrideMimeType() ​ pipe: function then() ​ progress: function add() ​ promise: function promise() ​ readyState: 4 ​ responseJSON: Object { exception: "Symfony\\Component\\HttpKernel\\Exception\\HttpException", file: "C:\\laragon\\www\\xxxxx\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Exceptions\\Handler.php", line: 203, … } ​ responseText: "{\n \"message\": \"\",\n \"exception\": \"Symfony\\\\Component\\\\HttpKernel\\\\Exception\\\\HttpException\",\n \"file\": \"C:\\\\laragon\\\\www\\\\xxxxxx\\\\vendor\\\\laravel\\\\framework\\\\src\\\\Illuminate\\\\Foundation\\\\Exceptions\\\\Handler.php\",\n \"line\": 203,\n \"trace\": [\n {\n \"file\": \"C:\\\\laragon\\\\www\\\\xxxxxx\\\\vendor\\\\laravel\\\\framework\\\\src\\\\Illuminate\\\\Foundation\\\\Exceptions\\\\Handler.php\",\n \"line\": 175,\n \"function\": \"prepareException\",\n \"class\": \"Illuminate\\\\Foundation\\\\Exceptions\\\\Handler\",\n \"type\": \"->\"\n },\n {\n \"file\": \"C:\\\\laragon\\\\www\\\\xxxxxx\\\\app\\\\Exceptions\\\\Handler.php\",\n \"line\": 51,\n \"function\": \"render\",\n \"class\": \"Illuminate\\\\Foundation\\\\Exceptions\\\\Handler\",\n \"type\": \"->\"\n },\n {\n \"file\": \"C:\\\\laragon\\\\www\\\\xxxxxx\\\\vendor\\\\laravel\\\\framework\\\\src\\\\Illuminate\\\\Routing\\\\Pipeline.php\",\n \"line\": 83,\n \"functi…" ​ setRequestHeader: function setRequestHeader() ​ state: function state() ​ status: 419 ​ statusCode: function statusCode() ​ statusText: "unknown status" ​ success: function add() ​ then: function then() ​ __proto__: Object { … } ``` UPDATE 2 ======== I have changed my `script` to code below: ``` $( document ).ready( function() { $("#modalsave").click(function(e){ e.preventDefault(); $.ajax({ type: "post", url: "{{ url('admin/addnewsupspecinprodcreat') }}", dataType: 'json', data: { \_token: $('input[name=\_token]').val(), title: $('input[name=spectitle]').val(), specification\_id: $('input[name=spac\_id]').val(), status\_id: $('input[name=stat\_id]').val(), }, success: function (data) { console.log(data); }, error: function (data) { console.log('Error:', data); } }); }); }); ``` Now I'm getting error `500` in my network, here is `response` of it: > > message SQLSTATE[23000]: Integrity constraint violation: 1048 Column > 'title' cannot be null (SQL: insert into `subspecifications` (`title`, > `specification_id`, `status_id`, `updated_at`, `created_at`) values (, > , , 2018-03-22 15:48:21, 2018-03-22 15:48:21)) > > ><issue_comment>username_1: Your JSON should be corrected as, ``` { "names": [ "Emil", "Tobias", "Linus" ], "places": [ "hyd", "tnd", "sec" ] }; ``` **DEMO** ```js var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.values= { "names": [ "Emil", "Tobias", "Linus" ], "places": [ "hyd", "tnd", "sec" ] }; }); ``` ```html ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: try using this method to populate your fields:- ``` Select Account Select Account var app = angular.module('main', []); app.controller('myCtrl', function($scope) { $scope.values =[ { names :1, name: "Email"}, { names :2, name: "Tobias"}, { names :3, name: "Linus"}, {place :1, p:"hyd"}, {place :2, p:"tnd"}, {place :3, p:"sec"} ]; // $scope.places=[ // {place :1, p:"hyd"}, // {place :2, p:"tnd"}, // {place :3, p:"sec"} // ]; $scope.selectedname=$scope.values[0].names; $scope.selectedname=$scope.values[0].place; }); ``` Upvotes: 0
2018/03/21
513
1,158
<issue_start>username_0: Initial matrix is `A = [ [1 2 3; 4 5 6; 7 8 9]`. Every row is to be replicated 3 times such that the output matrix is ``` B = [1 2 3;1 2 3;1 2 3;4 5 6; 4 5 6; 4 5 6; 7 8 9; 7 8 9; 7 8 9] B = replicate(permute(A,[3 2 1]),3,1) ```<issue_comment>username_1: you mean like that? ``` kron(A,ones(3,1)) ``` ans = ``` 1 2 3 1 2 3 1 2 3 4 5 6 4 5 6 4 5 6 7 8 9 7 8 9 7 8 9 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Since **R2015a**, there is a dedicated function for this: [**`repelem`**](https://de.mathworks.com/help/matlab/ref/repelem.html). ``` A = [1 2 3; 4 5 6; 7 8 9] B = repelem(A,3,1) ``` --- ``` B = 1 2 3 1 2 3 1 2 3 4 5 6 4 5 6 4 5 6 7 8 9 7 8 9 7 8 9 ``` Upvotes: 2 <issue_comment>username_3: Or just indexing: ``` A = [1 2 3; 4 5 6; 7 8 9]; % original matrix m = 3; % row repetition factor n = 1; % column repetition factor B = A(ceil(1/m:1/m:size(A,1)), ceil(1/n:1/n:size(A,2))); ``` Upvotes: 1
2018/03/21
426
1,137
<issue_start>username_0: I am making a website which has a forum where people can fill up data and also upload their images (5mb at max). I want to know that where should these images should be stored (like on the server or some cloud)<issue_comment>username_1: you mean like that? ``` kron(A,ones(3,1)) ``` ans = ``` 1 2 3 1 2 3 1 2 3 4 5 6 4 5 6 4 5 6 7 8 9 7 8 9 7 8 9 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Since **R2015a**, there is a dedicated function for this: [**`repelem`**](https://de.mathworks.com/help/matlab/ref/repelem.html). ``` A = [1 2 3; 4 5 6; 7 8 9] B = repelem(A,3,1) ``` --- ``` B = 1 2 3 1 2 3 1 2 3 4 5 6 4 5 6 4 5 6 7 8 9 7 8 9 7 8 9 ``` Upvotes: 2 <issue_comment>username_3: Or just indexing: ``` A = [1 2 3; 4 5 6; 7 8 9]; % original matrix m = 3; % row repetition factor n = 1; % column repetition factor B = A(ceil(1/m:1/m:size(A,1)), ceil(1/n:1/n:size(A,2))); ``` Upvotes: 1
2018/03/21
1,155
2,650
<issue_start>username_0: I want to set box shadow inside a box or div but only at right and left sides. I want something like this below. Please help me. [![enter image description here](https://i.stack.imgur.com/fbF20.jpg)](https://i.stack.imgur.com/fbF20.jpg)<issue_comment>username_1: You can create one inner div and one outer div. Then you need to set the shadow separately for both divs. ```css .outer, .inner { width: 200px; height: 50px; display: inlin-block; } .outer { -webkit-box-shadow: inset 10px 0px 23px -9px rgba(0,0,0,0.75); -moz-box-shadow: inset 10px 0px 23px -9px rgba(0,0,0,0.75); box-shadow: inset 10px 0px 23px -9px rgba(0,0,0,0.75); } .inner { -webkit-box-shadow: inset -10px 0px 23px -9px rgba(0,0,0,0.75); -moz-box-shadow: inset -10px 0px 23px -9px rgba(0,0,0,0.75); box-shadow: inset -10px 0px 23px -9px rgba(0,0,0,0.75); } ``` ```html ``` Or you can use also one div, with 2 inset parameters: ```css .outer { width: 200px; height: 50px; display: inlin-block; -webkit-box-shadow: inset 10px 0px 23px -9px rgba(0,0,0,0.75), inset -10px 0px 23px -9px rgba(0,0,0,0.75); -moz-box-shadow: inset 10px 0px 23px -9px rgba(0,0,0,0.75), inset -10px 0px 23px -9px rgba(0,0,0,0.75); box-shadow: inset 5px 0 8px -5px #000,inset -5px 0 8px -5px #000, inset -10px 0px 23px -9px rgba(0,0,0,0.75); } ``` ```html ``` Upvotes: 2 <issue_comment>username_2: To get it to appear only on the sides you need to essentially have two different sets: `box-shadow:inset 5px 0 8px -5px #000,inset -5px 0 8px -5px #000;` Upvotes: 3 <issue_comment>username_3: You can do this using the two div's. check the below code. But it will great if you can use the background image. ``` .div1 { width: 200px; height: 100px; border: 1px solid #c51e1e; margin: 50px; overflow: hidden; } .div2 { width: 80%; height: 100px; margin: 0 auto; box-shadow: 0px 0px 27px 17px #d6cdcd; } ``` Upvotes: 0 <issue_comment>username_4: try this with html: ``` ``` and css: ``` #box { border: 1px solid; position: relative; overflow: hidden; } #box:before { content: ""; box-shadow: 0px 0px 20px 10px #888888; position: absolute; height: 100%; width: 0px; } #box:after { content: ""; box-shadow: 0px 0px 20px 10px #888888; position: absolute; height: 100%; width: 0px; right: 0px; top: 0; } ``` Upvotes: 0 <issue_comment>username_5: And what about a linear-gradeint solution: ```css .box { width:200px; height:100px; background: linear-gradient(to left,#ccc , transparent 20%), linear-gradient(to right,#ccc , transparent 20%); } ``` ```html ``` Upvotes: 1
2018/03/21
300
964
<issue_start>username_0: I have tried the demo of shimmer `FrameLayout` but it goes very fast and I want to slow down the speed of this effect. How to slow down the speed of `shimmer` effect and how to use the properties of this library?<issue_comment>username_1: Try defining `app:shimmer_duration` in XML. e.g. `app:shimmer_duration="1000"` Upvotes: 2 <issue_comment>username_2: You need to use **`app:shimmer_duration="1500"`** to set speed of animation in **`ShimmerFrameLayout`** Try this ``` ``` Upvotes: 5 [selected_answer]<issue_comment>username_3: Add `app:duration="1500"` to shimmer `FrameLayout` by default its duration is 1000 so to slow down i increase the duration ``` ``` Upvotes: 2 <issue_comment>username_4: > > XML Attr: `app:shimmer_duration=""` > You can do the below programmatically - > > > ``` val builder = Shimmer.AlphaHighlightBuilder() builder.setDuration(500L) shimmerFrame.setShimmer(builder.build()) ``` Upvotes: 1
2018/03/21
579
2,181
<issue_start>username_0: ### Hi! Could you please explain why the function runs twice in console? ``` def changeList(myList1): myList2 = myList1.append(4) print(myList2) return myList1 = [1,2,3] changeList(myList1) print (myList1) ``` The result in console: ``` None [1, 2, 3, 4] ``` Does it mean function runs twice as "None" appears in the console?<issue_comment>username_1: Because in the function definition of `changeList`, there is a print statement, and then another print statement after calling `changeList`. The function is only running once actually, but you simply have two separate print statements. Upvotes: 1 <issue_comment>username_2: tl;dr - the function is only running once -- there are two print statements producing output ============================================================================================ The function is *not* running twice: indeed, it is only being run once. The output in the console is instead coming from the two calls to `print()` contained within your program: one inside the function `changeList()` and one outside the function (`print(myList1)`). `None` is being printed to the console because the `return` statement within the function `changeList()` isn't returning anything - there is no value to return: > > If an expression list is present, it is evaluated, else `None` is > substituted. > > > [Taken from the Python 3.6 Documentation] Seeing as how the `return` statement isn't doing anything, you can safely remove it - the function will still end anyway. Hope that helps you out! Upvotes: 2 <issue_comment>username_3: The function is running only once. You are appending one item to list and tried to store in other list by just assigning list with one more item appending which returns None and assigns to myList2. So, the code is wrong because append() function return's None. I think you wan't to do like this so, here is the correct code: comment if is it solved your problem or not. ``` def changeList(myList1): myList2=[] myList2.extend(myList1) myList2.append(4) print(myList2) return myList1 = [1,2,3] changeList(myList1) print (myList1) ``` Upvotes: 2
2018/03/21
495
2,004
<issue_start>username_0: I have two tables(models), one with a json column that may contain the id on other table. I want to join these two together, how do i chain a laravel join to my query.<issue_comment>username_1: Because in the function definition of `changeList`, there is a print statement, and then another print statement after calling `changeList`. The function is only running once actually, but you simply have two separate print statements. Upvotes: 1 <issue_comment>username_2: tl;dr - the function is only running once -- there are two print statements producing output ============================================================================================ The function is *not* running twice: indeed, it is only being run once. The output in the console is instead coming from the two calls to `print()` contained within your program: one inside the function `changeList()` and one outside the function (`print(myList1)`). `None` is being printed to the console because the `return` statement within the function `changeList()` isn't returning anything - there is no value to return: > > If an expression list is present, it is evaluated, else `None` is > substituted. > > > [Taken from the Python 3.6 Documentation] Seeing as how the `return` statement isn't doing anything, you can safely remove it - the function will still end anyway. Hope that helps you out! Upvotes: 2 <issue_comment>username_3: The function is running only once. You are appending one item to list and tried to store in other list by just assigning list with one more item appending which returns None and assigns to myList2. So, the code is wrong because append() function return's None. I think you wan't to do like this so, here is the correct code: comment if is it solved your problem or not. ``` def changeList(myList1): myList2=[] myList2.extend(myList1) myList2.append(4) print(myList2) return myList1 = [1,2,3] changeList(myList1) print (myList1) ``` Upvotes: 2
2018/03/21
659
2,481
<issue_start>username_0: > > Error : > Blockquote > it says "Argument labels '(String:)' do not match any available overloads" > > > ``` class SocketIOManager: NSObject { static let sharedInstance = SocketIOManager() let socket = SocketIOClient(manager: URL(String:"http://localhost:8080") as! URL, nsp: [.log(true), .forcePolling(true)]) // let socket = SocketIOClient(manager: URL(string: "http://localhost:8080")! as! SocketManagerSpec, nsp: [.log(true), .forcePolling(true)]) override init() { super.init() socket.on("test") { dataArray, ack in print(dataArray) } } ``` How can I solve this. any help would be apprciated.<issue_comment>username_1: Because in the function definition of `changeList`, there is a print statement, and then another print statement after calling `changeList`. The function is only running once actually, but you simply have two separate print statements. Upvotes: 1 <issue_comment>username_2: tl;dr - the function is only running once -- there are two print statements producing output ============================================================================================ The function is *not* running twice: indeed, it is only being run once. The output in the console is instead coming from the two calls to `print()` contained within your program: one inside the function `changeList()` and one outside the function (`print(myList1)`). `None` is being printed to the console because the `return` statement within the function `changeList()` isn't returning anything - there is no value to return: > > If an expression list is present, it is evaluated, else `None` is > substituted. > > > [Taken from the Python 3.6 Documentation] Seeing as how the `return` statement isn't doing anything, you can safely remove it - the function will still end anyway. Hope that helps you out! Upvotes: 2 <issue_comment>username_3: The function is running only once. You are appending one item to list and tried to store in other list by just assigning list with one more item appending which returns None and assigns to myList2. So, the code is wrong because append() function return's None. I think you wan't to do like this so, here is the correct code: comment if is it solved your problem or not. ``` def changeList(myList1): myList2=[] myList2.extend(myList1) myList2.append(4) print(myList2) return myList1 = [1,2,3] changeList(myList1) print (myList1) ``` Upvotes: 2
2018/03/21
714
2,647
<issue_start>username_0: I am using Spring Rest Controller in my Web project which is running in Tomcat 8 My json request is- ``` { "type": "Criteria", "fTypeOne": "DataSource", } ``` and my model class is ``` public class FormulaModel implements Serializable{ private String fTypeOne; private String type; } ``` When I send a json request to the rest controller from postman, I observe that the value of **fTypeOne** is not bound but **type** is bound properly. Any help on this issue will be more than welcome. **Environment**: * Spring-web-4.3.14-Release * jackson-databind-2.8.10 * Java version: 1.8.0\_91, vendor: Oracle Corporation * Java home: C:\Program Files\Java\jdk1.8.0\_91\jre * Default locale: en\_IN, platform encoding: Cp1252 * OS name: "windows 7", version: "6.1", arch: "amd64", family: "dos"<issue_comment>username_1: Because in the function definition of `changeList`, there is a print statement, and then another print statement after calling `changeList`. The function is only running once actually, but you simply have two separate print statements. Upvotes: 1 <issue_comment>username_2: tl;dr - the function is only running once -- there are two print statements producing output ============================================================================================ The function is *not* running twice: indeed, it is only being run once. The output in the console is instead coming from the two calls to `print()` contained within your program: one inside the function `changeList()` and one outside the function (`print(myList1)`). `None` is being printed to the console because the `return` statement within the function `changeList()` isn't returning anything - there is no value to return: > > If an expression list is present, it is evaluated, else `None` is > substituted. > > > [Taken from the Python 3.6 Documentation] Seeing as how the `return` statement isn't doing anything, you can safely remove it - the function will still end anyway. Hope that helps you out! Upvotes: 2 <issue_comment>username_3: The function is running only once. You are appending one item to list and tried to store in other list by just assigning list with one more item appending which returns None and assigns to myList2. So, the code is wrong because append() function return's None. I think you wan't to do like this so, here is the correct code: comment if is it solved your problem or not. ``` def changeList(myList1): myList2=[] myList2.extend(myList1) myList2.append(4) print(myList2) return myList1 = [1,2,3] changeList(myList1) print (myList1) ``` Upvotes: 2
2018/03/21
466
1,886
<issue_start>username_0: How to upload images using angular 5 and node js?<issue_comment>username_1: Because in the function definition of `changeList`, there is a print statement, and then another print statement after calling `changeList`. The function is only running once actually, but you simply have two separate print statements. Upvotes: 1 <issue_comment>username_2: tl;dr - the function is only running once -- there are two print statements producing output ============================================================================================ The function is *not* running twice: indeed, it is only being run once. The output in the console is instead coming from the two calls to `print()` contained within your program: one inside the function `changeList()` and one outside the function (`print(myList1)`). `None` is being printed to the console because the `return` statement within the function `changeList()` isn't returning anything - there is no value to return: > > If an expression list is present, it is evaluated, else `None` is > substituted. > > > [Taken from the Python 3.6 Documentation] Seeing as how the `return` statement isn't doing anything, you can safely remove it - the function will still end anyway. Hope that helps you out! Upvotes: 2 <issue_comment>username_3: The function is running only once. You are appending one item to list and tried to store in other list by just assigning list with one more item appending which returns None and assigns to myList2. So, the code is wrong because append() function return's None. I think you wan't to do like this so, here is the correct code: comment if is it solved your problem or not. ``` def changeList(myList1): myList2=[] myList2.extend(myList1) myList2.append(4) print(myList2) return myList1 = [1,2,3] changeList(myList1) print (myList1) ``` Upvotes: 2
2018/03/21
760
1,983
<issue_start>username_0: I have to sort a string array based on the number. **Example** ``` ["1.READ","10.CREATE","3.sfg","2.dfd","12.dqwe"]; ``` **Desired Result** ``` ["1.READ","2.dfd","3.sfg","10.CREATE","12.dqwe"]; ``` **My Code** ``` var arr = ["1.READ","10.CREATE","3.sfg","2.dfd","12.dqwe"]; var arr2 = arr.map( a => a.split('.').map( n => +n+100000 ).join('.') ).sort().map( a => a.split('.').map( n => +n-100000 ).join('.') ); console.log(arr); console.log(arr2); ```<issue_comment>username_1: You can just `split` and convert the first element to `Number` ```js var arr = ["1.READ", "10.CREATE", "3.sfg", "2.dfd", "12.dqwe"]; var arr2 = arr.sort((a, b) => { return Number(a.split(".")[0]) - Number(b.split(".")[0]); }); console.log(arr2); ``` --- The code above will also sort the first variable. If you you only want `arr2` to be sorted, you can: ```js var arr = ["1.READ", "10.CREATE", "3.sfg", "2.dfd", "12.dqwe"]; var arr2 = [...arr]; //Spread the array so that it will not affect the original arr2.sort((a, b) => { return Number(a.split(".")[0]) - Number(b.split(".")[0]); }); console.log(arr); console.log(arr2); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You could split and take only the first part. Then take the delta for sorting. ```js var array = ["1.READ", "10.CREATE", "3.sfg", "2.dfd", "12.dqwe"]; array.sort((a, b) => a.split(".")[0] - b.split(".")[0]); console.log(array); ``` Upvotes: 2 <issue_comment>username_3: Here it is: ``` var arr = ["1.READ","10.CREATE","3.sfg","2.dfd","12.dqwe"]; arr.sort(function(a, b) { return a.split('.')[0] - b.split('.')[0]; }); console.log(arr) // ["1.READ", "2.dfd", "3.sfg", "10.CREATE", "12.dqwe"] ``` This answer base on built in array sort function, with customizable compare logic. Check this out for more detail: [Javascript Array Sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) Cheers, Upvotes: 1
2018/03/21
2,776
11,751
<issue_start>username_0: I'm using **[PHP SQL PARSER](https://code.google.com/archive/p/php-sql-parser/)** my Code ``` php require_once dirname(__FILE__) . '/../src/PHPSQLParser.php'; $sql = 'SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders LEFT JOIN Customers ON Orders.CustomerID=Customers.CustomerID where Customers.CustomerName = "Siddhu"'; $sql = strtolower($sql); echo $sql . "\n"; $parser = new PHPSQLParser($sql, true); echo "<pre"; print_r($parser->parsed); ?> ``` I'm getting output like below array ``` Array ( [SELECT] => Array ( [0] => Array ( [expr_type] => colref [alias] => [base_expr] => orders.orderid [no_quotes] => orders.orderid [sub_tree] => [delim] => , [position] => 7 ) [1] => Array ( [expr_type] => colref [alias] => [base_expr] => customers.customername [no_quotes] => customers.customername [sub_tree] => [delim] => , [position] => 23 ) [2] => Array ( [expr_type] => colref [alias] => [base_expr] => orders.orderdate [no_quotes] => orders.orderdate [sub_tree] => [delim] => [position] => 47 ) ) [FROM] => Array ( [0] => Array ( [expr_type] => table [table] => orders [no_quotes] => orders [alias] => [join_type] => JOIN [ref_type] => [ref_clause] => [base_expr] => orders [sub_tree] => [position] => 70 ) [1] => Array ( [expr_type] => table [table] => customers [no_quotes] => customers [alias] => [join_type] => LEFT [ref_type] => ON [ref_clause] => Array ( [0] => Array ( [expr_type] => colref [base_expr] => orders.customerid [no_quotes] => orders.customerid [sub_tree] => [position] => 101 ) [1] => Array ( [expr_type] => operator [base_expr] => = [sub_tree] => [position] => 118 ) [2] => Array ( [expr_type] => colref [base_expr] => customers.customerid [no_quotes] => customers.customerid [sub_tree] => [position] => 119 ) ) [base_expr] => customers on orders.customerid=customers.customerid [sub_tree] => [position] => 88 ) ) [WHERE] => Array ( [0] => Array ( [expr_type] => colref [base_expr] => customers.customername [no_quotes] => customers.customername [sub_tree] => [position] => 146 ) [1] => Array ( [expr_type] => operator [base_expr] => = [sub_tree] => [position] => 169 ) [2] => Array ( [expr_type] => const [base_expr] => "siddhu" [sub_tree] => [position] => 171 ) ) ) ``` Now I want to generate the query using this array. Why am I doing this, later I will add additional parameters to this array. like I pass additional condition in WHERE clause or Table FOR EXAMPLE: Previous query ``` $sql = 'SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders LEFT JOIN Customers ON Orders.CustomerID=Customers.CustomerID where Customers.CustomerName = "Siddhu"'; ``` Now I want to pass two more conditions in where clause like after WHERE condition Customers.CustomerID = "123" and status = "Active" and created\_by = 1; so here my final query is like ``` $sql = 'SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders LEFT JOIN Customers ON Orders.CustomerID=Customers.CustomerID where Customers.CustomerName = "Siddhu" AND Customers.CustomerID = "123" and status = "Active" and created_by = 1; ``` So how can I achieve it, or Is there any function in [PHPSQLPARSER](https://code.google.com/archive/p/php-sql-parser/) using this array to have any function to generate the query? Thank you for Advance and Sorry for any grammar mistakes<issue_comment>username_1: Honestly, I admit I was not able to fully understand the question. But trying to answer it from what I was able to comprehend. I believe you want to use the output from first query and generate another query with additional where clause. You might just be able to do that by a simple additional select clause with CONCAT in original query itself. Concat your hardcoded original query with desired columns and generate your dynamic SQL as an additional output column. ``` SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate, CONCAT("SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders LEFT JOIN Customers ON Orders.CustomerID=Customers.CustomerID WHERE Customers.CustomerName = \"Siddhu\"", " AND Customers.CustomerID = \"", Customers.CustomerID, " and status = \"Active\" and created_by = 1;") FROM Orders LEFT JOIN Customers ON Orders.CustomerID=Customers.CustomerID WHERE Customers.CustomerName = "Siddhu" ``` If the status field is also coming from one of the tables then you can break the CONCAT function and use that column name instead. Hope it helps. Upvotes: 0 <issue_comment>username_2: To build a query from the Array, `PHPSQLParser` has a `creator` method, From the documentation here : [Parser manual](https://github.com/greenlion/PHP-SQL-Parser/wiki/Parser-Manual) > > There are two ways in which you can create statements from parser output > > > **Use the constructor** > > > The constructor simply calls the create() method on the provided parser tree output for convenience. > > > ``` $parser = new PHPSQLParser('select 1'); $creator = new PHPSQLCreator($parser->parsed); echo $creator->created; ``` > > **Use the create() method** > > > ``` $parser = new PHPSQLParser('select 2'); $creator = new PHPSQLCreator(); echo $creator->create($parser->parsed); /* this is okay, the SQL is saved in the _created_ property. */ /* get the SQL statement for the last parsed statement */ $save = $creator->created; ``` of course since `$parser->parsed` is an `array`, you can passe your own Array ``` echo $creator->create($myArray); ``` To add a condition to the array, you can add it to the `WHERE` array of conditions each condition has 3 arrays defining `colref` ( the column name ), `operator` ( well .. operator ) and `const` ( the value ) the tricky part is the `position` in the sub array of the `WHERE` as you need to specify where exactly you want to insert each one of those three, so based on the `WHERE` in the example you provided , you can see that the position of the operator `=` is `169` ( starting from `0` ) check this tool to see [character position in a string](http://pojo.sodhanalibrary.com/lineCharPosition.html) ( this starts from 1 ). And based on this [Complexe example](https://github.com/greenlion/PHP-SQL-Parser/wiki/Complex-Example) Your final `WHERE` Array should look like this (i'm not sure if you need the `[no_quotes]` key though) : ``` [WHERE] => Array ( [0] => Array ( [expr_type] => colref [base_expr] => customers.customername [no_quotes] => customers.customername [sub_tree] => [position] => 146 ) [1] => Array ( [expr_type] => operator [base_expr] => = [sub_tree] => [position] => 169 ) [2] => Array ( [expr_type] => const [base_expr] => "siddhu" [sub_tree] => [position] => 171 ) // adding other conditions [3] => Array ( [expr_type] => operator [base_expr] => and [sub_tree] => [position] => 180 ) [4] => Array ( [expr_type] => colref [base_expr] => customers.CustomerID [no_quotes] => customers.CustomerID [position] => 184 ) [5] => Array ( [expr_type] => operator [base_expr] => = [sub_tree] => [position] => 205 ) [6] => Array ( [expr_type] => const [base_expr] => "123" [sub_tree] => [position] => 207 ) [7] => Array ( [expr_type] => operator [base_expr] => and [sub_tree] => [position] => 213 ) [8] => Array ( [expr_type] => colref [base_expr] => status [no_quotes] => status [position] => 217 ) [9] => Array ( [expr_type] => operator [base_expr] => = [sub_tree] => [position] => 224 ) [10] => Array ( [expr_type] => const [base_expr] => "Active" [sub_tree] => [position] => 226 ) [11] => Array ( [expr_type] => operator [base_expr] => and [sub_tree] => [position] => 235 ) [12] => Array ( [expr_type] => colref [base_expr] => created_by [no_quotes] => created_by [position] => 239 ) [13] => Array ( [expr_type] => operator [base_expr] => = [sub_tree] => [position] => 250 ) [14] => Array ( [expr_type] => const [base_expr] => 1 [sub_tree] => [position] => 252 ) ) ``` **PS** : i used the query with multiple conditions you provided and took off indentation and line breaks to figure out the positions, play around with those values if you don't have the desired string output as this is supposed to be just an example. i hope this helps or at least gives you an idea and Good Luck. Upvotes: 3 [selected_answer]
2018/03/21
557
1,279
<issue_start>username_0: I am trying to use groups while using `re.sub`. The below works fine. ``` dt1 = "2026-12-02" pattern = re.compile(r'(?P\d{4})-(?P\d{1,2})-(?P\d{1,2})') m = pattern.match(dt1) print(m.group('year')) print(m.group('month')) print(m.group('day')) repl = '\\3-\\2-\\1' print(re.sub(pattern, repl, dt1)) ``` Output is > > 02-12-2026 > > > My query is instead of using group numbers can we use group names as: \day-\month-\year<issue_comment>username_1: ``` dt1 = "2026-12-02" from datetime import datetime print datetime.strptime(dt1, "%Y-%m-%d").strftime("%d-%m-%Y") ``` There is no need for regex here. Output: `02-12-2026` But if you want to use regex then here it goes, ``` dt1 = "2026-12-02" pattern = re.compile(r'(?P\d{4})-(?P\d{1,2})-(?P\d{1,2})') m = pattern.match(dt1) def repl(matchobj): print matchobj.groupdict() return matchobj.group('year')+"-"+matchobj.group('month')+"-"+matchobj.group('day') print(re.sub(pattern, repl, dt1)) ``` Upvotes: 2 <issue_comment>username_2: There is a pretty straight up syntax for accesing groups, using `\g` ``` import re dt1 = "2026-12-02" pattern = re.compile(r'(?P\d{4})-(?P\d{1,2})-(?P\d{1,2})') print(pattern.sub(r"\g-\g-\g", dt1)) Output: '02-12-2026' ``` Upvotes: 4 [selected_answer]
2018/03/21
515
1,849
<issue_start>username_0: Suddenly, can't build my React Native Apps on Android. **I have never changed Android side but this error occurs while building.** react-native: "^0.52.0", react-native-google-signin: "git+<https://github.com/invertase/react-native-google-signin.git#v0.12.1>", ``` :react-native-google-signin:mergeReleaseResources UP-TO-DATE :react-native-google-signin:processReleaseManifest UP-TO-DATE :react-native-google-signin:processReleaseResources FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':react-native-google-signin:processReleaseResources'. > Error: more than one library with package name 'com.google.android.gms.license' ```<issue_comment>username_1: I same problem too, i fix with this. edit `\node_modules\react-native-google-signin\android\build.gradle` ``` compile 'com.google.android.gms:play-services-auth:+ ``` change `+` to `11.6.0` Related with: <https://github.com/facebook/react-native/issues/18479> Upvotes: 2 <issue_comment>username_2: I solved the issues by adding in `android\build.gradle` the following ``` allprojects { repositories { ... configurations.all { resolutionStrategy { ... force 'com.google.android.gms:play-services-auth:11.6.0' } } } } ``` I would recommend against modifying `\node_modules\react-native-google-signin\android\build.gradle` as it would break on a clean `npm install` Upvotes: 0 <issue_comment>username_3: **if you are facing this issue while running ./gradlew assembleRelease command.** You can fix this issue by replacing ./gradlew assembleRelease with ./gradlew app:assembleRelease Upvotes: 0 <issue_comment>username_4: I fixed this issue by replace `./gradlew assembleRelease` by `./gradlew app:assembleRelease` Upvotes: 0
2018/03/21
617
1,981
<issue_start>username_0: I want to show my business tagline in "monotype corsiva" font it is not available on Google font so any body can please help me out for it .<issue_comment>username_1: First you have to locate the otf/ttf/woff font file on your local machine. Then, put this into the css file. ``` @font-face { font-family: mylocalfont; src: url(fontname.woff); } body{ font-family: mylocalfont; } ``` Upvotes: 1 <issue_comment>username_2: <http://fontsforweb.com/font/show?id=6771> Please log in or register to get your embedding links or Download the font which has all the code needed included. Upvotes: 1 <issue_comment>username_3: You need to upload your font and then write the code in css to access that. ``` @font-face { font-family: 'MyWebFont'; src: url('webfont.eot'); /* IE9 Compat Modes */ src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('webfont.woff2') format('woff2'), /* Super Modern Browsers */ url('webfont.woff') format('woff'), /* Pretty Modern Browsers */ url('webfont.ttf') format('truetype'), /* Safari, Android, iOS */ url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */ } body { font-family: 'MyWebFont', Fallback, sans-serif; } ``` In modern browsers you can only use .ttf file, so your font face code will be like: ``` @font-face { font-family: 'MyWebFont'; src: url('webfont.ttf'); } body { font-family: 'MyWebFont', Fallback, sans-serif; } ``` Make it correct answer if it resolve your problem. :) Upvotes: 2 <issue_comment>username_4: Paste all these font formates in your css folder otf/ttf/woff. Add in your stylesheet:- ``` @font-face { font-family: 'MTCORSVA'; src: url('./MTCORSVA.eot'); src: local('MTCORSVA'), url('./MTCORSVA.woff') format('woff'), url('./MTCORSVA.ttf') format('truetype'); } ``` now use this to apply font family `font-family: 'MTCORSVA';` Upvotes: 3 [selected_answer]
2018/03/21
683
2,153
<issue_start>username_0: Is there a way to check two file exists in same folder like *music1.mp3* and *music2.mp3* in folder *Testapp*? This my code check one file: ``` File f = new File(Environment.getExternalStorageDirectory()+"/Testapp/music1.mp3"); if(f.exists()) { /* do something */ } else { /* do something */ } ```<issue_comment>username_1: First you have to locate the otf/ttf/woff font file on your local machine. Then, put this into the css file. ``` @font-face { font-family: mylocalfont; src: url(fontname.woff); } body{ font-family: mylocalfont; } ``` Upvotes: 1 <issue_comment>username_2: <http://fontsforweb.com/font/show?id=6771> Please log in or register to get your embedding links or Download the font which has all the code needed included. Upvotes: 1 <issue_comment>username_3: You need to upload your font and then write the code in css to access that. ``` @font-face { font-family: 'MyWebFont'; src: url('webfont.eot'); /* IE9 Compat Modes */ src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('webfont.woff2') format('woff2'), /* Super Modern Browsers */ url('webfont.woff') format('woff'), /* Pretty Modern Browsers */ url('webfont.ttf') format('truetype'), /* Safari, Android, iOS */ url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */ } body { font-family: 'MyWebFont', Fallback, sans-serif; } ``` In modern browsers you can only use .ttf file, so your font face code will be like: ``` @font-face { font-family: 'MyWebFont'; src: url('webfont.ttf'); } body { font-family: 'MyWebFont', Fallback, sans-serif; } ``` Make it correct answer if it resolve your problem. :) Upvotes: 2 <issue_comment>username_4: Paste all these font formates in your css folder otf/ttf/woff. Add in your stylesheet:- ``` @font-face { font-family: 'MTCORSVA'; src: url('./MTCORSVA.eot'); src: local('MTCORSVA'), url('./MTCORSVA.woff') format('woff'), url('./MTCORSVA.ttf') format('truetype'); } ``` now use this to apply font family `font-family: 'MTCORSVA';` Upvotes: 3 [selected_answer]
2018/03/21
501
1,600
<issue_start>username_0: Okay so I've usually had **.box-4** as the last element inside of **.s1** as shown below: ``` ``` and had **.box-1** move before **.box-4** using the JavaScript: ``` var box1 = document.querySelector('.box-1'); var s1 = box1.parentNode; s1.insertBefore(box1, s1.lastElementChild); ``` to receive the following outcome: ``` ``` however, I have recently removed **.box-4** from **.s1**, and consequently **.box-1** no longer move/becomes **the** **.lastElementChild.** I would still like **.box-1** to move, and hence become last, however, I'm unsure of what command will achieve this; desirably something like this ``` .insertAs(box1, s1.lastElementChild); ``` to achieve this: ``` ``` NOTE: **.box-1** changes position depending on screen-width, so simply moving the div in HTML is not an option. NOTE: **Vanilla JavaScript only** - No jQquery. Thanks in advance guys, much appreciated!<issue_comment>username_1: To insert HTML without jQuery simply use insertAdjactedHTML function. <https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML> Upvotes: 0 <issue_comment>username_2: Just use `.appendChild`? ```js const box1 = document.querySelector('.box-1'); const s1 = box1.parentElement; box1.remove(); s1.appendChild(box1); ``` ```html b1 b2 b3 b4 ``` Upvotes: 0 <issue_comment>username_3: Below will append box1 as the last child (automatically removes it from it's original position). ``` var box1 = document.querySelector('.box-1'); var s1 = box1.parentNode; s1.appendChild(box1); ``` Upvotes: 2 [selected_answer]
2018/03/21
422
1,295
<issue_start>username_0: In the function shown below, there is no `return`. However, after executing it, I can confirm that the value entered `d` normally. There is no `return`. Any suggestions in this regard will be appreciated. **Code** ``` #installed plotly, dplyr accumulate_by <- function(dat, var) { var <- lazyeval::f_eval(var, dat) lvls <- plotly:::getLevels(var) dats <- lapply(seq_along(lvls), function(x) { cbind(dat[var %in% lvls[seq(1, x)], ], frame = lvls[[x]]) }) dplyr::bind_rows(dats) } d <- txhousing %>% filter(year > 2005, city %in% c("Abilene", "Bay Area")) %>% accumulate_by(~date) ```<issue_comment>username_1: To insert HTML without jQuery simply use insertAdjactedHTML function. <https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML> Upvotes: 0 <issue_comment>username_2: Just use `.appendChild`? ```js const box1 = document.querySelector('.box-1'); const s1 = box1.parentElement; box1.remove(); s1.appendChild(box1); ``` ```html b1 b2 b3 b4 ``` Upvotes: 0 <issue_comment>username_3: Below will append box1 as the last child (automatically removes it from it's original position). ``` var box1 = document.querySelector('.box-1'); var s1 = box1.parentNode; s1.appendChild(box1); ``` Upvotes: 2 [selected_answer]
2018/03/21
541
1,986
<issue_start>username_0: Without bothering you with what I intend to do, could someone kindly point out where I can get the default DataGridComboBoxColumn ControlTemplate. I am sure there must be a Control Template or some kind of style that targets a DataGridComboBoxColumn, otherwise how did Microsoft build the DataGridComboBoxColumn.<issue_comment>username_1: > > Without bothering you with what I intend to do > > > I think it is not so unimportant, because of these advises on MSDN page [DataGridComboBoxColumn Class](https://msdn.microsoft.com/en-us/library/system.windows.controls.datagridcomboboxcolumn(v=vs.110).aspx): > > Represents a DataGrid column that **hosts ComboBox controls** in its > cells. > > > and > > If you want to use other controls in your DataGrid, you can create > your own column types by using DataGridTemplateColumn. > > > For styling (also `ControlTemplate`!) of `ComboBox` you can use `ElementStyle` and `EditingElementStyle` properties of `DataGridComboBoxColumn`. Default template for ComboBox you can find here: [ComboBox Styles and Templates](https://learn.microsoft.com/en-us/dotnet/framework/wpf/controls/combobox-styles-and-templates) Small example: ``` <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ComboBox"> <TextBlock Text={Binding SomePropertyOfYourRowDataContext}/> </ControlTemplate> </Setter.Value> </Setter> ``` Upvotes: 1 <issue_comment>username_2: > > Could someone kindly point out where I can get the default `DataGridComboBoxColumn` `ControlTemplate`. > > > A `DataGridComboBoxColumn` is not a `Control` and hence it has no `ControlTemplate`. It creates a `ComboBox` in its `GenerateEditingElement` method and it is this `ComboBox` that you see when the cell of a `DataGridComboBoxColumn` is in edit mode: <https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Controls/DataGridComboBoxColumn.cs,90924e66a85fbfa4>. Upvotes: 0
2018/03/21
770
2,430
<issue_start>username_0: I've been trying my best to center a div that contains a form `.form-group` inside another div `#myCarousel`, responsively both vertically and horizontally. (works across different device widths) I've tried `absolute` positioning with pixels, percentage - but that didn't work. I tried making the form a child element inside the `#myCarousel`, but I wasn't able to make it work. My goal is to make the form in the exact center of the caraousel (over the image slider) and have the images sliding in background, while the form stays fixed in the center. Here is what my code looks like. **[Codepen Link](https://codepen.io/rahuls360/pen/PRpQpO)** ``` ... Product 1 Product 2 Product 3 ``` I'd be glad if you'll could guide me here.<issue_comment>username_1: margin:0px auto or position :absolute;left:50%;top:50%; to center Upvotes: 0 <issue_comment>username_2: Add this to your `form-group` class. ``` .form-group{ max-width: 300px; margin: auto; } ``` Upvotes: 1 <issue_comment>username_3: ``` #myCarousel { display: flex; justify-content: center; align-items: center; } ``` Sticking inside should make `.form-group` vertically and horizontally centered inside `#myCarousel`. [CSS Tricks has a good overview](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) Upvotes: 1 <issue_comment>username_4: Well first you will need to place the `.form-group` div inside of your `#myCarouse` div and then using `position: absolute` and `transform` trick you can align it vertically and horizontally center HTML ``` ... [Next](#myCarousel) ... ``` CSS ``` #myCarousel .form-group { width: 300px; width: 300px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: #fff; padding: 10px; } ``` **[Updated Codepen](https://codepen.io/bhuwanb9/pen/dmvmVK?editors=1000)** Upvotes: 2 [selected_answer]<issue_comment>username_5: You need to put .form-group inside #myCarousel. ``` .form-group { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); ``` } Upvotes: 0 <issue_comment>username_6: Try this in your CSS: ``` .slider-container { position: relative; } .form-group { # you should add and define css for custom class instead of overide Bootstrap class. margin: auto; position: absolute; top: 50%; left: 50%; margin-left: -150px; } ``` and HTML: ``` ..... ``` Upvotes: 0
2018/03/21
1,928
5,981
<issue_start>username_0: So as the title shows, I've got a function that uses a temporary array, and I want to write a value into it from another array, and then multiply the two value with itself. Example: ``` float[] a = {0, 0} a[0] *= a[0] = b[n ]; a[1] *= a[1] = b[n + 1]; ``` I would expect the above would do the following: ``` a[0] = b[n ]; a[0] *= a[0]; //(aka: a[0] = a[0] * a[0]) a[1] = b[n + 1]; a[1] *= a[1]; ``` Though that behavior doesn't seem to be whats happening. Instead it seems just multiply whatever the original value held in "a" was with whatever value was held in "b" like so: ``` a[0] = a[0] * b[n ]; a[1] = a[1] * b[n + 1]; ``` It was always my understanding that whatever comes after the "=" is evaluated first, as seen when you do: ``` float a, b; a = b = 5; //"a" and "b" both equal "5" now. ``` Being that that is the case, would it not show that my original example should work? Can anyone explain whats going on and why this code doesn't work as intended?<issue_comment>username_1: Assignment operators (unlike most other operators) are evaluated from *right* to *left* in Java ([documentation](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html)). This means that the following: ``` a[0] *= a[0] = b[n]; ``` is actually evaluated as: ``` a[0] *= (a[0] = b[n]); ``` The quantity in parentheses is an assignment, and returns the value `b[n]`, but does not change the value of `a[0]`. Then, the following final assignment is made: ``` a[0] = a[0] * b[n] ``` Both `*=` and `=` are assignment operators, and have the same level of precedence. So in this case, the right to left rule applies. Upvotes: 2 <issue_comment>username_2: Referring to the Java [documentation](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html): > > All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left. > > > So what is happening in your case of `a[0] *= a[0] = b[n ];` is that you assign `a[0]` the value of `b[n]` and then you multiply the original `a[0]` by that new value. So your expression is effectively `a[0] *= b[n]`. Personally, I don't use an assignment operator twice on a single line, it can be confusing to read. Upvotes: 2 <issue_comment>username_3: I think the answers so far are not correct. What comes into play is the evaluation of compound expressions like `a *= b`. In short, the value of **the left hand side is computed before the right hand side**. From the [JLS](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2) (emphasis mine): > > At run time, the expression is evaluated in one of two ways. > > > If the left-hand operand expression is not an array access expression, > then: > > > First, the left-hand operand is evaluated to produce a variable. If > this evaluation completes abruptly, then the assignment expression > completes abruptly for the same reason; the right-hand operand is not > evaluated and no assignment occurs. > > > Otherwise, **the value of the left-hand operand is saved and then the > right-hand operand is evaluated**. If this evaluation completes > abruptly, then the assignment expression completes abruptly for the > same reason and no assignment occurs. > > > Otherwise, the saved value of the left-hand variable and the value of > the right-hand operand are used to perform the binary operation > indicated by the compound assignment operator. If this operation > completes abruptly, then the assignment expression completes abruptly > for the same reason and no assignment occurs. > > > Otherwise, the result of the binary operation is converted to the type > of the left-hand variable, subjected to value set conversion (§5.1.13) > to the appropriate standard value set (not an extended-exponent value > set), and the result of the conversion is stored into the variable. > > > In your example: ``` a[0] *= a[0] = b[n ]; ``` 1. value of `a[0]` is computed and stored in say `tmp` 2. `a[0] = b[n]` is evaluated, giving the value of `b[n]` (and changing the value of `a[0]` to `b[n]`) 3. `tmp * a[0]` is computed 4. the result of the last step is assigned to `a[0]` So, what you get is effectively `a[0] *= b[n]`. **EDIT:** About the confusion about right-to-left-*evaluation* of assignments: I did not find that terminology used in the JLS, and IMHO it is not correct (although it is used in the Java tutorials). It is called right-\*\*associative\* assThe JLS says this about assignments: > > There are 12 assignment operators; all are syntactically > right-associative (they group right-to-left). Thus, a=b=c means > a=(b=c), which assigns the value of c to b and then assigns the value > of b to a. > > > Upvotes: 4 [selected_answer]<issue_comment>username_4: A key point that doesn't seem to have been pointed out in the answers yet is that `*=` isn't merely an assignment operator, but rather a *compound* assignment operator. [The language spec](https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.26.2) says that the following are equivalent: ``` E1 op= E2 <=> E1 = (T) ((E1) op (E2)) ``` where `op=` is something like `*=`, `+=` etc. As such: ``` a[0] *= a[0] = b[n ]; ``` is equivalent to: ``` a[0] = a[0] * (a[0] = b[n]); ``` and the `a[0]` is evaluated before the `(a[0] = b[n])`, because of the [left-to-right evaluation order](https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.7). So: * This reads the value from `a[0]` (call this "`A`") * It reads the value from `b[n]` (call this "`B`") * It assigns `B` to `a[0]` (\*) * And then multiplies `A * B` (call this "`C`") * And then stores `C` back in `a[0]`. So yes, this is equivalent to multiplying whatever is in `a[0]` by `b[n]`, because the step marked (\*) above is redundant: the value assigned there is never read before it is reassigned. Upvotes: 0
2018/03/21
648
2,108
<issue_start>username_0: Thank you for viewing. I am an engineer in Japan. I am glad that you can understand that you are not very good at English. Well, it is the main subject. programming language is PHP. I am trying to obtain account information by using HUOBI's API. <https://github.com/huobiapi/REST-API-demos/tree/master/REST-PHP-DEMO> An error occurred when `get_balance()` was executed by changing the setting of `demo.php` to my ID and password. The details of the error are as follows. ``` object(stdClass)#2 (4) { ["status"]=> string(5) "error" ["err-code"]=> string(44) "account-get-balance-account-inexistent-error" ["err-msg"]=> string(64) "account for id `*,***,***` and user id `×,×××,×××` is not exist" ["data"]=> NULL } ``` `*,***,***` is my UID!! `×,×××,×××` id Next number of UID(UID+1) Source is exactly as git goes up. I will wait for the answer.<issue_comment>username_1: you got the error message "account-get-balance-account-inexistent-error" which means your account is not correct in define. Please make sure you've define the value beforehand. ``` define('ACCOUNT_ID', ''); define('ACCESS_KEY',''); define('SECRET_KEY', ''); ``` Upvotes: 0 <issue_comment>username_2: Firstly, Check your UID here:<https://www.huobi.com/en-us/user_center/uc_info/> then get your **account-id** here [get account-id](https://github.com/huobiapi/API_Docs_en/wiki/REST_Reference#get-v1accountaccounts-get-all-the-accounts-pro-and-hadax-share-the-same-account-id) Replace `XXXXXXX` in `define('ACCOUNT_ID', 'XXXXXXX')` by your **account-id** Happy show hand :) Upvotes: 0 <issue_comment>username_3: Ok, i just wan't that somebody be able to google it because huobi support refuses to confirm or fix the problem. If you're getting "account-frozen-account-inexistent-error" while placing new it's possible, that everything is ok with your account, but you have no funds for concrete asset. For example, you have 0 BTC and trying to sell some BTC to exchange them with USDT. You'll get this error instead of "insufficient balance" or something more appropriate Upvotes: 2
2018/03/21
786
2,005
<issue_start>username_0: I have a .NET Core 2 class library im trying to create an artifact for in VSTS (for NuGet publish, but that's next..) My "Publish Build Artifacts" task can't find the folder i've published via `dotnet publish`. `dotnet publish` output: ``` 2018-03-21T06:11:41.2709655Z [command]"C:\Program Files\dotnet\dotnet.exe" publish D:\a\1\s\src\xxx\xxx.csproj --configuration release --output D:\a\1\a\publish 2018-03-21T06:11:41.5475294Z Microsoft (R) Build Engine version 15.6.82.30579 for .NET Core 2018-03-21T06:11:41.5476483Z Copyright (C) Microsoft Corporation. All rights reserved. 2018-03-21T06:11:41.5477091Z 2018-03-21T06:11:42.5040403Z Restore completed in 83.05 ms for D:\a\1\s\src\xxx\xxx.csproj. 2018-03-21T06:11:43.3434895Z xxx-> D:\a\1\s\src\xxx\bin\release\netstandard2.0\xxx.dll 2018-03-21T06:11:43.9833363Z xxx-> D:\a\1\a\publish\ ``` The "Publish Build Artifacts" task just errors and says: ``` 2018-03-21T06:11:44.9159833Z ##[error]Publishing build artifacts failed with an error: Not found PathtoPublish: D:\a\1\a\publish 2018-03-21T06:11:44.9209300Z ##[section]Finishing: Publish Artifact ``` Even though the last line in the `dotnet publish` output matches the line. This is what i have in VSTS: [![enter image description here](https://i.stack.imgur.com/oFgPB.png)](https://i.stack.imgur.com/oFgPB.png) What am i doing wrong?<issue_comment>username_1: If your project is not a asp.net application, after building and before the "publish artifacts" you have to add a copy task, like this ... [![enter image description here](https://i.stack.imgur.com/47uU5.png)](https://i.stack.imgur.com/47uU5.png) Upvotes: 2 <issue_comment>username_2: Since you want to use artifact for NuGet publish, you should use `Dotnet pack` to package the project, then publish to artifact, after that you can push package to server. 1. Remove .NET Core Publish task 2. Add .NET Core task before Publish Build Artifacts task (Command: pack) Upvotes: 3 [selected_answer]
2018/03/21
372
1,364
<issue_start>username_0: How can I pass a java variable to a tag and make it downloadable ? I have tried the below code. But unfortunately it opens the file, rather than downloading it. ``` out.println("[" + fileName + " download]( + path + )" + " "); ``` Please follow the full code, ``` while (rs.next()) { System.out.println(rs.getString("location")); path = rs.getString("location"); fileName = rs.getString("fileName"); out.print(path + " "); out.println("[" + fileName + " download]( + path + )" + " "); } ```<issue_comment>username_1: The latest chrome(from 65) disabled download file which is not same origin with the site you visit. Before chrome 65 you can download the file just add download attribute to tag. The commit link is <https://chromium.googlesource.com/chromium/src/+/2a6afcb26ba6cd2324ddaa366b11968237e304a3%5E%21/#F0> So if you still want to download the file, the link you request should return response header `Content-Disposition: attachment; filename=filename.ext` Upvotes: 2 <issue_comment>username_2: Server need to send the respnose header `Content-Disposition` when you click on that link. ``` Content-Type: application/octet-stream Content-Disposition: attachment; filename="picture.png" ``` Upvotes: 2 [selected_answer]
2018/03/21
1,113
4,183
<issue_start>username_0: [![enter image description here](https://i.stack.imgur.com/GJcus.png)](https://i.stack.imgur.com/GJcus.png)[![enter image description here](https://i.stack.imgur.com/gT5Kw.png)](https://i.stack.imgur.com/gT5Kw.png)[![enter image description here](https://i.stack.imgur.com/1Bu6q.png)](https://i.stack.imgur.com/1Bu6q.png)[![enter image description here](https://i.stack.imgur.com/JA6M3.png)](https://i.stack.imgur.com/JA6M3.png)Please find my code below. How can we append filter data on array from Firebase? ``` var childrenList = [DatabaseList]() let ref = Database.database().reference(withPath: "Messages") let query = ref.queryOrdered(byChild: "VideoID").queryEqual(toValue: "12345").observe(.value, with: { (snapshot) in for childSnapshot in snapshot.children{ print(childSnapshot) self.childrenList.append(snapshot) } }) DispatchQueue.main.async { self.tableView.reloadData() } ```<issue_comment>username_1: ``` let ref = Database.database().reference(withPath: "Messages") let query = ref.queryOrdered(byChild: "VideoID").queryEqual(toValue: "12345").observe(.value, with: { (snapshot) in print(snapshot) for (childSnapshotId, childSnapshotValue) in snapshot { if let dataListDict = childSnapshotValue as? [String: AnyObject] { //Init you newModel with the dataListDict here let newModel = DatabaseList(dict: dataListDict) print(childSnapshot) self.childrenList.append(newModel) } } DispatchQueue.main.async { self.tableView.reloadData() } }) class DatabaseList : NSObject { var messageBody : String? var name : String? var videoID : String? init(dict: [String: AnyObject]) { messageBody = dict["MessageBody"] name = dict["Name"] videoID = dict["videoID"] } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Your query is correct but there are few mistakes in finishing block. `self.childrenList.append(snapshot)` snapshot is an instance of `DataSnapshot` not a `DatabaseList` so you can not append it like this. ``` for childSnapshot in snapshot.children { /// childSnapshot is an instance of DataSnapshot not a dictionary but its value will be guard let data = (childSnapshot as! DataSnapshot).value else {continue} let dataDict = data as! Dictionary /// Initializing the new object of DatabaseList and passing the values from data let list: DatabaseList = DatabaseList() list.messageBody = dataDict["MessageBody"] as? String list.name = dataDict["Name"] as? String list.videoID = dataDict["VideoID"] as? String /// This is correct, and now you can append it to your array. childrenList.append(list) } ``` Apart from this you will have to reload the `tableView` inside the finishing block not below the block because this is an asynchronous request and data will come later. Also its always better to check the data existence. `snapshot.exists()`. One more suggestion if you want to fetch the data just once then do not use `.observe` use `.observeSingleEvent` instead. `.observe` will fire the block every time there is any change at this node. **Here is the full code snippet.** ``` let query = ref.queryOrdered(byChild: "VideoID").queryEqual(toValue: "12345").observe(.value, with: { (snapshot) in if !snapshot.exists() { // Data doesn't exist return } for childSnapshot in snapshot.children { guard let data = (childSnapshot as! DataSnapshot).value else {continue} let dataDict = data as! Dictionary let list: DatabaseList = DatabaseList() list.messageBody = dataDict["MessageBody"] as? String list.name = dataDict["Name"] as? String list.videoID = dataDict["VideoID"] as? String childrenList.append(list) } /// Reload your tableView here DispatchQueue.main.async { self.tableView.reloadData() } }) ``` **And expecting the class model like below:** ``` class DatabaseList: NSObject { var messageBody: String? var name: String? var videoID: String? } ``` Upvotes: 1
2018/03/21
1,367
3,686
<issue_start>username_0: Given a list of dictionaries: ``` players= [ { "name": 'matt', 'school': 'WSU', 'homestate': 'CT', 'position': 'RB' }, { "name": 'jack', 'school': 'ASU', 'homestate': 'AL', 'position': 'QB' }, { "name": 'john', 'school': 'WSU', 'homestate': 'MD', 'position': 'LB' }, { "name": 'kevin', 'school': 'ALU', 'homestate': 'PA', 'position': 'LB' }, { "name": 'brady', 'school': 'UM', 'homestate': 'CA', 'position': 'QB' }, ] ``` How do I group them into groups by matching their matching dictionary values, such that it spews out: > > Matching Value 1: > > > > > > > name: [matt, john, kevin], > > > > > > school: [WSU, WSU, ALU], > > > > > > homestate: [CT, MD, PA] > > > > > > position: [RB, LB, LB] > > > > > > > > > Matching Value 2: > > > > > > > name: [jack, brady], > > > > > > school: [ASU, UM], > > > > > > homestate: [AL, CA] > > > > > > position: [QB, QB] > > > > > > > > > Notice that the matching values are arbitrary; that is, it can be found anywhere. Maybe its in `school` or in `position`, or maybe in both. I tried grouping them by doing: ``` from collections import defaultdict result_dictionary = {} for i in players: for key, value in i.items(): result_dictionary.setdefault(key, []).append(value) ``` Which gives out: ``` {'name': ['matt', 'jack', 'john', 'kevin', 'brady'], 'school': ['WSU', 'ASU', 'WSU', 'ALU', 'UM'], 'homestate': ['CT', 'AL', 'MD', 'PA', 'CA'], 'position': ['RB', 'QB', 'LB', 'QB', 'QB']} ``` But I'm stuck on how do I further manipulate the output to match the required output I stated above, and I am sure there are better, simpler approach in doing it.<issue_comment>username_1: Just use `collections.defaultdict` that you already imported: ``` In [21]: from collections import defaultdict ...: result = defaultdict(lambda: defaultdict(list)) ...: for d in players: ...: for k,v in d.items(): ...: result[d['school']][k].append(v) ...: In [22]: result Out[22]: defaultdict(>, {'ASU': defaultdict(list, {'homestate': ['AL'], 'name': ['jack'], 'position': ['QB'], 'school': ['ASU']}), 'WSU': defaultdict(list, {'homestate': ['CT', 'MD'], 'name': ['matt', 'john'], 'position': ['RB', 'LB'], 'school': ['WSU', 'WSU']})}) ``` Upvotes: 2 <issue_comment>username_2: You can find the most common occurring header value and use the latter value as a focal point for further grouping: ``` import itertools players= [ { "name": 'matt', 'school': 'WSU', 'homestate': 'CT', 'position': 'RB' }, { "name": 'jack', 'school': 'ASU', 'homestate': 'AL', 'position': 'QB' }, { "name": 'john', 'school': 'WSU', 'homestate': 'MD', 'position': 'LB' }, { "name": 'kevin', 'school': 'ALU', 'homestate': 'PA', 'position': 'S' }, { "name": 'brady', 'school': 'UM', 'homestate': 'CA', 'position': 'QB' }, ] headers = ['name', 'school', 'homestate', 'position'] final_header = [[a, max(b, key=lambda x:b.count(x))] for a, b in zip(headers, zip(*[[i[b] for b in headers] for i in players])) if len(set(b)) < len(b)] d = [[list(b) for _, b in itertools.groupby(filter(lambda x:x[i] == c, players), key=lambda x:x[i])][0] for i, c in final_header] last_results = {'pattern {}'.format(i):{d[0][0]:[j[-1] for j in d] for c, d in zip(headers, zip(*map(dict.items, h)))} for i, h in enumerate(d, start=1)} ``` Output: ``` {'pattern 2': {'homestate': ['AL', 'CA'], 'school': ['ASU', 'UM'], 'name': ['jack', 'brady'], 'position': ['QB', 'QB']}, 'pattern 1': {'homestate': ['CT', 'MD'], 'school': ['WSU', 'WSU'], 'name': ['matt', 'john'], 'position': ['RB', 'LB']} } ``` Upvotes: 1
2018/03/21
2,967
10,927
<issue_start>username_0: Previously asked similar question but somehow I'm not finding my way out, attempting again with another example. The code as a starting point (a bit trimmed) is available at <https://ideone.com/zkQcIU>. (it has some issue recognizing `Microsoft.FSharp.Core.Result` type, not sure why) Essentially all operations have to be pipelined with the previous function feeding the result to the next one. The operations have to be async and they should return error to the caller in case an exception occurred. The requirement is to give the caller either result or fault. All functions return a Tuple populated with either **Success** `type Article` or **Failure** with `type Error` object having descriptive `code` and `message` returned from the server. Will appreciate a working example around my code both for the callee and the caller in an answer. **Callee Code** ``` type Article = { name: string } type Error = { code: string message: string } let create (article: Article) : Result = let request = WebRequest.Create("http://example.com") :?> HttpWebRequest request.Method <- "GET" try use response = request.GetResponse() :?> HttpWebResponse use reader = new StreamReader(response.GetResponseStream()) use memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(reader.ReadToEnd())) Ok ((new DataContractJsonSerializer(typeof)).ReadObject(memoryStream) :?> Article) with | :? WebException as e -> use reader = new StreamReader(e.Response.GetResponseStream()) use memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(reader.ReadToEnd())) Error ((new DataContractJsonSerializer(typeof)).ReadObject(memoryStream) :?> Error) ``` **Rest of the chained methods** - Same signature and similar bodies. You can actually reuse the body of `create` for `update`, `upload`, and `publish` to be able to test and compile code. ``` let update (article: Article) : Result // body (same as create, method <- PUT) let upload (article: Article) : Result // body (same as create, method <- PUT) let publish (article: Article) : Result // body (same as create, method < POST) ``` **Caller Code** ``` let chain = create >> Result.bind update >> Result.bind upload >> Result.bind publish match chain(schemaObject) with | Ok article -> Debug.WriteLine(article.name) | Error error -> Debug.WriteLine(error.code + ":" + error.message) ``` **Edit** Based on the answer and matching it with Scott's implementation (<https://i.stack.imgur.com/bIxpD.png>), to help in comparison and in better understanding. ``` let bind2 (switchFunction : 'a -> Async>) = fun (asyncTwoTrackInput : Async>) -> async { let! twoTrackInput = asyncTwoTrackInput match twoTrackInput with | Ok s -> return! switchFunction s | Error err -> return Error err } ``` **Edit 2** Based on F# implementation of bind ``` let bind3 (binder : 'a -> Async>) (asyncResult : Async>) = async { let! result = asyncResult match result with | Error e -> return Error e | Ok x -> return! binder x } ```<issue_comment>username_1: Take a look at the [Suave source code](https://github.com/SuaveIO/suave/blob/4e7ff951f1a85daaceea1a2dcf5408983ea2c200/src/Suave/WebPart.fs), and specifically the `WebPart.bind` function. In Suave, a WebPart is a function that takes a context (a "context" is the current request and the response so far) and returns a result of type `Async`. The semantics of chaining these together are that if the async returns `None`, the next step is skipped; if it returns `Some value`, the next step is called with `value` as the input. This is pretty much the same semantics as the `Result` type, so you could almost copy the Suave code and adjust it for Result instead of Option. E.g., something like this: ``` module AsyncResult let bind (f : 'a -> Async>) (a : Async>) : Async> = async { let! r = a match r with | Ok value -> let next : Async> = f value return! next | Error err -> return (Error err) } let compose (f : 'a -> Async>) (g : 'b -> Async>) : 'a -> Async> = fun x -> bind g (f x) let (>>=) a f = bind f a let (>=>) f g = compose f g ``` Now you can write your chain as follows: ``` let chain = create >=> update >=> upload >=> publish let result = chain(schemaObject) |> Async.RunSynchronously match result with | Ok article -> Debug.WriteLine(article.name) | Error error -> Debug.WriteLine(error.code + ":" + error.message) ``` Caution: I haven't been able to verify this code by running it in F# Interactive, since I don't have any examples of your create/update/etc. functions. It should work, in principle — the types all fit together like Lego building blocks, which is how you can tell that F# code is probably correct — but if I've made a typo that the compiler would have caught, I don't yet know about it. Let me know if that works for you. **Update:** In a comment, you asked whether you need to have both the `>>=` and `>=>` operators defined, and mentioned that you didn't see them used in the `chain` code. I defined both because they serve different purposes, just like the `|>` and `>>` operators serve different purposes. `>>=` is like `|>`: it passes a *value* into a *function*. While `>=>` is like `>>`: it takes *two functions* and combines them. If you would write the following in a non-AsyncResult context: ``` let chain = step1 >> step2 >> step3 ``` Then that translates to: ``` let asyncResultChain = step1AR >=> step2AR >=> step3AR ``` Where I'm using the "AR" suffix to indicate versions of those functions that return an `Async>` type. On the other hand, if you had written that in a pass-the-data-through-the-pipeline style: ``` let result = input |> step1 |> step2 |> step3 ``` Then that would translate to: ``` let asyncResult = input >>= step1AR >>= step2AR >>= step3AR ``` So that's why you need both the `bind` and `compose` functions, and the operators that correspond to them: so that you can have the equivalent of either the `|>` or the `>>` operators for your AsyncResult values. BTW, the operator "names" that I picked (`>>=` and `>=>`), I did not pick randomly. These are the standard operators that are used all over the place for the "bind" and "compose" operations on values like Async, or Result, or AsyncResult. So if you're defining your own, stick with the "standard" operator names and other people reading your code won't be confused. **Update 2**: Here's how to read those type signatures: ``` 'a -> Async> ``` This is a function that takes type A, and returns an `Async` wrapped around a `Result`. The `Result` has type B as its success case, and type C as its failure case. ``` Async> ``` This is a value, not a function. It's an `Async` wrapped around a `Result` where type A is the success case, and type C is the failure case. So the `bind` function takes two parameters: * a function from A to an async of (either B or C)). * a value that's an async of (either A or C)). And it returns: * a value that's an async of (either B or C). Looking at those type signatures, you can already start to get an idea of what the `bind` function will do. It will take that value that's either A or C, and "unwrap" it. If it's C, it will produce an "either B or C" value that's C (and the function won't need to be called). If it's A, then in order to convert it to an "either B or C" value, it will call the `f` function (which takes an A). All this happens within an async context, which adds an extra layer of complexity to the types. It might be easier to grasp all this if you look at the [basic version of `Result.bind`](https://github.com/fsharp/fsharp/blob/e19ddca7d6049ae04cc6a827e803555285d19b26/src/fsharp/FSharp.Core/result.fs), with no async involved: ``` let bind (f : 'a -> Result<'b, 'c>) (a : Result<'a, 'c>) = match a with | Ok val -> f val | Error err -> Error err ``` In this snippet, the type of `val` is `'a`, and the type of `err` is `'c`. **Final update**: There was one comment from the chat session that I thought was worth preserving in the answer (since people almost never follow chat links). Developer11 asked, > > ... if I were to ask you what `Result.bind` in my example code maps to your approach, can we rewrite it as `create >> AsyncResult.bind update`? It worked though. Just wondering i liked the short form and as you said they have a standard meaning? (in haskell community?) > > > My reply was: > > Yes. If the `>=>` operator is properly written, then `f >=> g` will **always** be equivalent to `f >> bind g`. In fact, that's precisely the definition of the `compose` function, though that might not be immediately obvious to you because `compose` is written as `fun x -> bind g (f x)` rather than as `f >> bind g`. But those two ways of writing the compose function would be *exactly equivalent*. It would probably be very instructive for you to sit down with a piece of paper and draw out the function "shapes" (inputs & outputs) of both ways of writing compose. > > > Upvotes: 4 [selected_answer]<issue_comment>username_2: Why do you want to use Railway Oriented Programming here? If you just want to run a sequence of operations and return information about the first exception that occurs, then F# already provides a language support for this using exceptions. You do not need Railway Oriented Programming for this. Just define your `Error` as an exception: ``` exception Error of code:string * message:string ``` Modify the code to throw the exception (also note that your `create` function takes `article` but does not use it, so I deleted that): ``` let create () = async { let ds = new DataContractJsonSerializer(typeof) let request = WebRequest.Create("http://example.com") :?> HttpWebRequest request.Method <- "GET" try use response = request.GetResponse() :?> HttpWebResponse use reader = new StreamReader(response.GetResponseStream()) use memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(reader.ReadToEnd())) return ds.ReadObject(memoryStream) :?> Article with | :? WebException as e -> use reader = new StreamReader(e.Response.GetResponseStream()) use memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(reader.ReadToEnd())) return raise (Error (ds.ReadObject(memoryStream) :?> Error)) } ``` And then you can compose functions just by sequencing them in `async` block using `let!` and add exception handling: ``` let main () = async { try let! created = create () let! updated = update created let! uploaded = upload updated Debug.WriteLine(uploaded.name) with Error(code, message) -> Debug.WriteLine(code + ":" + message) } ``` If you wanted more sophisticated exception handling, then Railway Oriented Programming might be useful and there is certainly a way of integrating it with `async`, but if you just want to do what you described in your question, then you can do that much more easily with just standard F#. Upvotes: 2
2018/03/21
2,516
7,781
<issue_start>username_0: In my code I am trying to detect whether a key for example 'A' is pressed alone or is pressed with combination. I have different if statements for each. But when I press them together something weird happens. I think the problem is related to `Input.Getkey` and when I try to use `Input.GeyKeyDown` it becomes nearly impossible to press them both at the same time. How can I improve my code? It seems a common problem but I am unable to comprehend it. I want my transform to move to different location when only A is pressed and to another different location when A is pressed in combination with W or S. The result I want is in the image. When I click a&&w then generate a random Vector3 between a range like this: ``` new Vector3(Random.Range(-2.7f, -0.95f), 0, Random.Range(4.5f, 6f)); ``` Generating random location works perfectly but the only problem is when I try to press combination keys, first this runs ``` if (Input.GetKeyUp(KeyCode.W)) { activePos = new Vector3(Random.Range(0.95f, -0.95f), 0, Random.Range(4.5f, 6f)); return activePos; } ``` then this ``` if (Input.GetKey(KeyCode.A) || (Input.GetKey(KeyCode.Q) && Input.GetKey(KeyCode.A))) { activePos = new Vector3(Random.Range(-2.7f, -0.95f), 0, Random.Range(2f, 4.5f)); return activePos; } ``` and this ``` if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.A)) { activePos = new Vector3(Random.Range(-2.7f, -0.95f), 0, Random.Range(4.5f, 6f)); return activePos; } ``` Whereas I want only the last one to run. I want only this code to run when w&&a are pressed together ``` if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.A)) { activePos = new Vector3(Random.Range(-2.7f, -0.95f), 0, Random.Range(4.5f, 6f)); return activePos; } ``` [![enter image description here](https://i.stack.imgur.com/L8UfS.png)](https://i.stack.imgur.com/L8UfS.png) This is the full method: ``` public static Vector3 GetTargetPosition() { /* * near z = 1 - 2.5, key = s * center z = 2 - 4.5, key = q * far z = 4.5 - 6, key = w * very far possibly outside z = 6 - 7.5 * left x = (-2.7) to -0.95, key = a * center x = -0.95 to 0.95, key = q * right x = 0.95 to 2.7, key = d */ if (Input.GetKeyUp(KeyCode.S)) { activePos = new Vector3(Random.Range(0.95f, -0.95f), 0, Random.Range(1f, 2.5f)); return activePos; } else if (Input.GetKeyUp(KeyCode.W)) { activePos = new Vector3(Random.Range(0.95f, -0.95f), 0, Random.Range(4.5f, 6f)); return activePos; } else if (Input.GetKeyUp(KeyCode.Q)) { activePos = new Vector3(Random.Range(0.95f, -0.95f), 0, Random.Range(2f, 4.5f)); return activePos; } else if (Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.A)) { activePos = new Vector3(Random.Range(-2.7f, -0.95f), 0, Random.Range(1f, 2.5f)); return activePos; } else if (Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.D)) { activePos = new Vector3(Random.Range(0.95f, 2.7f), 0, Random.Range(1f, 2.5f)); return activePos; } else if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.A)) { activePos = new Vector3(Random.Range(-2.7f, -0.95f), 0, Random.Range(4.5f, 6f)); return activePos; } else if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.D)) { activePos = new Vector3(Random.Range(0.95f, 2.7f), 0, Random.Range(4.5f, 6f)); return activePos; } else if (Input.GetKey(KeyCode.A) || (Input.GetKey(KeyCode.Q) && Input.GetKey(KeyCode.A))) { activePos = new Vector3(Random.Range(-2.7f, -0.95f), 0, Random.Range(2f, 4.5f)); return activePos; } else if (Input.GetKey(KeyCode.D) || (Input.GetKey(KeyCode.Q) && Input.GetKey(KeyCode.D))) { activePos = new Vector3(Random.Range(0.95f, 2.7f), 0, Random.Range(2f, 4.5f)); return activePos; } else { return new Vector3(0, 0, 0); } } ```<issue_comment>username_1: I assume this function will be called in Update() function, which is executed on every frame. You don't have to use logic and A && B for the case when two keys are pressed at the same time, just define A and B case separately, and when both are called, the changes are applied **sequentially**, but very quickly, so quick that no one can detect such sequence, which meet your requirement. ``` if (Input.GetKeyUp(KeyCode.A)) {...} if (Input.GetKeyUp(KeyCode.B)) {...} // if (Input.GetKeyUp(KeyCode.A) && Input.GetKeyUp(KeyCode.A)) {...} //Avoid this! ``` Update: ``` if (Input.GetKeyUp(KeyCode.A)) { activePos += ... //Let activePos to be class level variable, no need to return; } ``` Upvotes: 1 <issue_comment>username_2: You can try setting a value with each key press, so when you press the a key it sets `bool a = true`. Then later you can check with `if (a && d)` or something similar. Upvotes: 0 <issue_comment>username_3: Try this one: ``` if ((Input.GetKey(KeyCode.S) && Input.GetKeyUp(KeyCode.Q)) || (Input.GetKey(KeyCode.Q) && Input.GetKeyUp(KeyCode.S))) { DoCode(); } ``` Upvotes: 0 <issue_comment>username_4: The problem isn't with > > if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.A)) > > > as this is perfectly fine for what you are trying to do. the problem lies with the fact that you are using a lot of if-else statements. Your code is being run sequential, meaning from top to bottom. if you hit both the keys A and W it will go through your code and the first match it will find will be > > else if (Input.GetKeyUp(KeyCode.W)) > { > activePos = new Vector3(Random.Range(0.95f, -0.95f), 0, Random.Range(4.5f, 6f)); > > > > ``` > return activePos; > } > > ``` > > since you did actually press the W, which will perform the code inside this if statement and break out of all other cases. Never reaching ``` else if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.A)) { activePos = new Vector3(Random.Range(-2.7f, -0.95f), 0, Random.Range(4.5f, 6f)); return activePos; } ``` There are multiple ways you can can go around this, each having their own pros and cons. What i would personally probably do is nest your if statements. This will mean that you will first check if key A is pressed, and inside that if statement you can do another check to see if W is also pressed, for example: > > > ``` > if(Input.GetKey(KeyCode.A)) > { > //some logic goes here for when A is pressed > if(Input.GetKey(KeyCode.W)) > { > //some logic for when both A and W are pressed > } > } > > ``` > > the pro of this is that you can do both the A and W check in the same if statement. or you could do something like this: ``` if(Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.A)) { //logic for both A And W pressed } if(Input.GetKey(KeyCode.W) && !Input.GetKey(KeyCode.A)) { //by checking if A is NOT pressed you will prevent this code from //running if you press both A and W //Logic for just W pressed } ``` in short; get rid of the entire if-else structure and just stick with the if, if for some reason you really want to stick with the if-else structure reversing the order in which you check everything will also do (e.g check for the double key presses first, and the single key presses after, since you break out of the if-else after the first positive hit) but i wouldn't recommend this approach. also you don't have to return the active pos. just setting it with = new Vector3 is all you need to do! Apologies if the formatting of the post is a bit messy, typing this quick from mobile! Upvotes: 3 [selected_answer]
2018/03/21
602
2,075
<issue_start>username_0: I am editing the file, here i can change the filename as well as i can add another file for versions, If I have chosen the file, filename edit field should be disabled immediately. I have tried this following code, but its not get disabled until i type something in filename field. My View code: ``` Choose file File Name ``` My app.js In my controller I have wrote function: ``` $scope.filechoosen = false $scope.fileNameChanged = function() { $scope.filechoosen= true } ``` Is there any mistake in my code.<issue_comment>username_1: try `ng-change` insted of `onchange` ``` ``` to ``` ``` Upvotes: 0 <issue_comment>username_2: Can you please try with $scope.$apply() inside the click function ```html Choose file File Name ``` var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.filechoosen = false $scope.fileNameChanged = function() { $scope.filechoosen= true $scope.$apply() } }); as below Upvotes: 1 <issue_comment>username_3: The user @sqren (<https://stackoverflow.com/users/434980/sqren>) has made a custom directive which will help to solve this since angularjs doesn't have any ng-change support for file. **view.html** **controller.js:** ```js app.controller('myCtrl', function($scope){ $scope.uploadFile = function(event){ var files = event.target.files; }; }); ``` **directive.js:** ```js app.directive('customOnChange', function() { return { restrict: 'A', link: function (scope, element, attrs) { var onChangeHandler = scope.$eval(attrs.customOnChange); element.on('change', onChangeHandler); element.on('$destroy', function() { element.off(); }); } }; }); ``` He has also created a [JSFiddle](http://jsfiddle.net/sqren/27ugfym6/) which help you to understand this. The answer credit goes to @sqren, I am just mentioning it over here. More information on the actual answer can be seen here - <https://stackoverflow.com/a/19647381/1723852> Upvotes: 0
2018/03/21
558
1,946
<issue_start>username_0: I gave a requirement involving SMS and AWS platform, the requirement is - users can send SMS to a mobile number and I need to store the SMS and it's metadata into AWS RDS or DynamoDB or any AWS compatible storage. These SMS will be used to populate a realtime dashboard. Anyone here came across such a scenario? or any tools or technologies I could use to resolve it? Thanks a ton for your replies, Arun<issue_comment>username_1: try `ng-change` insted of `onchange` ``` ``` to ``` ``` Upvotes: 0 <issue_comment>username_2: Can you please try with $scope.$apply() inside the click function ```html Choose file File Name ``` var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.filechoosen = false $scope.fileNameChanged = function() { $scope.filechoosen= true $scope.$apply() } }); as below Upvotes: 1 <issue_comment>username_3: The user @sqren (<https://stackoverflow.com/users/434980/sqren>) has made a custom directive which will help to solve this since angularjs doesn't have any ng-change support for file. **view.html** **controller.js:** ```js app.controller('myCtrl', function($scope){ $scope.uploadFile = function(event){ var files = event.target.files; }; }); ``` **directive.js:** ```js app.directive('customOnChange', function() { return { restrict: 'A', link: function (scope, element, attrs) { var onChangeHandler = scope.$eval(attrs.customOnChange); element.on('change', onChangeHandler); element.on('$destroy', function() { element.off(); }); } }; }); ``` He has also created a [JSFiddle](http://jsfiddle.net/sqren/27ugfym6/) which help you to understand this. The answer credit goes to @sqren, I am just mentioning it over here. More information on the actual answer can be seen here - <https://stackoverflow.com/a/19647381/1723852> Upvotes: 0
2018/03/21
883
3,109
<issue_start>username_0: My current configuration in gradle file is ``` sourceCompatibility = 1.7 targetCompatibility = 1.7 ``` this specification make my project specific to java 1.7. **My requirement is that i should be able to build my project for different java version like for both java 1.7 and java 1.8** PS: like profile building in gradle where we can specify different java version.<issue_comment>username_1: Gradle uses whatever JDK it finds in the PATH or JAVA\_HOME. So if you remove sourceCompatibility and targetCompatibility it should build the project with the Java version used on the machine where the project runs. Of course, this does mean that you shouldn't have constructs like lambdas in the code or compilation on Java 7 will fail. You should also be aware that starting with Gradle 5 support for Java 7 will be dropped and it will run only with Java 8 (or newer). Another way to do it is to specify the JDK at runtime, see this [link](https://stackoverflow.com/questions/18487406/how-do-i-tell-gradle-to-use-specific-jdk-version?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) If you want to build for multiple Java versions at the same time, you can use something like this: ``` task compile7(type: JavaCompile) { source = fileTree(dir: 'src', include: '**/*.java') classpath = sourceSets.main.compileClasspath sourceCompatibility = 1.7 targetCompatibility = 1.7 destinationDir = file('build/java7') } task jar7(type: Jar, dependsOn: compile7) { from('build/java7') archiveName = 'project-JDK7.jar' destinationDir = file('build/jars') } task compile8(type: JavaCompile) { source = fileTree(dir: 'src', include: '**/*.java') classpath = sourceSets.main.compileClasspath sourceCompatibility = 1.8 targetCompatibility = 1.8 destinationDir = file('build/java8') } task jar8(type: Jar, dependsOn: compile8) { from('build/java8') archiveName = 'project-JDK8.jar' destinationDir = file('build/jars') } ``` You can call `gradle jar7 jar8` to build jars for both java versions you want. Of course, the code above can be improved to parametrize the operations, like this: ``` ext.javaVer = project.hasProperty('javaVer') ? project.getProperty('javaVer') : '1.7' task compileJ(type: JavaCompile) { source = fileTree(dir: 'src', include: '**/*.java') classpath = sourceSets.main.compileClasspath sourceCompatibility = javaVer targetCompatibility = javaVer destinationDir = file('build/' + javaVer) } task jarJ(type: Jar, dependsOn: compileJ) { from('build/' + javaVer) archiveName = 'project-' + javaVer + '.jar' destinationDir = file('build/jars') } ``` Using this format you would call `gradle jarJ -P javaVer=1.8` and `gradle jarJ` to build for Java 8 and Java 7. Upvotes: 2 <issue_comment>username_2: This is how i had solved it ``` ext.javaVer = project.hasProperty('javaVer') ? project.getProperty('javaVer') : '1.7' sourceCompatibility = javaVer targetCompatibility = javaVer ``` while building project ``` gradle build -P javaVer=1.8 ``` Upvotes: 3 [selected_answer]
2018/03/21
1,044
3,455
<issue_start>username_0: I am reading Excel sheet using Apache POI and writing it to a PDF using iText library.This has been achieved successfully but I am getting default black border for every cell that I write to PDF. So I need to get the cell border color using Apache POI which can be achieved using CellStyle class method getBottomBorderColor() which returns a short value.However I need a way to convert this value to RGB value so that while writing cell to PDF I can apply that RGB color value to the cell border.<issue_comment>username_1: you can archive this by using this color class ``` CTScRgbColor scrgb = (CTScRgbColor)ch; int r = scrgb.getR(); int g = scrgb.getG(); int b = scrgb.getB(); color = new Color(255 * r / 100000, 255 * g / 100000, 255 * b / 100000); ``` Upvotes: -1 <issue_comment>username_2: The `short` value from [CellStyle.getBottomBorderColor](https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/CellStyle.html#getBottomBorderColor--) is an index of the color in the color palette of the workbook. This is an olld approach for storing colors from the old binary `*.xls` `Excel` format. So in `apache poi` there is only [HSSFPalette](https://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFPalette.html) which only should be used in `HSSF` and not more be used in `XSSF`. In newer `*.xlsx` `Excel` formats, the color will either be stored directly as hex value or as reference to a theme color. So for `XSSF` there is [XSSFCellStyle.getBottomBorderXSSFColor](https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFCellStyle.html#getBottomBorderXSSFColor--) to get that color directly and not via index. So unfortunately we have to differ both aproaches dependent on the kind of `Excel` workbook. Example: ``` import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.*; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.HSSFColor; import java.io.FileInputStream; class ExcelCellBorderColor{ public static void main(String[] args) throws Exception { Workbook wb = WorkbookFactory.create(new FileInputStream("ExcelCellBorderColor.xlsx")); //Workbook wb = WorkbookFactory.create(new FileInputStream("ExcelCellBorderColor.xls")); String strrgb; Sheet sheet = wb.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { CellStyle style = cell.getCellStyle(); if (style instanceof XSSFCellStyle) { XSSFColor xssfcolor = ((XSSFCellStyle)style).getBottomBorderXSSFColor(); if (xssfcolor != null) { byte[] brgb = xssfcolor .getRGB(); strrgb = "R:"+String.format("%02X", brgb[0])+",G:"+String.format("%02X", brgb[1])+",B:"+String.format("%02X", brgb[2]); System.out.println("Cell " + cell.getAddress() + " has border bottom color: " + strrgb); } } else if (style instanceof HSSFCellStyle) { short colorindex = ((HSSFCellStyle)style).getBottomBorderColor(); HSSFPalette palette = ((HSSFWorkbook)wb).getCustomPalette(); HSSFColor hssfcolor = palette.getColor(colorindex); if (hssfcolor != null) { short[] srgb = hssfcolor.getTriplet(); strrgb = "R:"+String.format("%02X", srgb[0])+",G:"+String.format("%02X", srgb[1])+",B:"+String.format("%02X", srgb[2]); System.out.println("Cell " + cell.getAddress() + " has border bottom color index: " + colorindex + ". This is " + strrgb); } } } } wb.close(); } } ``` Upvotes: 1
2018/03/21
252
833
<issue_start>username_0: I have a working base. How can I remove the attribute of uniqueness for one of the fields? `connectId : {type : String, index: true, unique: true},` I need to remove `unique: true` `connectId : {type : String, index: true},` [![enter image description here](https://i.stack.imgur.com/fxRWq.png)](https://i.stack.imgur.com/fxRWq.png) Thanks<issue_comment>username_1: You would just need to use the $unset operator: ``` db.collection.update({},{$unset: {"connectId.unique": ""}}); ``` Please find below more documentation on the $unset operator [here](https://docs.mongodb.com/manual/reference/operator/update/unset/ "here") Upvotes: 1 <issue_comment>username_2: my solution ``` db.connections.dropIndex("connectId_1") db.connections.createIndex({connectId: 1}, {background: "true"}) ``` Upvotes: 0
2018/03/21
540
1,975
<issue_start>username_0: I am setting the store value to a variable using getters and when I later change the variable value, vuex store value is getting updated. Below given is my code ``` let startdate = this.$store.getters.getDateRange.start let endDate = this.$store.getters.getDateRange.end let compareStart = startdate compareStart.setDate(startdate.getDate() - 7) let compareEnd = endDate compareEnd.setDate(endDate.getDate() + 7) ``` While setDate function is executed, the store value is changed to 'compareEnd' value. Why is this happening? Is this because it's an object reference? If so what is the work around?<issue_comment>username_1: For time being i solved the issue. I was passing an object from the store and hence was updating the value. So i changed the code a little bit. ``` let startdate = this.$store.getters.getDateRange.start let endDate = this.$store.getters.getDateRange.end let compareStart = new Date(startdate.getUTCFullYear(), startdate.getUTCMonth(), startdate.getUTCDate()) compareStart.setDate(startdate.getDate() - 7) let compareEnd = new Date(endDate.getUTCFullYear(), endDate.getUTCMonth(), endDate.getUTCDate()) compareEnd.setDate(endDate.getDate() + 7) ``` I'm not sure is this the best way or not. Upvotes: 0 <issue_comment>username_2: Great Question! This is a classic Javascript case of Pass by Reference and Pass by Value. In your case the startDate/endDate becomes a reference of this.$store.getters.getDateRange.start / end and thus whenever you update the startDate/endDate it changes the one at the store. Looks to me your store variable is a JS date object. Try the following. ``` //Let's Breakdown References let startdate = new Date(this.$store.getters.getDateRange.start.valueOf()) let endDate = new Date(this.$store.getters.getDateRange.end.valueOf()) ``` Learn More about JS variables Here [<https://hackernoon.com/javascript-reference-and-copy-variables-b0103074fdf0]> Upvotes: -1
2018/03/21
484
1,345
<issue_start>username_0: Can someone suggest the best way to merge two lists in scala so that the resulting list will only contain matching elements in both lists? Example: ``` List[Int] = List(10,20,30) List[Int] = List(30,50) Result: List[Int] = List(30) ```<issue_comment>username_1: **And condition (nested for loop)** You can use *nested for loops* as ``` val list1 = List(10, 20, 30) val list2 = List(30, 50) val result = for(value1 <- list1; value2 <- list2; if value1 == value2) yield value1 println(result) ``` which would print `List(30)` **Intersect() (built-in function)** You can use `intersect` function which will give you *common values in both lists* as ``` println(list1.intersect(list2)) ``` which should give you `List(30)` Upvotes: 3 [selected_answer]<issue_comment>username_2: Besides the intersect solution, you can also use an `filter` with a `contains` inside ``` l1.filter(l2.contains(_)) ``` With your input: ``` l1: List[Int] = List(10, 20, 30) l2: List[Int] = List(30, 50) ``` Result will be: ``` List[Int] = List(30) ``` Upvotes: 0 <issue_comment>username_3: Similar functionality can be achieved with `dropwhile` or `takeWhile` also ``` scala> l2.takeWhile(l1.contains(_)) res8: List[Int] = List(30) scala> l1.dropWhile(!l2.contains(_)) res10: List[Int] = List(30) ``` Upvotes: 0
2018/03/21
687
2,452
<issue_start>username_0: I am creating employee management software in python in flask environement by referring this code <https://github.com/littlewonder/squadmaster> i have installed pip , flask an other relevant libraries .i have also created virtal environment .I put the project folder inside the flask as well . folder structure in side flask folder is like this [![enter image description here](https://i.stack.imgur.com/VOzWu.png)](https://i.stack.imgur.com/VOzWu.png) when i tried to tun run.py . it gives me error ``` app.config.from_object(app_config[config_name]) KeyError: None ``` this is my run.py file ``` import os from app import create_app config_name = os.getenv('FLASK_CONFIG') app = create_app(config_name) if __name__ == '__main__': app.run() ``` i have faced similar question [Flask does not load configuration](https://stackoverflow.com/questions/34811823/flask-does-not-load-configuration) i have implemented its solution and use these strings ``` app.config.from_object('myapplication.default_settings') app.config.from_object('my_app.config.{}'.format(config_name)) ``` I have set FLASK\_CONFIG as in upper as documented I have setup the FLASK\_CONFIG as environment variable in system build path . but it results me to error as KeyError = "full path" . i have also tried to set FLASK\_CONFIG ='development' and FLASK\_CONFIG =DevelopmentConfig as mentioned in config.py ``` app_config = { 'development': DevelopmentConfig, 'production': ProductionConfig } ``` what else can i tried to get a hint whats going wrong . need some suggestion<issue_comment>username_1: The first problem can be solved with a reasonable default: ``` config_name = os.getenv('FLASK_CONFIG') or 'default' ``` or just `os.getenv('FLASK_CONFIG', 'default')`, where the meaning of the default can be set in config.app\_config ``` app_config = { 'development': DevelopmentConfig, 'production': ProductionConfig, 'default': ProductionConfig } ``` The `app_config` maps a name to an object with configuration. A reference ina string form is also allowed, but you can pass the object directly to `.from_object`): ``` app.config.from_object(app_config[config_name]) ``` The configuration data stored e.g. `DevelopmentConfig` must contain the data items as its attributes. It can be a class. Upvotes: 2 <issue_comment>username_2: For Linux first type: export FLASK\_ENV=development Upvotes: 1
2018/03/21
1,441
5,533
<issue_start>username_0: I am a fairly new programmer in Java and am currently learning about how to incorporate multiple methods in one code. The goal of this practice activity is to use several different methods to: -Create two arrays (one for employee names and another for how much that employee sold) -Find the average of total sales -Find the highest sale number -Find the name of the Employee(s) with the highest sale count (and print "hooray" for every employee that had the highest sale count) ``` import java.util.*; public class MethodActivity{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); String[] names={"Employee A", "Employee B", "Employee C", "Employee D", "Employee E", "Employee F", "Employee G", "Employee H", "Employee I", "Employee J"}; System.out.print("Enter the sales numbers, in dollars, for each employee: "); int num1 = sc.nextInt(); int num2 = sc.nextInt(); int num3 = sc.nextInt(); int num4 = sc.nextInt(); int num5 = sc.nextInt(); int num6 = sc.nextInt(); int num7 = sc.nextInt(); int num8 = sc.nextInt(); int num9 = sc.nextInt(); int num10 = sc.nextInt(); double[] sales={num1, num2, num3, num4, num5, num6, num7, num8, num9, num10}; return double[] sales; return String[] names; } public static double getAverage(double[] sales){ double average=(num1+num2+num3+num4+num5+num6+num7+num8+num9+num10)/10; return average; } public static int getHighestSale(double[] sales){ double highest = sales[0]; int locationOfHighest=0; if(sales[1]>highest){ highest=sales[1]; locationOfHighest=1; }else if(sales[2]>highest){ highest=sales[2]; locationOfHighest=2; }else if(sales[3]>highest){ highest=sales[3]; locationOfHighest=3; }else if(sales[4]>highest){ highest=sales[4]; locationOfHighest=4; }else if(sales[5]>highest){ highest=sales[5]; locationOfHighest=5; }else if(sales[6]>highest){ highest=sales[6]; locationOfHighest=6; }else if(sales[7]>highest){ highest=sales[7]; locationOfHighest=7; }else if(sales[8]>highest){ highest=sales[8]; locationOfHighest=8; }else{ highest=sales[9]; locationOfHighest=9; } return highest; } public static String showName(String[] names){ String nameOfHighest = ""; String hooray = ""; for (int i = 0; i ``` However, when I run the program, I got these errors. The thing is, I don't really understand what they mean: ``` MethodActivity.java:20: error: '.class' expected return double[] sales; ^ MethodActivity.java:21: error: '.class' expected return String[] names; ^ MethodActivity.java:75: error: expected public static void (String[] args){ ``` I would really appreciate if someone could clarify what these mean, since I'm still quite confused by the concept of a multi method code. And, if you could, maybe point out any other issues or fixable elements in my code (since I know my code might look pretty sloppy to someone with programming experience and I could really use some pointers). Thank you for your time.<issue_comment>username_1: You need to remove this both returns. There are two problem in your code: 1) java method can have only one return statement. 2) it is main method and because of it returns void type. void means no return type. [![enter image description here](https://i.stack.imgur.com/vVauF.png)](https://i.stack.imgur.com/vVauF.png) Upvotes: 1 <issue_comment>username_2: Rather using separate method for printing "public static void (String[] args), print those in main method itself. Also refer answer by iMBMT. Upvotes: 0 <issue_comment>username_3: import java.util.Scanner; public class MethodActivity { ``` public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter Number of employees : "); int totalEmployeeCount = sc.nextInt(); System.out.println("## totalEmployeeCount : " + totalEmployeeCount); String[] employeeNames = new String[totalEmployeeCount]; int[] employeeSoldCount = new int[totalEmployeeCount]; String name; int count; for (int index = 0; index < totalEmployeeCount; index++) { System.out.print("Enter employee name : "); name = sc.next(); System.out.print("Enter employee sale count : "); count = sc.nextInt(); employeeNames[index] = name; employeeSoldCount[index] = count; } System.out.println("---------------- Pringting all info ----------------"); for (int i = 0; i < employeeNames.length; i++) { System.out.println("name : " + employeeNames[i] + " & sale count : " + employeeSoldCount[i]); } findTheAverageOfTotalSales(employeeSoldCount); findTheHighestSaleNumber(employeeSoldCount); } private static void findTheAverageOfTotalSales(int[] employeeSoldCount) { for (int saleCount : employeeSoldCount) { System.out.println("Write your own code ..."); } } private static void findTheHighestSaleNumber(int[] employeeSoldCount) { for (int saleCount : employeeSoldCount) { System.out.println("Write your own code ..."); } } ``` } Upvotes: 0
2018/03/21
425
1,305
<issue_start>username_0: I have created a login page but its not responsive and for achieving that I have messed up my entire design. ``` .box { position: center; top: 17; left: 17; } .logo { position: absolute; top:50px; left: 100px; border-right: 2px solid gray; } ADMIN PANEL LOGIN ----------------- Email: Submit ![](back_box.png) ![](logo_written.png) ``` i have added bootstrap classes too but i am unable to achieve my goal of responsive design<issue_comment>username_1: For Bootstrap you need to add bootstrap file source just add this to your head section. ``` ``` Upvotes: 2 <issue_comment>username_2: just add one link cdn of bootstrap.css.. ```html .box { position: center; top: 17; left: 17; } .logo { position: absolute; top:50px; left: 100px; border-right: 2px solid gray; } ADMIN PANEL LOGIN ----------------- Email: Submit ![](back_box.png) ![](logo_written.png) ``` Upvotes: 0 <issue_comment>username_3: Add this meta tag to your head tag ``` ``` after that you can able to write media query for multiple devices like mobile & tablates... ``` @media (max-width: 767px) { /* write css for mobile here */ } @media (min-width: 768px) and (max-width: 1024px) { /* write css for tablate here */ } ``` Upvotes: 0
2018/03/21
1,365
4,507
<issue_start>username_0: I want to print Hello World `n**n` times without calculating the value of `n**n` in python. eg, if n is 2, it should print `'Hello World'` 4 times. if n is 3 it should print `'Hello World'` 27 times and so on. I am allowed to use loops and recursion but now allowed to use any inbuilt function or calculate the value of n \*\*n and print that many times. Thank you in advance.<issue_comment>username_1: First: ``` def compose(f, g): def wrapper(x): return f(g(x)) wrapper.__name__ = f'compose({f.__name__}, {g.__name__})' return wrapper def ntimes(n): def wrap(func): if n == 1: return func return compose(func, ntimes(n-1)(func)) return wrap ``` That should be obvious, right? `ntimes(3)` is a function that composes any function with itself 3 times, so `ntimes(3)(func)(x)` is `func(func(func(x)))`. And now, we just need to call `ntimes` on `ntimes` with the same `n` at both levels. I could write an `nntimes` function that does that the same way `ntimes` did, but for variety, let's make it flatter: ``` def nntimes(n, func, arg): f = ntimes(n) return f(f)(func)(arg) ``` So `nntimes(n, func, arg)` calls `ntimes(n)` on `ntimes(n)`, which gives you a function that composes its argument `n**n` times, and then calls that function on `arg`. And now we just need a function to pass in. `print` doesn't quite work, because it returns `None`, so you can't compose it with itself. So: ``` def printret(x): print(x, end=' ') return x ``` And now we just call it: ``` >>> nntimes(2, printret, 'Hi') hi hi hi hi >>> nntimes(3, printret, 'Hi') hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi ``` --- If you still can't understand what's happening, maybe this will help. Let's do something a bit simpler than the general `nntimes` and just hardcode three, and then print out the composition: ``` >>> thrice = ntimes(3) >>> print(thrice(thrice)(printret).__name__) compose(compose(compose(printret, compose(printret, printret)), compose(compose(printret, compose(printret, printret)), compose(printret, compose(printret, printret)))), compose(compose(compose(printret, compose(printret, printret)), compose(compose(printret, compose(printret, printret)), compose(printret, compose(printret, printret)))), compose(compose(printret, compose(printret, printret)), compose(compose(printret, compose(printret, printret)), compose(printret, compose(printret, printret)))))) ``` All those parentheses! It's like I've died and gone to Lisp! --- If you read up on [Church numerals](https://en.wikipedia.org/wiki/Church_encoding#Church_numerals), you'll see that I've sort of cheated here. Write up the trivial functions to Church-encode a number and to exponentiate two Church numerals, then compare it to what my code does. So, have I really avoided calculating the value of `n**n`? --- Of course you can do this a whole lot more simply with a simple flat recursion and no higher-order functions, or with `itertools` (well, you're not allowed to use builtins, but everything in itertools comes with source and/or or a "roughly equivalent" function in the docs, so you can just copy that). But what's the fun in that? After all, if you actually wanted a Pythonic, or simple, or efficient version, you'd just loop over `range(n**n)`. I assume the point of this interview question is to force you to think outside the Pythonic box. Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` >>> def new(number,loop): ... if loop == 1: ... return number ... else: ... return number * new(number,loop-1) ... >>> a = new(3,3) >>> print a 27 >>> print "Hello "*a Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello ``` > > > > > > > > > > > > > > > > > > > > > > > > Upvotes: 0 <issue_comment>username_3: Just for fun and to give an instructive answer you could do it this way with a very simple recursive function without calculating `n**n`: ``` def fun(n, level): if (level == n): print('Hello World') return for i in range (n): fun(n, level+1) ``` And if you try ``` fun(2,0) ``` you get ``` Hello World Hello World Hello World Hello World ``` the same works for `fun(3,0)`... Hope that helps. Is a rather trivial solution. @username_1 wonderful solution! Best, username_3 Upvotes: 0
2018/03/21
1,230
4,641
<issue_start>username_0: I wrote a script to backup the first argument that the user input with the script: ``` #!/bin/bash file=$1/$(date +"_%Y-%m-%d").tar.gz if [ $1 -eq 0 ] then echo "We need first argument to backup" else if [ ! -e "$file" ]; then tar -zcvf $1/$(date +"_%Y-%m-%d").tar.gz $1 else exit fi fi ``` The result that i want from the script is 1. backup folder the first argument that user input 2. save the backup file into folder that user input with date time format. but the script is not running when I try to input the argument. What's wrong with the script?<issue_comment>username_1: The backup part of your script seem to be working well, but not the part where you check that `$1` is not empty. Firstly you would need quotes around `$1`, to prevent that it expends to nothing. Without the quotes the shell sees it as ``` if [ -eq 0 ] ``` and throws an error. Secondly it would be better to use the `-z` operator to test if the variable exists: ``` if [ -z "$1" ] ``` Now you script should work as expected Upvotes: 2 <issue_comment>username_2: I see several problems: * As username_1 pointed out, the test for whether an argument was passed is wrong. Use `if [ -z "$1" ]` to check for a missing/blank argument. * Also, it's almost always a good idea to wrap variable references in double-quotes, as in `"$1"` above. You do this in the test for whether `$file` exists, but not in the `tar` command. There are places where it's safe to leave the double-quotes off, but the rules are complicated; it's easier to just *always* double-quote. * In addition to checking whether `$1` was passed, I'd recommend checking whether it corresponds to a directory (or possibly file) that actually exists. Use something like: ``` if [ -z "$1" ]; then echo "$0: We need first argument to backup" >&2 elif [ ! -d "$1" ]; then echo "$0: backup source $1 not found or is not a directory" >&2 ``` BTW, note how the error messages start with `$0` (the name the script was run as) and are directed to error output (the `>&2` part)? These are both standard conventions for error messages. * This isn't serious, but it really bugs me: you calculate `$1/$(date +"_%Y-%m-%d").tar.gz`, store it in the `file` variable, test to see whether something by that name exists, and then *calculate it again* when creating the backup file. There's no reason to do that; just use the `file` variable again. The reason it bugs me is partly that it violates the DRY ("Don't Repeat Yourself") principle, partly that if you ever change the naming convention you have to change it consistently in two places or the script will not work, and partly because in principle it's possible that the script will run just at midnight, and the first calculation will get one day and the second will get a different day. * Speaking of naming conventions, there's a problem with how you store the backup file. If you put it in the directory that's being backed up, then the first day you'll get a .tar.gz file containing the previous contents of the directory. The second day you'll get a file containing the regular contents *plus the first backup file*. Thus, the second day's backup will be about twice as big. The third day's backup will contain the regular contents, plus the first two backup files, so it'll be four times as big. And the fourth day's will be eight times as big, then 16 times, then 32 times, etc. You need to either store the backup file somewhere *outside* the directory being backed up, or add something like `--exclude="*.tar.gz"` to the arguments to `tar`. The disadvantage of the `--exclude` option is that it may exclude other .tar.gz files from the backup, so I'd really recommend the first option. And if you followed my advice about using `"$file"` everywhere instead of recalculating the name, you only need to make a change in one place to change where the backup goes. One final note: run your scripts through [shellcheck.net](http://www.shellcheck.net). It'll point out a lot of common errors and bad practices before you discover them the hard way. Here's a corrected version of the script (storing the backup in the directory, and excluding .tar.gz files; again, I recommend the other option): ``` #!/bin/bash file="$1/$(date +"_%Y-%m-%d").tar.gz" if [ -z "$1" ]; then echo "$0: We need first argument to backup" >&2 elif [ ! -d "$1" ]; then echo "$0: backup source $1 not found or is not a directory" >&2 elif [ -e "$file" ]; then echo "$0: A backup already exists for today" >&2 else tar --exclude="*.tar.gz" -zcvf "$file" "$1" fi ``` Upvotes: 1
2018/03/21
392
1,572
<issue_start>username_0: Is there a good way to receive information when customer makes an **order**? Judging from the documentation, there isn't. I know there are some apps related to managing payments on Etsy, and I believe they would depend on order feed. If Etsy does not provide such feed, how would you solve this? My first idea is to periodically poll the API and request the **orders**. From there, understand if new order/s happened. Your help is appreciated.<issue_comment>username_1: Not the best answer, but I'm trying to do the same thing right now. What I'm doing is collecting the transaction ID from the email associated with the Etsy account. With the transaction ID you can request for the details from Etsy. I'm still trying to figure how to do that myself though. Upvotes: 0 <issue_comment>username_2: Currently, there is **no** straight forward, documented way to subscribe to the "new order created" event. I was hoping this would be one of the must have features on the new API v3, but unfortunately it isn't implemented so far. Upvotes: 1 [selected_answer]<issue_comment>username_3: FYI see <https://github.com/etsy/open-api/issues/28> - [FEATURE] New real time feeds/suscriptions #28 Doesn't seem to be implemented yet, but that's probably the place to track it. Upvotes: 2 <issue_comment>username_4: I was trying something like this as well, but so far creating a sync request to call the <https://developers.etsy.com/documentation/reference/#operation/getShopReceipts> every time I need the orders data updated (before shipment) Upvotes: 0
2018/03/21
552
2,215
<issue_start>username_0: I am currently using batch files to run a set of simulations. Each line in the batch file reads: ``` "filepath\program.exe" "filepath\simulation.file" ``` The quotation marks exist to bound any spaces that exist within the file paths. Without any spaces in the file paths, the quotation marks can be removed. When I run the batch file through PowerShell, using the following command, it works fine: ``` .\batch.bat ``` The executable is run and the output is written to the host, as if I was running the same batch file in cmd. However, I want to ditch the batch files and run the command directly through PowerShell. When I run the following, I get the program to execute, though it doesn't run properly and I don't get anything written to host. It also appears to hang until I use Ctrl+C to cancel. ``` & "filepath\program.exe" "filepath\simulation.file" ``` Could you please help me with the following? * Any resources discussing how PowerShell executes batch files. * How to run an executable through PowerShell without using cmd or a batch file and have it write to host.<issue_comment>username_1: Not the best answer, but I'm trying to do the same thing right now. What I'm doing is collecting the transaction ID from the email associated with the Etsy account. With the transaction ID you can request for the details from Etsy. I'm still trying to figure how to do that myself though. Upvotes: 0 <issue_comment>username_2: Currently, there is **no** straight forward, documented way to subscribe to the "new order created" event. I was hoping this would be one of the must have features on the new API v3, but unfortunately it isn't implemented so far. Upvotes: 1 [selected_answer]<issue_comment>username_3: FYI see <https://github.com/etsy/open-api/issues/28> - [FEATURE] New real time feeds/suscriptions #28 Doesn't seem to be implemented yet, but that's probably the place to track it. Upvotes: 2 <issue_comment>username_4: I was trying something like this as well, but so far creating a sync request to call the <https://developers.etsy.com/documentation/reference/#operation/getShopReceipts> every time I need the orders data updated (before shipment) Upvotes: 0
2018/03/21
453
1,634
<issue_start>username_0: `Statement.excecuteQuery()` is taking too much time, no matter what the query is. ``` athenaQuery = "SELECT DISTINCT date " + "FROM sid.lvmh_shareofshelf_new_cat_all_dod "+ "where scope='PCD' and date!='' and country='" + countryName+ "' " + "and rname='" + rname + "' and top_category_lvmh='" + top_category_lvmh + "' ORDER BY date DESC"; stmt = conn.createStatement(); long startTime = System.nanoTime(); rs = stmt.executeQuery(athenaQuery); long endTime = System.nanoTime(); System.out.println("Total time taken : "+ (endTime - startTime)); ``` Time taken was 2776930359 nano seconds (2.776930359seconds)<issue_comment>username_1: I don't know internal structure of your project. I suggest few things that will help you. * Create prepare statement instead of its compile every time. Prepare query with parameter. This is syntax level optimization you can do. * Where clause parameter every time you want then you can create index of it. This is database level optimization. Than try and see is performance improve!! Upvotes: 1 <issue_comment>username_2: I checked Athena DB driver, <https://s3.amazonaws.com/athena-downloads/drivers/AthenaJDBC41-1.1.0.jar> it has com.amazonaws.athena.jdbc.AthenaConnection class which implements java.sql.Connection interface from JDBC API. it has all overloaded methods of prepareStatement promised by JDBC. I assume you already know benefits of using Prepared statement. In you query in Where clause you date != '' Is it Character data type ? you may try > > date is not null > > > Upvotes: 0
2018/03/21
585
2,079
<issue_start>username_0: I want to search for a specific record in database and show it on html page. I have inserted a search bar with a search button. I want to enter let's say Student Name and view the record of that student in an html table. But it's not working, It shows nothing in the table. Here is the code for search: ```html php include("connection.php"); if (isset($_POST['search'])) { $valueToSearch=$_POST['valueToSearch']; $query="SELECT * FROM 'table_name' WHERE Student_Name LIKE '%".$valueToSearch."%"; $search_result=filterTable($query); } else{ $query="SELECT * FROM 'table_name'"; $search_result=filterTable($query); } function filterTable($query) { $connect=@mysql_connect("localhost","root","","db"); $filter_Result=@mysql_query($connect,$query); return $filter_Result; } ? Search Record table,tr,th,td { border:1px solid black; } | Id | First Name | Last Name | Age | | --- | --- | --- | --- | php while($row = mysqli\_fetch\_array($search\_result)):?| php echo $row['id'];? | php echo $row['fname'];? | php echo $row['lname'];? | php echo $row['age'];? | php endwhile;? ```<issue_comment>username_1: I don't know internal structure of your project. I suggest few things that will help you. * Create prepare statement instead of its compile every time. Prepare query with parameter. This is syntax level optimization you can do. * Where clause parameter every time you want then you can create index of it. This is database level optimization. Than try and see is performance improve!! Upvotes: 1 <issue_comment>username_2: I checked Athena DB driver, <https://s3.amazonaws.com/athena-downloads/drivers/AthenaJDBC41-1.1.0.jar> it has com.amazonaws.athena.jdbc.AthenaConnection class which implements java.sql.Connection interface from JDBC API. it has all overloaded methods of prepareStatement promised by JDBC. I assume you already know benefits of using Prepared statement. In you query in Where clause you date != '' Is it Character data type ? you may try > > date is not null > > > Upvotes: 0
2018/03/21
1,424
4,787
<issue_start>username_0: Here is an [discussion on stackoverflow](https://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-const-cast-and-reinterpret-cast-be-used/332086#332086) of the four kinds of explicitly cast. But I've come across a question in the most-voted answer. Quoted from the most-voted wiki answer: > > `static_cast` can also cast through inheritance hierarchies. It is unnecessary when casting upwards (towards a base class), but when casting downwards it can be used as long as it doesn't cast through `virtual` inheritance. It does not do checking, however, and **it is undefined behavior to `static_cast` down a hierarchy to a type that isn't actually the type of the object**. > > > But in [cppref](http://en.cppreference.com/w/cpp/language/static_cast),I read something less severely: `static_cast < new_type > ( expression )` > > If new\_type is a pointer or reference to some class D and the type of expression is a pointer or reference to its non-virtual base B, `static_cast` performs a downcast. This downcast is ill-formed if B is ambiguous, inaccessible, or virtual base (or a base of a virtual base) of D. Such `static_cast` **makes no runtime checks** to ensure that the object's runtime type is actually D, and **may only be used safely** if this precondition is guaranteed by other means. > > > So in cppref it does not says **undefined behavior**,but instead less severely as **not safe** . So when I do something like: ``` class A{virtual foo(){}}; class B:public A{}; class C:public B{}; int main() { C*pc=new C; A*pa=static_cast(pc);//Ok,upcast. B\*pb=static\_cast(pa);//downcast,\*\*is it undefined or just not safe?\*\* C\* pc1=static\_cast(pb);//downcast back to C; } ``` One more question,if it's not UB,is it UB to dereference `pb` ?<issue_comment>username_1: It's well defined behavior. > > A prvalue of type “pointer to *cv1* `B`,” where `B` is a class type, can be converted to a prvalue of type “pointer > to *cv2* `D`,” where `D` is a class derived (Clause 10) from `B`, if a valid standard conversion from “pointer to `D`” > to “pointer to `B`” exists (4.10), *cv2* is the same cv-qualification as, or greater cv-qualification than, *cv1*, and > `B` is neither a virtual base class of `D` nor a base class of a virtual base class of `D`. The null pointer value (4.10) > is converted to the null pointer value of the destination type. **If the prvalue of type “pointer to *cv1* `B`” points > to a `B` that is actually a subobject of an object of type `D`, the resulting pointer points to the enclosing object > of type `D`**. Otherwise, the behavior is undefined. > > > (C++14 [expr.static.cast] (§5.9) ¶11, emphasis added) `pa` points to an object of type `A` which is actually a subobject of a `B`, so the second cast is fine and the result points to a valid `B`. Your third cast is OK for the same reason (`pb` points to a `B` subobject of a `C`). The "not safe" bit expressed by cppreference is about the fact that there are no safety nets here: you have to know by your own means if the actual dynamic type of the pointed object is compatible with the cast you ask for; if you get it wrong there's no `std::bad_cast` or `nullptr` - you get bad old undefined behavior. Upvotes: 2 <issue_comment>username_2: cppreference is written in English with the intent to convey good understanding, it's not actually specification. But I have no problem with its wording here: > > Such `static_cast` makes no runtime checks to ensure that the object's runtime type is actually D, and may only be used safely if this precondition is guaranteed by other means. > > > If you guarantee the precondition, it's fine. If you don't guarantee the precondition, then your code isn't safe. What does it mean for code to not be safe? Its behavior isn't defined. The actual specification uses [this wording](http://eel.is/c++draft/expr.static.cast#11): > > If the prvalue of type “pointer to *cv1* `B`” points to a `B` that is actually a subobject of an object of type `D`, the resulting pointer points to the enclosing object of type `D`. Otherwise, the behavior is undefined. > > > --- Either way, in your example, all of your casts are valid. ``` B*pb=static_cast(pa);//downcast,\*\*is it undefined or just not safe?\*\* ``` You're missing the condition. A downcast isn't undefined behavior, in of itself. It's only undefined behavior if there isn't actually an object of derived type there. And in this case `pa` is pointing to a `C`, which is a `B`, so the cast to a `B` is safe. This, however, is not: ``` struct B { }; struct D1 : B { }; struct D2 : B { }; B* p = new D1; static_cast(p); // undefined behavior, no D2 object here ``` Upvotes: 4 [selected_answer]
2018/03/21
377
1,318
<issue_start>username_0: What's the best library for laravel to use when it comes to exporting data to an excel file ? something that uses a template would be much better.<issue_comment>username_1: [Laravel Excel](https://laravel-excel.maatwebsite.nl/docs/3.0/getting-started/installation) if you need to add dropdown in your excel sheet [PhpSpreadsheet](https://phpspreadsheet.readthedocs.io) would a good choice over [Laravel Excel](https://laravel-excel.maatwebsite.nl/docs/3.0/getting-started/installation) For Laravel Excel you can simply ``` Excel::loadView('folder.file', $data) ->setTitle('FileName') ->sheet('SheetName') ->mergeCells('A2:B2') ->export('xls'); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Use maatwebsite to Create and import Excel, CSV and PDF files Add this lines to your composer.json: ``` "require": { "maatwebsite/excel": "~2.1.0" } ``` After updating composer, add the ServiceProvider to the providers array in config/app.php ``` Maatwebsite\Excel\ExcelServiceProvider::class, ``` You can use the facade for shorter code. Add this to your aliasses: ``` 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ``` To publish the config settings in Laravel 5 use: ``` php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" ``` Upvotes: 0
2018/03/21
624
1,821
<issue_start>username_0: I have a data file as below ``` TOTALUNITS TOTALRECEIPTS 55529 12806357 45472 6813097 19605 4217647 19202 2105760 17114 2568849 16053 1577361 1506 657607 ``` I need to write a measure to calculate the average of TOTALUNITS. The measure should give me a result as (TOTALUNITS/SUM(TOTALUNITS))\*100 as below ``` TOTALUNITS TOTALRECEIPTS %TOTALUNITS 55529 12806357 31.8% 45472 6813097 26.1% 19605 4217647 11.2% 19202 2105760 11.0% 17114 2568849 9.8% 16053 1577361 9.2% 1506 657607 0.9% ``` Someone help me with this.<issue_comment>username_1: Please try this, and format as Percentage: ``` %TotalUnits = DIVIDE( SUM(Receipts[TOTALUNITS]), CALCULATE( SUM(Receipts[TOTALUNITS]), ALL(Receipts) )) ``` Edit: Receipt is the table name Upvotes: 0 <issue_comment>username_2: If you want this as a measure that will sum to 100% of what you have filtered, then try this: ``` %TotalUnits = DIVIDE( SUM(Receipts[TotalUnits]), CALCULATE( SUM(Receipts[TotalUnits]), ALLSELECTED(Receipts))) ``` If you try this as a calculated column though, you'll get 100% every time. If you want to do this as a calculated column, then you'll need to remove the `SUM` from the first argument of `DIVIDE`: ``` %TotalUnits = DIVIDE( Receipts[TotalUnits], CALCULATE( SUM(Receipts[TotalUnits]), ALL(Receipts))) ``` Calculated columns are not responsive to slicers or filtering on the report page. They are computed once when the data is loaded or refreshed, but not dynamically interactive. Upvotes: 2
2018/03/21
1,837
5,459
<issue_start>username_0: I am working on a simple query where I've to show data from two tables. The condition is if the alloment table has data and the leave details has no data, then it should show data from the allotment table only. In my case, when both the tables have data, it shows up the data. Tried with this but returns when both the tables have data: ``` SELECT K.EMPNO, K.LV_NAME, K.ALLOTMENT, K.REMAIN, M.LV_FROM, M.LV_TO FROM LV_ADJ_DETAILS m LEFT JOIN TBL_LV_ALLOTMENT k ON M.EMPNO = K.EMPNO WHERE K.EMPNO = 'EMP00259' AND K.YEAR_NAME = '2018' AND EXTRACT(YEAR FROM M.LV_TO) = '2018'; ``` Expected Output: For the year **2018** If both table have data - ``` EMPNO LV_NAME ALLOTMENT REMAIN LV_FROM LV_TO EMP00259 MLWP 0 0 4/22/2018 4/30/2018 EMP00259 Maternity Leave 103 103 5/20/2018 5/22/2018 EMP00259 MLWP 0 0 5/24/2018 5/26/2018 EMP00259 Maternity Leave 103 103 5/28/2018 5/30/2018 ``` If one table has data - If no leave details like leave from and to ``` EMPNO LV_NAME ALLOTMENT REMAIN LV_FROM LV_TO EMP00259 MLWP 0 0 EMP00259 Maternity Leave 103 103 103 ``` **Script**: ``` CREATE TABLE HRD.TBL_LV_ALLOTMENT ( EMPNO VARCHAR2(10 BYTE), LV_NAME VARCHAR2(30 BYTE), YEAR_NAME INTEGER, ALLOTMENT NUMBER, ENJOY NUMBER, REMAIN NUMBER, STATUS INTEGER ) CREATE TABLE HRD.LV_ADJ_DETAILS ( EMPNO VARCHAR2(20 BYTE), APP_NO VARCHAR2(10 BYTE), LEAVE_NAME VARCHAR2(30 BYTE), APV_DAYS NUMBER(3), LV_FROM DATE, LV_TO DATE, BALANCE NUMBER(3), COM_ID VARCHAR2(15 BYTE) ) ``` **Note**: I am filtering with year in the `WHERE` clause.<issue_comment>username_1: This condition `(AND EXTRACT(YEAR FROM M.LV_TO) = '2018')` in where clause makes the issue. Try this: ``` SELECT K.EMPNO, K.LV_NAME, K.ALLOTMENT, K.REMAIN, M.LV_FROM, M.LV_TO FROM LV_ADJ_DETAILS m LEFT JOIN TBL_LV_ALLOTMENT k ON M.EMPNO = K.EMPNO AND EXTRACT(YEAR FROM M.LV_TO) = '2018' WHERE K.EMPNO = 'EMP00259' AND K.YEAR_NAME = '2018'; ``` Upvotes: 1 <issue_comment>username_2: The first thing with outer joins is to get the table order correct. With a LEFT OUTER JOIN the table with all the table comes before the join and the table with some of the table comes after. You say ... > > if the alloment table has data and the leave details has no data, then it should show data from the allotment table only > > > ... so the correct join order is `tbl_lv_allotment k left outer join lv_adj_details m`. There is also a gotcha when filtering in outer joins, and you have fallen prey to it. By including `m.lv_to` in the WHERE clause criteria you will discard any rows where `m.lv_to` is null, which short-circuits the outer join. There are a couple of ways of fixing this, but the simplest is to test for null: ``` select k.empno , k.lv_name , k.allotment , k.remain , m.lv_from , m.lv_to from tbl_lv_allotment k left outer join lv_adj_details m on m.empno = k.empno where k.empno = 'EMP00259' and k.year_name = '2018' and ( m.lv_to is null or extract(year from m.lv_to) = '2018' ); ``` However, depending on your data it may be better to use a subquery: ``` select k.empno , k.lv_name , k.allotment , k.remain , m.lv_from , m.lv_to from tbl_lv_allotment k left outer join ( select * from lv_adj_details where extract(year from lv_to) = '2018' ) m on m.empno = k.empno where k.empno = 'EMP00259' and k.year_name = '2018' ; ``` Here is [a demo on SQL Fiddle](http://sqlfiddle.com/#!4/5c7e5/5) using a version of your query, showing how the WHERE clause subverts the outer join. --- In the Fiddle I altered the join criteria to include `and m.leave_name = k.lv_name`. This removes the horrible product you get from matching all the rows in one table to all the the rows in the other. I haven't done that here, because I think code in the answer should produce the output shown in the question. Upvotes: 3 [selected_answer]<issue_comment>username_3: You want to select from table `tbl_lv_allotment` and outer join records from table `lv_adj_details`, but you have it vice versa. Then imagine the situation that the main table has no match in the outer joined table. Then you get a row with all columns of the outer joined table being null. If you then have a condition in your `WHERE` clause on that table (such as `K.EMPNO = 'EMP00259'` in your query) then you dismiss the row right away, because in an outer joined row this value is null. This renders your outer join a mere inner join. Criteria on outer joined tables belongs in the `ON` clause: ``` select a.empno, a.lv_name, a.allotment, a.remain, d.lv_from, d.lv_to from tbl_lv_allotment a left join lv_adj_details d on d.empno = a.empno and to_char(d.lv_to, 'yyyy') = a.year_name where a.empno = 'EMP00259' and a.year_name = '2018'; ``` I've changed `EXTRACT(YEAR FROM M.LV_TO) = '2018'` (which should be `2018`, not `'2018'` because you are dealing with a number here) to `to_char(d.lv_to, 'yyyy') = a.year_name`, because obviously this is about matching the year of the main table. Upvotes: 2
2018/03/21
318
1,262
<issue_start>username_0: Im using Symfony 4. I want to use Router and mailer in my services. I am including them using Dependency injection. ``` public function __construct(Swift_Mailer $mailer, EngineInterface $templating, RouterInterface $router) { $this->mailer = $mailer; $this->router = $router; $this->templating = $templating; } ``` I am getting this error: ``` argument "$templating" of method "__construct()" references interface "Symfony\Component\Templating\EngineInterface" but no such service exists. It cannot be auto-registered because it is from a different root namespace. Did you create a class that implements this interface? ``` Any hint to use Mailer, Router services in Symfony 4 ?<issue_comment>username_1: Change the TypeHint and use Interface, the autowire work with interface type hint try this : ``` public function __construct(Swift_Mailer $mailer, \Twig_Environment $templating, RouterInterface $router) ``` Upvotes: 3 <issue_comment>username_2: I had to `composer require symfony/templating`in order to get the `Symfony\Bundle\FrameworkBundle\Templating\EngineInterface` service. Also the following configuration has to be added under `framework`: `templating: enabled: false engines: ['twig']` Upvotes: 3
2018/03/21
292
967
<issue_start>username_0: ``` result = connect.query("SELECT * FROM data WHERE event_type = 'ALARM_OPENED' AND severity = '2'") equipments = result.map { |print_this| [print_this['sourcetime'], print_this['description']] } p equipments ``` The Datatype for `sourcetime` in MySQL workbench is set to TIME The result I get is `2000-01-01 12:00:04 +0100` I would like to get only the time `12:00:04` and drop the date and +0100<issue_comment>username_1: Change the TypeHint and use Interface, the autowire work with interface type hint try this : ``` public function __construct(Swift_Mailer $mailer, \Twig_Environment $templating, RouterInterface $router) ``` Upvotes: 3 <issue_comment>username_2: I had to `composer require symfony/templating`in order to get the `Symfony\Bundle\FrameworkBundle\Templating\EngineInterface` service. Also the following configuration has to be added under `framework`: `templating: enabled: false engines: ['twig']` Upvotes: 3
2018/03/21
1,263
5,040
<issue_start>username_0: I am working on BLE project where hardware records the audio data & sending to the iOS application. I writting a logic to convert mp3/wav file from data. Here, I written mp3 file conversion logic from Data like below: ``` func storeMusicFile(data: Data) { let fileName = "Record-1" guard mediaDirectoryURL != nil else { print("Error: Failed to fetch mediaDirectoryURL") return } let filePath = mediaDirectoryURL!.appendingPathComponent("/\(fileName).mp3") do { try data.write(to: filePath, options: .atomic) } catch { print("Failed while storing files.") } } ``` But while playing an audio file in AVAudioPlayer, I am getting "**The operation couldn’t be completed. (OSStatus error 1954115647.)**" error. So, Confused whether audio file conversion logic is wrong or data from hardware is still needs to decode?<issue_comment>username_1: To create a audio file(.mp3/.wav), you have to dynamically calculate header file data & need to append that header with actual transfer audio data from the hardware. **Reference:** [WAVE PCM soundfile format](http://soundfile.sapp.org/doc/WaveFormat/) Here, below I added Swift 4 code snippet for reference ``` //MARK: Logic for Creating Audio file class ARFileManager { static let shared = ARFileManager() let fileManager = FileManager.default var documentDirectoryURL: URL? { return fileManager.urls(for: .documentDirectory, in: .userDomainMask).first } func createWavFile(using rawData: Data) throws -> URL { //Prepare Wav file header let waveHeaderFormate = createWaveHeader(data: rawData) as Data //Prepare Final Wav File Data let waveFileData = waveHeaderFormate + rawData //Store Wav file in document directory. return try storeMusicFile(data: waveFileData) } private func createWaveHeader(data: Data) -> NSData { let sampleRate:Int32 = 2000 let chunkSize:Int32 = 36 + Int32(data.count) let subChunkSize:Int32 = 16 let format:Int16 = 1 let channels:Int16 = 1 let bitsPerSample:Int16 = 8 let byteRate:Int32 = sampleRate * Int32(channels * bitsPerSample / 8) let blockAlign: Int16 = channels * bitsPerSample / 8 let dataSize:Int32 = Int32(data.count) let header = NSMutableData() header.append([UInt8]("RIFF".utf8), length: 4) header.append(intToByteArray(chunkSize), length: 4) //WAVE header.append([UInt8]("WAVE".utf8), length: 4) //FMT header.append([UInt8]("fmt ".utf8), length: 4) header.append(intToByteArray(subChunkSize), length: 4) header.append(shortToByteArray(format), length: 2) header.append(shortToByteArray(channels), length: 2) header.append(intToByteArray(sampleRate), length: 4) header.append(intToByteArray(byteRate), length: 4) header.append(shortToByteArray(blockAlign), length: 2) header.append(shortToByteArray(bitsPerSample), length: 2) header.append([UInt8]("data".utf8), length: 4) header.append(intToByteArray(dataSize), length: 4) return header } private func intToByteArray(_ i: Int32) -> [UInt8] { return [ //little endian UInt8(truncatingIfNeeded: (i ) & 0xff), UInt8(truncatingIfNeeded: (i >> 8) & 0xff), UInt8(truncatingIfNeeded: (i >> 16) & 0xff), UInt8(truncatingIfNeeded: (i >> 24) & 0xff) ] } private func shortToByteArray(_ i: Int16) -> [UInt8] { return [ //little endian UInt8(truncatingIfNeeded: (i ) & 0xff), UInt8(truncatingIfNeeded: (i >> 8) & 0xff) ] } func storeMusicFile(data: Data) throws -> URL { let fileName = "Record \(Date().dateFileName)" guard mediaDirectoryURL != nil else { debugPrint("Error: Failed to fetch mediaDirectoryURL") throw ARError(localizedDescription: AlertMessage.medioDirectoryPathNotAvaiable) } let filePath = mediaDirectoryURL!.appendingPathComponent("\(fileName).wav") debugPrint("File Path: \(filePath.path)") try data.write(to: filePath) return filePath //Save file's path respected to document directory. } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: The previous answer from @sagar-thummar saved me a ton of time. Unfortunately I am not allowed to vote or comment on it. A few corrections I need to do was: * change mediaDirectoryURL to documentDirectoryURL * create ARError exception * adjust the sample rate AND bits per sample to my settings Upvotes: 2
2018/03/21
889
2,987
<issue_start>username_0: When a user clicks on a link. I am trying to find the closest span value by class and then get that classes text. Currently it is just returning empty text: Here is the HTML: ``` DOUBLE DATA $ 85 per month Min. Total Cost is $2,040 over 24 months. 28GB TOTAL DATA Includes 14GB + 14GB bonus data for 24 mths New and recontracting services only Offer ends 15/04/18 $10 per extra 1GB **Data Pool -** Combine any of our latest My Plan Plus (including SIM Only) and My Mobile Broadband Plus plans on the one bill to pool and share the data. [more](#) ``` and my javascript So when someone clicks on the `a href` with the `class="more-data-link"` I want to find the span with the `class="amount"` and get its text ``` $(".more-data-link").on("click", function(event) { event.preventDefault(); var x = $(this).closest('plan-header').find('.price').find('.amount').text(); console.log(x); }); ```<issue_comment>username_1: ``` $(".more-data-link").on("click", function(event) { event.preventDefault(); var x = $(this).closest('.plan-header').find('.amount').text(); console.log(x); }); ``` Fixed it. You don't need to use the second find and you missed a dot Upvotes: -1 <issue_comment>username_2: Please use this [fiddle](https://jsfiddle.net/9omhzp3z/55/) ```js $(".more-data-link").on("click", function(event) { event.preventDefault(); var x = $(this).closest('.plan.recommended').find('.plan-header .price .amount').text(); console.log(x); }); ``` ```html DOUBLE DATA $ 85 per month Min. Total Cost is $2,040 over 24 months. 28GB TOTAL DATA Includes 14GB + 14GB bonus data for 24 mths New and recontracting services only Offer ends 15/04/18 $10 per extra 1GB **Data Pool -** Combine any of our latest My Plan Plus (including SIM Only) and My Mobile Broadband Plus plans on the one bill to pool and share the data. [more](#) ``` You need to select parent (plan recommended) class and then find its child... Upvotes: 3 [selected_answer]<issue_comment>username_3: I check your script and find some error in it, use `innerHtml` in place of `text()` and `closest('plan-header')` should be `closest('.plan-header')`. but may be you not get the proper result because it will search in parents div not subling check link <https://www.w3schools.com/jquery/traversing_closest.asp> you can use the simplest and best way to do same by creating the attribute of the more-data-link and save value of amount in it and use the following code. ``` $(".more-data-link").on("click", function(event) { event.preventDefault(); var x = $(this).attr('amount'); console.log(x); }); ``` Upvotes: -1 <issue_comment>username_4: For those seeking a solution without jquery (the logic inside the click event is the same as described by username_2): ``` window.onload = function(){ for(var tL=document.querySelectorAll('.more-data-link'), i=0, j=tL.length; i ``` Upvotes: 0
2018/03/21
880
3,140
<issue_start>username_0: I am getting an error " Element is not reachable by keyboard" Can you guys please help me in it. I just want to attach the PDF file but as the cusror goes on it i am unable to find click on it nor upload file on it. Code is:- ``` WebElement uploadElement = driver.findElement(By.xpath("//*[@id=\"registerproduct\"]/div/div[4]/div/div/div/div[2]/div[2]/div/div/span/label")); uploadElement.sendKeys("C:\\Users\\Rahul\\Downloads\\kemgo-auction-detail-574.pdf"); ``` The Html is:- ``` Attach specification sheet ``` Can you guys help me in uploading file. Thanks<issue_comment>username_1: As per the *HTML* you have shared and your *code trials* the *WebElement* to pass the file path is not the tag. You should target the tag. Additionally the tag is having *style* attribute set to **display: none;**. You can use the following code block to upload the file : ``` WebElement uploadElement = driver.findElement(By.xpath("//input[@id='btn_myFileInput']")); ((JavascriptExecutor)driver).executeScript("arguments[0].removeAttribute('style')", uploadElement); uploadElement.sendKeys("C:\\Users\\Rahul\\Downloads\\kemgo-auction-detail-574.pdf"); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: This is my solution and I think it can solve other cases. And I will explain clearly about my code > > > ``` > driver.executeScript("return document.readyState").equals("complete"); > > WebElement uploadImage = driver.findElementByXPath("*\*"); > > String scriptOn = "arguments[0].setAttribute('style','display: block')"; > > driver.executeScript(scriptOn, uploadImage); > > uploadImage.sendKeys("\*\*"); > > String scriptOff = "arguments[0].setAttribute('style','display: none')"; > > driver.executeScript(scriptOff, uploadImage); > > ``` > > Explanation: Pre-condition: driver: FFDriver language: Java Steps: Line 1: Because it's a hidden element so u don't know when it appears => that why you need to wait for page that full load Line 2: Define the element that u want to detect, don't worry that it can't detect example my xPath: *//input[@accept='image/*']\* Line 3: Define new value for Style attribute that as u expected example URL = "path/01.png" Line 4: execute command Element's current style = new value ('style','display: block') => it makes the hidden element to show Line 5: Now your expectation element is show, so u can sendkeys (image URL) to it Line 6 + 7: return raw state to this element Upvotes: 0 <issue_comment>username_3: Make the input field visible using element Id, when `style="display:none;"` ``` public void makeInputElementVisible(){ JavascriptExecutor executor = (JavascriptExecutor)driver; executor.executeScript("document.getElementById('your_element_id').style.display='block';"); } ``` Make the input field visible using css selector, when `style="display:none;"` ``` public void makeInputElementVisible(){ JavascriptExecutor executor = (JavascriptExecutor)driver; executor.executeScript("document.querySelector('your_css_selector_for_input_field').style.display='block';"); } ``` Upvotes: 0
2018/03/21
1,869
5,378
<issue_start>username_0: I am trying to implement fuzzy logic for classifying the weather into different climatic zone. I am getting this Null exception when I call fuzzy\_inference() function of sets package in RStudio. The following is my code defining sets and fuzzy rules. ``` sets_options("universe", seq(1, 200, 0.5)) variables <- set( rainfall=fuzzy_partition(varnames = c(range1 = 30, range2 = 70, range3 = 90),sd = 5.0), maxTemp = fuzzy_partition(varnames = c(hot = 30, hotter = 70),sd = 5.0), humidity = fuzzy_partition(varnames = c(less_humid = 30, humid = 60, more_humid = 80),sd = 3.0), soil = fuzzy_partition(varnames=c(Black_soil=10,Mixed_Red_and_Black_soil=20, Mixed_Red_and_clay_soil=30, Mixed_red_and_sandy_soil=40,Mixed_Red_Loamy_and_sandy_soil=50, Mixed_sandy_and_clayey_soil=60, Red_forest_soil=70,Red_Lateritic_soil=80,Red_Loamy_soil=90, Red_sandy_soil=100),sd = 3.0), climate=fuzzy_partition(varnames = c(Northern_Dry_Zone=10, Eastern_Dry_Zone=20, North_Eastern_Transition_Zone=30, Southern_Dry_Zone=40,Eastern_Dry_Zone=50,Hilly_Zone=60, Central_Dry_Zone=70,Coastal_Zone=80,Southern_Transition_Zone=90, Northern_Transition_Zone=100),sd = 3.0), FUN = fuzzy_cone, radius = 10) rules <- set( fuzzy_rule(humidity %is% less_humid && maxTemp %is% hot && rainfall %is% range2 && soil %is% Black_soil ,climate %is% Northern_Dry_Zone), fuzzy_rule(humidity %is% humid && maxTemp %is% hot && rainfall %is% range2 && soil %is% Red_Loamy_soil ,climate %is% Eastern_Dry_Zone), fuzzy_rule(humidity %is% humid && maxTemp %is% hot && rainfall %is% range2 && soil %is% Black_soil ,climate %is% Northern_Dry_Zone), fuzzy_rule(humidity %is% less_humid && maxTemp %is% hotter && rainfall %is% range1 && soil %is% Mixed_Red_and_Black_soil ,climate %is% Northern_Dry_Zone), fuzzy_rule(humidity %is% less_humid && maxTemp %is% hot && rainfall %is% range1 && soil %is% Black_soil ,climate %is% Northern_Transition_Zone), fuzzy_rule(humidity %is% humid && maxTemp %is% hot && rainfall %is% range3 && soil %is% Red_forest_soil ,climate %is% Southern_Dry_Zone), fuzzy_rule(humidity %is% humid && maxTemp %is% hot && rainfall %is% range2 && soil %is% Mixed_red_and_sandy_soil ,climate %is% Eastern_Dry_Zone), fuzzy_rule(humidity %is% less_humid && maxTemp %is% hotter && rainfall %is% range2 && soil %is% Mixed_Red_and_Black_soil ,climate %is% Central_Dry_Zone), fuzzy_rule(humidity %is% more_humid && maxTemp %is% hot && rainfall %is% range3 && soil %is% Red_Loamy_soil ,climate %is% Hilly_Zone), fuzzy_rule(humidity %is% more_humid && maxTemp %is% hotter && rainfall %is% range3 && soil %is% Red_Lateritic_sandy_soil ,climate %is% Coastal_Zone), fuzzy_rule(humidity %is% less_humid && maxTemp %is% hotter && rainfall %is% range3 && soil %is% Black_soil ,climate %is% North_Eastern_Dry_Zone), fuzzy_rule(humidity %is% more_humid && maxTemp %is% hot && rainfall %is% range3 && soil %is% Red_Loamy_soil ,climate %is% Southern_Transition_Zone), fuzzy_rule(humidity %is% humid && maxTemp %is% hot && rainfall %is% range2 && soil %is% Mixed_Red_Loamy_and_sandy_soil ,climate %is% Eastern_Dry_Zone), fuzzy_rule(humidity %is% less_humid && maxTemp %is% hotter && rainfall %is% range2 && soil %is% Black_soil ,climate %is% Northern_Dry_Zone), fuzzy_rule(humidity %is% humid && maxTemp %is% hot && rainfall %is% range3 && soil %is% Red_Loamy_soil ,climate %is% Southern_Dry_Zone), fuzzy_rule(humidity %is% less_humid && maxTemp %is% hot && rainfall %is% range1 && soil %is% Black_soil ,climate %is% North_Eastern_Dry_Zone), fuzzy_rule(humidity %is% humid && maxTemp %is% hotter && rainfall %is% range2 && soil %is% Mixed_Red_Loamy_and_sandy_soil ,climate %is% Eastern_Dry_Zone) ) model<- fuzzy_system(variables, rules) ### error code #### example.1 <- fuzzy_inference(model, list(humidity=63,maxTemp=31,rainfall=72.5,soil=41.5)) ``` The following line of the code is throwing null error. `### error code #### example.1 <- fuzzy_inference(model, list(humidity=63,maxTemp=31,rainfall=72.5,soil=41.5))`<issue_comment>username_1: I haven't evaluated your code, but if the problem is that you try to set an attribute on `NULL`, then the solution is simple. Don't do that. The `NULL` object is not really an object. It is the *absence* of an object. You cannot modify it or set attributes to it; you cannot have `NULL` objects of different classes; `NULL` is nothing. You can set attributes to `NA` because that *is* an object -- just a missing value, but of a specific type. It is an explicit representation of the lack of a value. But `NULL` is different. It is R's way of representing that you do not have an object. There is no way to assign attributes to `NULL`. If you want a value that represents nothing but has classes or attributes, you need `NA` or some other representation. `NULL` isn't going to work. Upvotes: 1 <issue_comment>username_2: I had the same issue and found this old thread without a solution. In my case, I had rules defined with not matching characteristics as the defined variables. So check your variables and your rules. Upvotes: 0