date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/16
397
1,487
<issue_start>username_0: I have a problem with my Visual Studio 2017 Community. I installed Visual with Python, but Intellisense doesn't detect Python modules. [Screen1](https://i.stack.imgur.com/RGLG3.png) [Screen2](https://i.stack.imgur.com/4ffwA.png) [Screen3](https://i.stack.imgur.com/G8lVD.png) [Screen4](https://i.stack.imgur.com/Q4HGR.png) I repaired Visual Studio - it doesn't solve problem. I reinstall python 3.64 - it also doesn't solve problem.<issue_comment>username_1: With Desktop App Converter, making customisation while creating AppX packages is not straightforward. It may be easier to use one of the application repackaging tools which enable you to capture any number of MSI and make the necessary customisations, including any changes to the registry or file system. Here's the list of some of such tools on Microsoft website: <https://learn.microsoft.com/en-us/windows/uwp/porting/desktop-to-uwp-root> Upvotes: 2 [selected_answer]<issue_comment>username_2: Converting the packages is now much easier with the new [free Express edition from Advanced Installer](https://www.advancedinstaller.com/express-edition.html), developed in partnership with Microsoft. It has a GUI that allows for advanced customization of the APPX packages, without requiring you to have knowledge about the internals package schemas. If you have any questions about it, let me know, would love to help. *Disclaimer: I work on the team that builds Advanced Installer.* Upvotes: 0
2018/03/16
1,000
2,746
<issue_start>username_0: I inspected the output parquet file of a spark job that always beaks, because of `Out of Memory Errors`. I use `Spark 1.6.0` on `Cloudera 5.13.1` I noticed that the parquet row group size is uneven. The first and the last row group are huge. The rest is really small... Shortened output from parquet-tools `RC = row count`, `TS = total size`: ``` row group 1: RC:5740100 TS:566954562 OFFSET:4 row group 2: RC:33769 TS:2904145 OFFSET:117971092 row group 3: RC:31822 TS:2772650 OFFSET:118905225 row group 4: RC:29854 TS:2704127 OFFSET:119793188 row group 5: RC:28050 TS:2356729 OFFSET:120660675 row group 6: RC:26507 TS:2111983 OFFSET:121406541 row group 7: RC:25143 TS:1967731 OFFSET:122069351 row group 8: RC:23876 TS:1991238 OFFSET:122682160 row group 9: RC:22584 TS:2069463 OFFSET:123303246 row group 10: RC:21225 TS:1955748 OFFSET:123960700 row group 11: RC:19960 TS:1931889 OFFSET:124575333 row group 12: RC:18806 TS:1725871 OFFSET:125132862 row group 13: RC:17719 TS:1653309 OFFSET:125668057 row group 14: RC:1617743 TS:157973949 OFFSET:134217728 ``` Is this a known bug? How can I set the parquet block size (row group size) in Spark? **EDIT:** What the Spark application does is: It reads a big AVRO file, then distributes the rows by two partition keys (using `distribute by` in the select) and then writes a parquet file for each partition using: `DF.write.partitionBy().parquet()`<issue_comment>username_1: Your RDD could be unevenly partitioned. The number of rows in each block is related to the size of the different partition of your RDD. When a RDD is created, each partition contains roughly the same amount of data (due to the [HashPartitioner](https://spark.apache.org/docs/1.6.3/api/java/org/apache/spark/HashPartitioner.html)). After the processing of the Spark job, one partition could contain more data than another , maybe a filter transformation removed more rows from one partition than from another. The partitions can be rebalanced calling [repartition](https://spark.apache.org/docs/1.6.3/api/java/org/apache/spark/rdd/RDD.html#repartition(int,%20scala.math.Ordering)) before writing the parquet file. **EDIT:** if the problem is not related to the partitions, maybe reducing the size of the row groups could help: ```scala sc.hadoopConfiguration.setInt( "parquet.block.size", blockSize ) ``` Upvotes: 2 <issue_comment>username_2: There is a known bug for this : [PARQUET-1337](https://issues.apache.org/jira/browse/PARQUET-1337) Upvotes: 1
2018/03/16
602
2,089
<issue_start>username_0: **About**: there are two threads running - one check for timeout (inactivity for some time), another one is where user works with UI. **Problem**: timeout event occured slightly before user action, even though at the same millisecond, based on logs I can see it ``` 2018-03-15 16:58:54:921 INFO {Thread-58} [InputTimeoutThread] Input timeout occured. 2018-03-15 16:58:54:921 DEBUG {AWT-EventQueue-1} [INPUT\_EVENT] Input event : functionKeyID = 10056 2018-03-15 16:58:54:921 DEBUG {AWT-EventQueue-1} [FunctionManagerImpl] Calling function [ID (10056)] ``` **Result**: inconsistent results as because of timeout logout event was called, but at the same time user action was done. If timeout had happened before the user action it would have blocked the user to do any action, but this did not happen here as you can see. Can anyone please advise how to tackle this? So that it can be guaranteed: no actions possible after some event happaned (in different threads).<issue_comment>username_1: Your RDD could be unevenly partitioned. The number of rows in each block is related to the size of the different partition of your RDD. When a RDD is created, each partition contains roughly the same amount of data (due to the [HashPartitioner](https://spark.apache.org/docs/1.6.3/api/java/org/apache/spark/HashPartitioner.html)). After the processing of the Spark job, one partition could contain more data than another , maybe a filter transformation removed more rows from one partition than from another. The partitions can be rebalanced calling [repartition](https://spark.apache.org/docs/1.6.3/api/java/org/apache/spark/rdd/RDD.html#repartition(int,%20scala.math.Ordering)) before writing the parquet file. **EDIT:** if the problem is not related to the partitions, maybe reducing the size of the row groups could help: ```scala sc.hadoopConfiguration.setInt( "parquet.block.size", blockSize ) ``` Upvotes: 2 <issue_comment>username_2: There is a known bug for this : [PARQUET-1337](https://issues.apache.org/jira/browse/PARQUET-1337) Upvotes: 1
2018/03/16
481
1,656
<issue_start>username_0: I'm using the following VBA code and assigned it to a button: ``` Sub pastespecial () ActiveSheet.Range("A4:X400").Copy Activesheet.Next.Range("A4:X400").PasteSpecial Paste:=xlPasteFormats ActiveSheet.Next.Range("A4:X400").PasteSpecial paste:=xlPasteFormulas ActiveSheet.Previous.Activate Application.CutCopyMode = False MsgBox "Data has been copied Successfully" End sub ``` It was doing it before but start making issues now. I am getting > > run time error 1004 pastespecial method of Range class Failed > > > Thanks in advance<issue_comment>username_1: Your RDD could be unevenly partitioned. The number of rows in each block is related to the size of the different partition of your RDD. When a RDD is created, each partition contains roughly the same amount of data (due to the [HashPartitioner](https://spark.apache.org/docs/1.6.3/api/java/org/apache/spark/HashPartitioner.html)). After the processing of the Spark job, one partition could contain more data than another , maybe a filter transformation removed more rows from one partition than from another. The partitions can be rebalanced calling [repartition](https://spark.apache.org/docs/1.6.3/api/java/org/apache/spark/rdd/RDD.html#repartition(int,%20scala.math.Ordering)) before writing the parquet file. **EDIT:** if the problem is not related to the partitions, maybe reducing the size of the row groups could help: ```scala sc.hadoopConfiguration.setInt( "parquet.block.size", blockSize ) ``` Upvotes: 2 <issue_comment>username_2: There is a known bug for this : [PARQUET-1337](https://issues.apache.org/jira/browse/PARQUET-1337) Upvotes: 1
2018/03/16
445
1,506
<issue_start>username_0: How to specify proxy settings for konanc? I tried to start it with ``` konanc hello.kt -Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800 ``` and also tried to specify system variable at Windows ``` set JAVA_FLAGS=-Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800 ``` but it fails on Download native dependencies… with `java.net.ConnectException: Connection refused: connect` Thank you!<issue_comment>username_1: Your RDD could be unevenly partitioned. The number of rows in each block is related to the size of the different partition of your RDD. When a RDD is created, each partition contains roughly the same amount of data (due to the [HashPartitioner](https://spark.apache.org/docs/1.6.3/api/java/org/apache/spark/HashPartitioner.html)). After the processing of the Spark job, one partition could contain more data than another , maybe a filter transformation removed more rows from one partition than from another. The partitions can be rebalanced calling [repartition](https://spark.apache.org/docs/1.6.3/api/java/org/apache/spark/rdd/RDD.html#repartition(int,%20scala.math.Ordering)) before writing the parquet file. **EDIT:** if the problem is not related to the partitions, maybe reducing the size of the row groups could help: ```scala sc.hadoopConfiguration.setInt( "parquet.block.size", blockSize ) ``` Upvotes: 2 <issue_comment>username_2: There is a known bug for this : [PARQUET-1337](https://issues.apache.org/jira/browse/PARQUET-1337) Upvotes: 1
2018/03/16
704
2,126
<issue_start>username_0: I need help getting certain numbers with a regex. As I dont know much about regex I have only managed to see if the first two characters match with 95 - 99. ^([0-9][5-9]{4}) I have the numbers 00000 through 99999. I want to exclude all the numbers that start with 95 and up. So 00000 - 94999 is ok, 95000 - 99999 is not ok.<issue_comment>username_1: A regex is for validating if a string matches the set pattern. It is not for comparing numbers to see if they are within range. Convert the text (if that is what you are starting from) to a number and then use comparison operators in an if statement. Upvotes: 0 <issue_comment>username_2: Regex is not well suited to performing numeric comparisons, from both a readability and performance standpoint. It would be much more sensible to extract the number and perform a numeric compare afterwards. You've not mentioned a language, so I'll demonstrate with Python3. ```py # input data lines = [ "my line #1 :94995: message #1", "my line #2 :95005: message #2" ] for i, line in enumerate(x): # extract a 5-digit number wrapped in colons match = re.search(':([0-9]{5}):', line) if match is None: continue # convert to a number, and verify num = int(match.group(1)) if num >= 95000: continue # print any lines that meet our criteria print("line %d meets our criteria! (%d)" % ( i, num )) ``` Will output: ```none line 0 meets our criteria! (94995) ``` Upvotes: 0 <issue_comment>username_3: You could match the range of numbers 00000 - 94999 including leading zeroes you might try it like this: * `^` From the beginning of the string * `(?=\d{5}$)` Start with a positive lookahead that makes sure that the number is not longer than 5 digits until the end of the string * `0*` Preprend with zero or more zeroes * `(?:9[0-4][0-9]{3}|[1-8][0-9]{4}|[1-9][0-9]{1,3}|[0-9])` Match the range of numbers * `$` The end of the string Your regex could look like: [`^(?=\d{5}$)0*(?:9[0-4][0-9]{3}|[1-8][0-9]{4}|[1-9][0-9]{1,3}|[0-9])$`](https://regex101.com/r/700uRS/1) Upvotes: 2 [selected_answer]
2018/03/16
675
2,540
<issue_start>username_0: I am supposed to make a program to add all the elements inside the 2D rectangular array but the answer for this is supposed to be 31, instead it prints 33. What am I doing wrong? Heres the code: ``` public static int sum(int[][] array) { int[][] numArray = { {3, -1, 4, 0}, {5, 9, -2, 6}, {5, 3, 7, -8} }; int sumOfRow = 0; for (int i = 0; i < numArray.length; i++) { sumOfRow += numArray[0][i]; sumOfRow += numArray[1][i]; sumOfRow += numArray[2][i]; } System.out.println(sumOfRow); return sumOfRow; } ```<issue_comment>username_1: `numArray.length` is the number of rows, and your code treats it as the number of columns, so you ignore the last column of each row. The number of columns in a given row is `numArray[i].length`. You should use nested loops: ``` for (int i = 0; i < numArray.length; i++) { for (int j = 0; j < numArray[i].length; j++) { sumOfRow += numArray[i][j]; } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: `numArray.length` is the length of outer array, you should use `numArray[0].length` instead of `numArray.length` which should give you expected results. If you are using java 8, here is the solution: ``` int sum = Arrays.stream(numArray) .mapToInt(arr->IntStream.of(arr).sum()) // sum the inner array .sum(); // sum the outer array ``` Upvotes: 2 <issue_comment>username_3: As mentioned by the others already, `numArray.length` refers to the number of rows (or in other words the number of other arrays referenced by the references in `numArray`), and your code treats it as the number of columns and because there are fewer rows than columns you're getting un-expected results. Nevertheless, the first index for any two-dimensional array should be the row index and the second should indicate the column index. username_1's answer indicates how to solve your current issue. However, I just wanted to provide another more ideal solution in Java-8+ to sum the elements of your two-dimensional array. ``` int sum = Arrays.stream(numArray) .flatMapToInt(Arrays::stream) .sum(); ``` It's more ideal because the `flatMapToInt` is the perfect method for this type of job and simply calling the `sum` terminal operation should render the results you need. Upvotes: 2
2018/03/16
968
3,546
<issue_start>username_0: Part of the deliverables for the client include the source code of the project we are working on. I'm using maven with `mvn generate-sources`. The problem is that it includes all the dependencies and aggregates the sources per dependency. I'm trying to generate a flat structure with the `.java` files filtered on `groupid`. The documentation is very evasive about [maven-source-plugin](https://maven.apache.org/plugins/maven-source-plugin/usage.html). All the searches I do end-up pointing me toward filtering resources, which is not what I'am looking for. The structure of my project is a parent pom with children and I'm trying to achieve something like this: ``` org.apache.maven.plugins maven-source-plugin 3.0.1 attach-sources jar com.mygroupid.project ``` What I am expecting: * A 'fat' structure (all project sources aggregated by package name in one dir) * No duplicate sources * No code outside of my source group id **Edit:** Assuming a structure like this: ``` - module-1 pom.xml // aggregate project |- module-1-core (has dependency to module-2 and module-2) |- module-1-war - module-2 pom.xml // aggregate project |- module-2-commons - module-3 pom.xml // aggregate project |- module-3-services - // etc... ``` I would like the archive as follows: ``` - big-fat-code-sources.zip |- module-1-core sources + test source |- module-1-war sources + test source |- module-2-commons sources + test source |- module-3-services sources + test source |- // etc... ```<issue_comment>username_1: Using `source:aggregate` goal should solve this task: ``` mvn clean source:aggregate ``` Supposing you have the following project structure ``` - root pom.xml // aggregate project |- module1 // jar module |- module2 // another jar... ``` With just following configuration in root pom: ``` org.apache.maven.plugins maven-source-plugin 3.0.1 ``` and the above command executed, it will produce a `.jar` in `target` folder, which will contain the all the *sources* of `modules` mixed together. [More doc](https://maven.apache.org/plugins/maven-source-plugin/aggregate-mojo.html) for this Maven goal. Upvotes: 2 <issue_comment>username_2: I ended up solving the issue with the `maven-assembly-plugin` and a lot of not obvious extra configuration. In my `assembly.xml` descriptor I added a filter on the modules from the project: ``` // 1 mrkrabs-secret-recipe:\* true ${artifactId}-${version} // 2 true // 3 src \*\*/target/\*\* \*\*/bin/\*\* ``` 1. Includes all the modules in the maven project 2. Map each module to a directory with the artifact id and the version 3. Enforce filtering to keep sources only This does not yet include the transitive dependencies and their source code. So I added a filter on the dependencies: ``` // 1 // 2 mrkrabs-secret-recipe:\* provided /dependencies // 3 true // 4 true // 5 mrkrabs-\*/\*\* \*.sql \*.zip \*.class \*.jar true ``` 1. Includes all the dependencies of the maven project 2. Filter to include only the artifacts from the mrkrabs project 3. Put all the dependencies in a /dependencies folder 4. Force the filtering to be applied to the transitive dependencies 5. Apply extra filtering when unpacking the transitive dependencies: 1. Include only mrkrabs projects (the `useTransitiveFiltering` should take care of this but does not) 2. Exclude certain files we do not wanna see in the archive (.sql, .zip, .class, .jar) Upvotes: 1 [selected_answer]
2018/03/16
815
3,048
<issue_start>username_0: I am having a div as below, ``` ``` Its content is to be filled fled with Partial view using an AJAX call. Below is the AJAX implementation: ``` $.ajax({ type: "POST", url: '@Url.Action("GetCustReqChartData", "DA_CPC")', contentType: "application/json; charset=utf-8", dataType: "json", data: "{'ProjectID':" + getUrlParameter('PID')"}", success: function (JsonData) { $('#d1').load('@Html.Action("PlotCurrentStatusCountTbl", "DA_CPC", new{ CurrentStatus = JsonData.StatusCount })'); } }); ``` While i call above AJAX call, i am getting error : **The name 'JsonData' does not exist in the current context.** in the below line : ``` $('#d1').load('@Html.Action("PlotCurrentStatusCountTbl", "DA_CPC", new{ CurrentStatus = JsonData.StatusCount })'); ``` How do i pass the javascript variable into `@Html.Action` method.<issue_comment>username_1: Using `source:aggregate` goal should solve this task: ``` mvn clean source:aggregate ``` Supposing you have the following project structure ``` - root pom.xml // aggregate project |- module1 // jar module |- module2 // another jar... ``` With just following configuration in root pom: ``` org.apache.maven.plugins maven-source-plugin 3.0.1 ``` and the above command executed, it will produce a `.jar` in `target` folder, which will contain the all the *sources* of `modules` mixed together. [More doc](https://maven.apache.org/plugins/maven-source-plugin/aggregate-mojo.html) for this Maven goal. Upvotes: 2 <issue_comment>username_2: I ended up solving the issue with the `maven-assembly-plugin` and a lot of not obvious extra configuration. In my `assembly.xml` descriptor I added a filter on the modules from the project: ``` // 1 mrkrabs-secret-recipe:\* true ${artifactId}-${version} // 2 true // 3 src \*\*/target/\*\* \*\*/bin/\*\* ``` 1. Includes all the modules in the maven project 2. Map each module to a directory with the artifact id and the version 3. Enforce filtering to keep sources only This does not yet include the transitive dependencies and their source code. So I added a filter on the dependencies: ``` // 1 // 2 mrkrabs-secret-recipe:\* provided /dependencies // 3 true // 4 true // 5 mrkrabs-\*/\*\* \*.sql \*.zip \*.class \*.jar true ``` 1. Includes all the dependencies of the maven project 2. Filter to include only the artifacts from the mrkrabs project 3. Put all the dependencies in a /dependencies folder 4. Force the filtering to be applied to the transitive dependencies 5. Apply extra filtering when unpacking the transitive dependencies: 1. Include only mrkrabs projects (the `useTransitiveFiltering` should take care of this but does not) 2. Exclude certain files we do not wanna see in the archive (.sql, .zip, .class, .jar) Upvotes: 1 [selected_answer]
2018/03/16
868
3,297
<issue_start>username_0: I am currently working on an assignment where I have to be able to read a certain predetermined amount of lines of input, each of which correlate to a certain line of output. Simply put, if I have 200 lines of input, I should also have 200 lines of output. I read the input through a scanner on the standard input, copy pasting it into the standard input, and every line, except the last line, is automatically outputted. For the last line to appear, I have to press enter. How do I make it so that this last line automatically appears and I don't have to press enter? ``` int numberOfPackets = Integer.parseInt(in.nextLine()); for (int i = 0; i < numberOfPackets; i++){ String nextLine = in.nextLine(); if (nextLine.charAt(0) == 'D'){ //Check to see if the packet is a data packet or a router packet out.print("\n" + dataParser(nextLine)); } else if (nextLine.charAt(0) == 'R'){ out.print("\n" + routeParser(nextLine)); } } ``` This is the code that reads each line into input, is there something I'm missing? Edit: I cannot edit the input to include an empty line at the end as many of you have suggested. This is a brilliant solution but unfortunately I'm not allowed to do this!<issue_comment>username_1: Using `source:aggregate` goal should solve this task: ``` mvn clean source:aggregate ``` Supposing you have the following project structure ``` - root pom.xml // aggregate project |- module1 // jar module |- module2 // another jar... ``` With just following configuration in root pom: ``` org.apache.maven.plugins maven-source-plugin 3.0.1 ``` and the above command executed, it will produce a `.jar` in `target` folder, which will contain the all the *sources* of `modules` mixed together. [More doc](https://maven.apache.org/plugins/maven-source-plugin/aggregate-mojo.html) for this Maven goal. Upvotes: 2 <issue_comment>username_2: I ended up solving the issue with the `maven-assembly-plugin` and a lot of not obvious extra configuration. In my `assembly.xml` descriptor I added a filter on the modules from the project: ``` // 1 mrkrabs-secret-recipe:\* true ${artifactId}-${version} // 2 true // 3 src \*\*/target/\*\* \*\*/bin/\*\* ``` 1. Includes all the modules in the maven project 2. Map each module to a directory with the artifact id and the version 3. Enforce filtering to keep sources only This does not yet include the transitive dependencies and their source code. So I added a filter on the dependencies: ``` // 1 // 2 mrkrabs-secret-recipe:\* provided /dependencies // 3 true // 4 true // 5 mrkrabs-\*/\*\* \*.sql \*.zip \*.class \*.jar true ``` 1. Includes all the dependencies of the maven project 2. Filter to include only the artifacts from the mrkrabs project 3. Put all the dependencies in a /dependencies folder 4. Force the filtering to be applied to the transitive dependencies 5. Apply extra filtering when unpacking the transitive dependencies: 1. Include only mrkrabs projects (the `useTransitiveFiltering` should take care of this but does not) 2. Exclude certain files we do not wanna see in the archive (.sql, .zip, .class, .jar) Upvotes: 1 [selected_answer]
2018/03/16
754
2,545
<issue_start>username_0: I'm working with Bootstrap 4 dropdown and there are about 18 dropdown items. Because the height is too much, popper.js automatically moves the dropdown away from its original position to the top of the screen. How do I prevent this? I always want the dropdown to appear right below the button that toggles it. Thanks Posting code as requested - ( I'm using C# but the code should convey the point I'm hoping) ``` @topMenu.Name @foreach (var subMenu in topMenu.SubMenu) { [@subMenu.Name](@Url.Content() } ```<issue_comment>username_1: **Bootstrap 4.1** There is a new "display" option that disables popper.js dropdown positioning. Use `data-display="static"` to [prevent popper.js from dynamically changing the dropdown position](https://getbootstrap.com/docs/4.1/components/dropdowns/#options)... **Bootstrap 4.0** There are some issues with `popper.js` and positioning. I've found the solution is to `position-relative` the `.dropdown`, and set it as the `data-boundary=""` option in the dropdown toggle: <https://www.codeply.com/go/zZJwAuwC5s> ``` Dropdown [Link 1](#) [Link 1](#) [Link 1](#) [Link 1](#) [Link 1](#) [Link 1](#) [Link 1](#) [Link 1](#) [Link 1](#) [Link 1](#) ... ``` The `boundary` is set to the `id` of the dropdown. Read more about [data-boundary](https://getbootstrap.com/docs/4.0/components/dropdowns/#options). --- Related questions: [Bootstrap 4: Why popover inside scrollable dropdown doesn't show?](https://stackoverflow.com/questions/49319865/bootstrap-4-why-popover-inside-scrollable-dropdown-doesnt-show) [Scrolling a dropdown in a modal in Bootstrap4](https://stackoverflow.com/questions/49168548/scrolling-a-dropdown-in-a-modal-in-bootstrap4) Upvotes: 5 [selected_answer]<issue_comment>username_2: ZimSystems got it almost right in Bootstrap 4.1. To disable the dropdown changing direction while open, aka. it's x-placement="bottom-end", you should use the "flip" option, instead of the "display" option. Display static disables the positioning entirely, while flip only disables the LIVE checks, that flip the dropdown upside down, when you scroll towards the top of the screen. Upvotes: 2 <issue_comment>username_3: I achieved this in Bootstrap 4.3.1 by adding `data-flip="false"` to the dropdown element. ex: `[dropdown](#)` Upvotes: 3 <issue_comment>username_4: In options, you can try to change `dropupAuto : true` to `dropupAuto : false`. <https://developer.snapappointments.com/bootstrap-select/options/#bootstrap-version> Upvotes: -1
2018/03/16
459
1,664
<issue_start>username_0: I'm using `ngx-perfect-scrollbar` with my Angular 5 project. I want to scroll the `div` to top when the route changes. **dashboard.html** ``` ``` **dashboard.ts** ``` @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', }) export class DashboardComponent implements OnInit { @ViewChild('perfectscroll') perfectscroll: PerfectScrollbarDirective; ngOnInit() { this.router.events.subscribe((evt) => { if (!(evt instanceof NavigationEnd)) { return; } this.perfectscroll.scrollToTop() }); } } ``` But I get this error : > > TypeError: \_this.perfectscroll.scrollToTop is not a function > > ><issue_comment>username_1: just use this: @ViewChild(PerfectScrollbarDirective) perfectscroll: PerfectScrollbarDirective; you will have instance and then you can call functions like scrollToTop() Upvotes: 2 <issue_comment>username_2: Look at my working example. In the trmplate: ``` ... ... ... ``` ... In the component: ``` @ViewChild('psLeft') psLeft: PerfectScrollbarDirective; @ViewChild('psRight') psRight: PerfectScrollbarDirective; ... if (this.psRight) { this.psRight.scrollToTop(); } ``` Upvotes: 3 <issue_comment>username_3: All of these solutions didn't work for me. I've fixed like below ``` scrollUp(): void { const container = document.querySelector('.main-panel'); container.scrollTop = 0; } ``` Upvotes: 0 <issue_comment>username_4: It worked for me ``` @ViewChild(PerfectScrollbarDirective, { static: false }) perfectScrollbarDirectiveRef?: PerfectScrollbarDirective; ``` Upvotes: 0
2018/03/16
1,329
4,298
<issue_start>username_0: I have some HTML (which I have no control over) coming from a DB and it contains lots of text and images. I need to insert a particular element before or after the first tag that has an `![]()` tag inside it. Here is an example of the HTML: ``` Nokia 8 4GB RAM 64GB Dual Sim Phone The Nokia 8 undergoes a rigorous 40-stage process of machining, anodizing and polishing to ensure its distinctive design pairs flawlessly with the polished aluminium unibody. The ultimate in seamless unibody construction, Nokia 8 is designed to nestle perfectly in the palm of your hand. [![](https://cdn2.gsmarena.com/vv/bigpic/nokia-8-.jpg)](https://www.nokia.com) We offer 14 days money back guarantee in case of a change of mind. I want to move this content ``` This is as far as I can get to moving the `div` before the `img` element but obviously it will never work because the img is wrapped in an anchor tag. So how would I get jQuery to insert the `div` before the first anchor element that has an image inside of it? ``` $(".movethisdiv").insertBefore( $("section.main").find("a > img").first()); ``` The above will insert the `div` before the `img` tag only, but within the `a` element. I want it to insertBefore the `a` element.<issue_comment>username_1: use [`.first()`](https://api.jquery.com/first/) and [`.parent()`](https://api.jquery.com/parent/) method here is example ```js $("a").find('img').first($(".movethisdiv").insertBefore($("section.main > a img:first").parent())); ``` ```html Nokia 8 4GB RAM 64GB Dual Sim Phone The Nokia 8 undergoes a rigorous 40-stage process of machining, anodizing and polishing to ensure its distinctive design pairs flawlessly with the polished aluminium unibody. The ultimate in seamless unibody construction, Nokia 8 is designed to nestle perfectly in the palm of your hand. [![](https://cdn2.gsmarena.com/vv/bigpic/nokia-8-.jpg)](https://www.nokia.com) We offer 14 days money back guarantee in case of a change of mind. I want to move this content ``` Upvotes: 1 <issue_comment>username_2: Add `.parent()` after `.first()` so something like this: `$(".movethisdiv").insertBefore( $("section.main").find("a > img").first().parent());` Upvotes: 2 [selected_answer]<issue_comment>username_3: You can use a filter: ```js $('.movethisdiv').insertBefore( $("section.main").find('a').filter(function() { // get all anchors in main return $(this).children('img').length; // filter out anchors with an image }).first()); // get the first one ``` ```css .movethisdiv { color: red; } ``` ```html Nokia 8 4GB RAM 64GB Dual Sim Phone [a test link](#) The Nokia 8 undergoes a rigorous 40-stage process of machining, anodizing and polishing to ensure its distinctive design pairs flawlessly with the polished aluminium unibody. The ultimate in seamless unibody construction, Nokia 8 is designed to nestle perfectly in the palm of your hand. [![](https://cdn2.gsmarena.com/vv/bigpic/nokia-8-.jpg)](https://www.nokia.com) We offer 14 days money back guarantee in case of a change of mind. I want to move this content ``` Upvotes: 1 <issue_comment>username_4: You can do something like this. Find all `img` that are inside an `a` , select first one, and select it's parent. Then insert the div before that parent ```js let firstAnchor = $("a img").first().parent() $(".movethisdiv").insertBefore(firstAnchor) ``` ```css .movethisdiv { color:red; font-size:20px; } ``` ```html Nokia 8 4GB RAM 64GB Dual Sim Phone The Nokia 8 undergoes a rigorous 40-stage process of machining, anodizing and polishing to ensure its distinctive design pairs flawlessly with the polished aluminium unibody. The ultimate in seamless unibody construction, Nokia 8 is designed to nestle perfectly in the palm of your hand. [![](https://cdn2.gsmarena.com/vv/bigpic/nokia-8-.jpg)](https://www.nokia.com) We offer 14 days money back guarantee in case of a change of mind. [![](https://cdn2.gsmarena.com/vv/bigpic/nokia-8-.jpg)](https://www.nokia.com) [![](https://cdn2.gsmarena.com/vv/bigpic/nokia-8-.jpg)](https://www.nokia.com) [![](https://cdn2.gsmarena.com/vv/bigpic/nokia-8-.jpg)](https://www.nokia.com) I want to move this content ``` Upvotes: 0
2018/03/16
4,235
13,588
<issue_start>username_0: i've been struggling with this issue for days now and i can't seem to find a way to solve it, here is the full error : ``` CommandInvokationFailure: Gradle build failed. C:/Program Files/Java/jdk1.8.0_131\bin\java.exe -classpath "C:\Program Files\Unity2017.2\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-2.14.jar" org.gradle.launcher.GradleMain "assembleDebug" stderr[ FAILURE: Build failed with an exception. * What went wrong: A problem occurred configuring root project 'gradleOut'. > failed to find Build Tools revision 28.0.0 * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. ] stdout[ BUILD FAILED Total time: 2.877 secs ] exit code: 1 UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.GradleWrapper.RunJava (System.String args, System.String workingdir, UnityEditor.Android.Progress progress) Rethrow as GradleInvokationException: Gradle build failed UnityEditor.Android.GradleWrapper.RunJava (System.String args, System.String workingdir, UnityEditor.Android.Progress progress) UnityEditor.Android.GradleWrapper.Run (System.String workingdir, System.String task, UnityEditor.Android.Progress progress) UnityEditor.Android.PostProcessor.Tasks.BuildGradleProject.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr) ``` here is my gradle.build content : ``` // GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.1.0' } } allprojects { repositories { flatDir { dirs 'libs' } } } apply plugin: 'com.android.application' dependencies { compile 'com.android.support:multidex:1.0.1' compile fileTree(dir: 'libs', include: ['*.jar']) compile(name: 'android.arch.core.runtime-1.1.0', ext:'aar') compile(name: 'android.arch.lifecycle.livedata-core-1.1.0', ext:'aar') compile(name: 'android.arch.lifecycle.runtime-1.1.0', ext:'aar') compile(name: 'android.arch.lifecycle.viewmodel-1.1.0', ext:'aar') compile(name: 'cardview-v7-25.3.1', ext:'aar') compile(name: 'com.android.support.animated-vector-drawable-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.appcompat-v7-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.asynclayoutinflater-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.cardview-v7-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.coordinatorlayout-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.cursoradapter-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.customtabs-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.customview-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.documentfile-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.drawerlayout-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.interpolator-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.loader-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.localbroadcastmanager-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.percent-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.print-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.recyclerview-v7-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.slidingpanelayout-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.support-compat-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.support-core-ui-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.support-core-utils-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.support-fragment-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.support-media-compat-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.support-v4-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.support-vector-drawable-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.swiperefreshlayout-28.0.0-alpha1', ext:'aar') compile(name: 'com.android.support.viewpager-28.0.0-alpha1', ext:'aar') compile(name: 'com.github.vungle.vungle-android-sdk-5.3.0', ext:'aar') compile(name: 'com.google.ads.mediation.unity-2.1.2.0', ext:'aar') compile(name: 'com.google.ads.mediation.vungle-5.3.0.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-ads-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-ads-license-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-ads-lite-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-ads-lite-license-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-base-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-base-license-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-basement-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-basement-license-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-gass-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-gass-license-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-gcm-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-gcm-license-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-iid-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-iid-license-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-location-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-location-license-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-tasks-11.8.0', ext:'aar') compile(name: 'com.google.android.gms.play-services-tasks-license-11.8.0', ext:'aar') compile(name: 'com.sglib.easymobile.easy-mobile-1.0.2', ext:'aar') compile(name: 'com.unity3d.ads.unity-ads-2.1.2', ext:'aar') compile(name: 'common', ext:'aar') compile(name: 'constraint-layout-1.0.2', ext:'aar') compile(name: 'GoogleAIDL', ext:'aar') compile(name: 'GooglePlay', ext:'aar') compile(name: 'onesignal-unity', ext:'aar') compile(name: 'percent-25.3.1', ext:'aar') compile(name: 'unity-ads', ext:'aar') compile project(':answers') compile project(':beta') compile project(':crashlytics') compile project(':crashlytics-wrapper') compile project(':fabric') compile project(':fabric-init') compile project(':GoogleMobileAdsPlugin') compile project(':OneSignalConfig') } android { compileSdkVersion 21 buildToolsVersion '28.0.0' defaultConfig { multiDexEnabled true targetSdkVersion 21 applicationId 'com.chorusworldwide.upjump' } lintOptions { abortOnError false } aaptOptions { noCompress '.unity3d', '.ress', '.resource', '.obb' } buildTypes { debug { minifyEnabled false useProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt' jniDebuggable true } release { minifyEnabled true useProguard true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt' } } } ``` for some reason it keeps overwriting its buildToolsVersion to "'28.0.0'" even that i specifically set the build settings to this : ![enter image description here](https://i.stack.imgur.com/64VQl.png) I also added my own gradle.build file to Plugin/Android which is the same file but with a different BuildToolsVersion set to 27.0.0, yet, still the build.gradle file located in Temp folder inside the project is resetting itself to "28", I also added my own gradle.build file to Plugin/Android which is the same file but with a different BuildToolsVersion set to 27.0.0, yet, still the build.gradle file located in Temp folder inside the project is resetting itself to "28", and finally here is some screenshots of my SDK manager : ![enter image description here](https://i.stack.imgur.com/2nuSw.png) The partially installed for Android (P) is because of this (i don't have to install them all isn't ?) : ![enter image description here](https://i.stack.imgur.com/TJSBW.png) the SDK tools : ![enter image description here](https://i.stack.imgur.com/Todmz.png) ![enter image description here](https://i.stack.imgur.com/PWF5J.png) ![enter image description here](https://i.stack.imgur.com/Q0GKd.png) ![enter image description here](https://i.stack.imgur.com/ijdHT.png) **UPDATE:** after removing 28.0.0-rc1 from build tools, the build.gradle start building with version 27, but now am getting a new error : ``` CommandInvokationFailure: Gradle build failed. C:/Program Files/Java/jdk1.8.0_131\bin\java.exe -classpath "C:\Program Files\Unity2017.2\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-2.14.jar" org.gradle.launcher.GradleMain "assembleDebug" stderr[ C:\Projects\UpJump\Temp\gradleOut\build\intermediates\exploded-aar\com.android.support.appcompat-v7-28.0.0-alpha1\res\values-v28\values-v28.xml:5:5-8:13: AAPT: No resource found that matches the given name (at 'dialogCornerRadius' with value '?android:attr/dialogCornerRadius'). FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':processDebugResources'. > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'D:\DevTools\New_SDK\build-tools\27.0.0\aapt.exe'' finished with non-zero exit value 1 * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. ] ```<issue_comment>username_1: The answer in the similar issue mentioned by @SawThinkarNayHtoo will get you most of the way. Here's that link again: [Importing Vufoira Scene into native android app](https://stackoverflow.com/questions/49106942/importing-vufoira-scene-into-native-android-app/49125433#49125433) The gist of it is you want to export your Unity project while targeting Android. There are great tutorials elsewhere about how to do this, but here's the link from the answer above: [Export Unity Project to Android Studio](https://bettercallunity.blogspot.in/2017/09/unity3d-tutorial-export-project-unity.html) After following the steps above, I needed one more step: 1. In Android Studio, open your exported project and go to Edit > Find > Find in Path... 2. Search for "buildToolsVersion" without the quotes. 3. Replace all instances of versions "buildToolsVersion '28" with "buildToolsVersion '27". If necessary, you can also edit the files without exporting. Search your project directory in the file system for "buildToolsVersion". You should find build.gradle files. Edit those as above. Upvotes: 2 <issue_comment>username_2: Solved it! my main issue was here : [![enter image description here](https://i.stack.imgur.com/r2hms.png)](https://i.stack.imgur.com/r2hms.png) see all these 28.0.0-alpha files, the problem start occurring because of these, i am 100% sure of it because when i rolled back (thankfully am using version control) one of the main differences was that these libraries weren't there, i deleted them, but they kept coming back due to the "Play Service Resolver", so i figured it has nothing to do with whatever version i have installed in my Android SDK and it was 100% related to one of the plugins. I created a new project, imported GoogleAdsMediation for Unity (that's the most important plugin) and did the "Resolving" thing, and there was no "28" files at all, so it wasn't google plugin, i kept doing with this with all the plugins we have. import -> delete all libraries -> force resolve. Until i found the culpable one, it was OneSignal, their dependencies configuration (or something) forced the resolver to import these "28.0.0-alpha" libraries, i deleted that version of OneSignal, imported an older one (from an older version of our project) and Boom! problem solved :) I hope this helps. cheers! Upvotes: 3 [selected_answer]<issue_comment>username_3: [username_1's answer](https://stackoverflow.com/a/49521245/5183414) got me most of the way there. But the solution for me was less complicated. I generated a mainTemplate.gradle file that unity creates when you turn on "use custom gradle file" in the player settings and changed the buildToolsVersion line. Original line in Assets/Plugins/Android/mainTemplate.gradle: > > `buildToolsVersion '**BUILDTOOLS**'` > > > New: > > `buildToolsVersion '27'` > > > Upvotes: 3 <issue_comment>username_4: I had the same issue, I was ok until I downloaded the latest 29 sdk build tools. I deleted the build tools from my sdks and it solved my problem Upvotes: 0
2018/03/16
572
2,156
<issue_start>username_0: ``` {!loading && (ad.status !== 'active' && ad.status !== 'paid') && display something base on not active and not paid } {!loading && ad.status === 'paid' && display content base on paid} {!loading && ad.status === 'active' && display content base on active} ``` I have above 3 condition and have 3 different block of html, above code just work but I felt the `!loading` declaration is too repeatable, how to improve code above? `!loading` is a must because I don't want to show anything before the API fetch is pending.<issue_comment>username_1: Consider splitting into it's own component/function and then do this: ``` if (loading) { return null; } {(ad.status !== 'active' && ad.status !== 'paid') && display something base on not active and not paid } {ad.status === 'paid' && display content base on paid} {ad.status === 'active' && display content base on active} ``` Upvotes: 0 <issue_comment>username_2: I would create a function like this: ``` function getContent(status) { switch (status) { case 'paid': return (display content base on paid); case 'active': return (display content base on active); default: return (display something base on not active and not paid); } } ``` ... and then change your code block into: ``` {!loading && getContent(ad.status)} ``` Upvotes: 2 <issue_comment>username_3: I really like [`recompose`](https://github.com/acdlite/recompose) for that: ``` const BaseComponent = ()=>( this is your most common case (blue sky scenario) ); // add special cases as branches const FinalComponent = compose( branch(({loading}) => loading, renderNothing)), branch(({ad}) => ad.paid, renderComponent(PaidContent))), branch(({ad}) => !ad.active, renderComponent(InactiveContent))), )(BaseComponent) ``` I might have mixed up which case is your normal case and which cases are the exceptions. But this gives you an idea of how it works. In our project our Base components never include loading and edge cases. This makes the normal case code a lot easier to read. Note: The order of the `branch` calls is important. Upvotes: 0
2018/03/16
1,044
3,527
<issue_start>username_0: I'm revising for an operating systems exam and currently trying to understand this processes question: ``` int main() { int v=0; if(fork()) { v++; if(!fork()) { fork(); v--; } } } ``` So the question asks to > > 1. Draw a tree reflecting the parent-child hierarchy of processes created when the program above is run. > 2. How many separate copies of the integer variable v are created? Discuss what is the value of v at the end of the program for each of the processes in the tree. > > > The main thing I'm having an issue with is the ``` if(fork()) ``` line in the code. From looking at other stack overflows I realised that ``` if(fork()) = if(fork() != 0) ``` but I'm still having difficulty understanding whether the first if statement creates a child process? Because thats the only way that the second if statement: ``` (!fork()) ``` can be executed? This is how far I've got with my current understanding of the question. [screenshot of attempt](https://i.stack.imgur.com/1C6Gl.png) [![enter image description here](https://i.stack.imgur.com/1C6Gl.png)](https://i.stack.imgur.com/1C6Gl.png) Hopefully the diagram is legible! I'd be really grateful for any hints or pointers with this.<issue_comment>username_1: Notice that `if (fork()) /*etc*/` is *exactly* the same as ``` pid_t newtmp = fork(); if (newtmp != 0) /*etc*/ ``` where `newtmp` is a fresh (new) variable name not occurring in your program (you could use `x1`, `x2` etc.... provided it has no occurrence in your program), and `pid_t` is some integral type (probably `int`). Once you rewrote your code with *explicit* and *unique* names given to result of `fork` you'll understand it better. BTW, the code is poor taste. When you use `fork` you need to handle *three* cases: * the `fork` failed (e.g. because your system has not enough memory, or because you exceeded some limits) and gives -1 * the `fork` succeeded in the child so gives 0 * the `fork` succeeded in the parent, so gives the pid of the child. But when you code `if (fork())` you are forgetting -or handling incorrectly- the first case (failure). It can *rarely* happen. Read *carefully* (and several times) the [fork(2)](http://man7.org/linux/man-pages/man2/fork.2.html) man page. Notice that [fork](https://en.wikipedia.org/wiki/Fork_(system_call)) is difficult to understand. Regarding limits, be aware of [setrlimit(2)](http://man7.org/linux/man-pages/man2/setrlimit.2.html) (and the `ulimit` bash builtin). Upvotes: 2 <issue_comment>username_2: The answer is ``` if (fork ()) ``` may or may determine whether a child process was created. Go to the man page: <http://man7.org/linux/man-pages/man2/fork.2.html> We find that fork () returns three types of values: * -1 => fork() failed * 0 => return value in the child process * a positive value => success and the PID of the child process. Thus the test ``` if (fork ()) ``` which is the same as if (fork () != 0) may succeed whether or not a child process was created. A competently written question would have said ``` if (fork () > 0) ``` Assuming everything works correctly: ``` int main() { int v=0; if(fork()) // Creates a child process that does nothing. { v++; if(!fork()) // Creates a child process that creates a child process (that then does nothing but decrement v). { fork(); v--; } } } ``` Upvotes: 0
2018/03/16
1,338
3,971
<issue_start>username_0: I have a similar question as asked here ([Strip suffix from all variable names in SPSS](https://stackoverflow.com/questions/34798827/strip-suffix-from-all-variable-names-in-spss)) and the answers there already helped a lot but there is still one question remaining. I have a dataset in which every variable name has the prefix "v23\_1\_". I want to remove this prefix from all variables, but there are hundreds of them, so I am looking for a way to do it without using the RENAME statement hundreds of times. I used this code: ``` begin program. vdict=spssaux.VariableDict() mylist=vdict.range(start="v23_1_dg_mnpdocid", end="v23_1_phq9t0_asku3t0") nvars = len(mylist) for i in range(nvars): myvar = mylist[i] mynewvar = myvar.strip("v23_1_") spss.Submit(r""" rename variables ( %s = %s) . """ %(myvar, mynewvar)) end program. ``` Here is a list of the first few variables: ``` v23_1_dg_mnppusid v23_1_dg_sigstatus v23_1_dg_mnpvsno v23_1_dg_mnpvslbl v23_1_dg_mnpcvpid v23_1_dg_mnpvisid v23_1_dg_mnpvisno v23_1_dg_mnpvispdt v23_1_dg_mnpvisfdt v23_1_dg_mnpfs0 v23_1_dg_mnpfs1 v23_1_dg_mnpfs2 v23_1_dg_mnpfs3 v23_1_dg_mnpfcs0 v23_1_dg_mnpfcs1 v23_1_dg_mnpfcs2 ``` It worked ok for the first variables but then stopped with the message "renaming has created two variables named dg\_mnpfs". But the next variable would after stripping has the name "dg\_mnpfs2". What has happened is that the 1 at the end in "v23\_1\_dg\_mnpfs1" gets deleted too. And then it propbably intends to also delete the 2 at the end in "v23\_1\_dg\_mnpfs2", which will then lead to the same variable. I don't understand why this is happening and how I can avoid it. Thanks a lot for your support! Kind regards, Beate<issue_comment>username_1: As you syntax looks right now, it will run on a variable-by-variable basis. You are submitting/running the `RENAME VARIABLES` command as many times as the number of variables in your list. On one hand, this is in-efficient, as it takes longer to run than what I am suggesting below. On the other (and more important) hand, doing it variable by variable, does not guard against duplicate variables. I am guessing that you already have in your datafile a variable named `dg_mnpfs`, and you are attempting to create a new one by renaming `v23_1_dg_mnpfs`. Just check your datafile, after your python code breaks. A more efficient way of writing you code would be to create lists with the old names, and new names, and submit the syntax with only one command. ``` begin program. import spss,spssaux vdict=spssaux.VariableDict() mylist=vdict.range(start="v23_1_dg_mnpdocid", end="v23_1_phq9t0_asku3t0") nvars = len(mylist) my_new_list=[] for i in range(nvars): myvar = mylist[i] mynewvar = myvar.strip("v23_1_") my_new_list.append(mynewvar) my_syntax="ren var (" + " ".join(mylist) + "=" + " ".join(my_new_list) +")." spss.Submit(my_syntax) end program. ``` And one more thing: the `strip` function removes the text from both ends of the variables. If you only want to remove the prefix, consider using `lstrip`. Details can be found [here, in the official documentation.](https://docs.python.org/2/library/string.html#string.lstrip) Upvotes: 3 [selected_answer]<issue_comment>username_2: Here's a version of the process using SPSS macro. Using `SPSSINC SELECT VARIABLES` lets you get the whole list of all relevant variables, whatever order they are in, without naming them in the command: ``` *this is just to create a sample data to play with. data list list/v23_1_var1 to v23_1_var6. begin data end data. ``` The following creates a list of the relevant variables: ``` SPSSINC SELECT VARIABLES MACRONAME="!list" /PROPERTIES PATTERN = "v23_1_*". * the following macro creates one rename command for all the list. define !doRename () rename variables (!eval(!list)=!do !i !in(!eval(!list)) !substr(!i, 7) !doend). !enddefine. !doRename . ``` Upvotes: 1
2018/03/16
1,102
4,099
<issue_start>username_0: This is my migration file ``` php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateSessionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('sessions', function (Blueprint $table) { $table-string('id')->unique(); $table->text('payload'); $table->integer('last_activity'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('sessions'); } } ``` It was created when i ran ``` php artisan session:table ``` The database connection is correctly configured since the project is writing and reading from it without problem. From the root directory of my project i run ``` php artisan migrate ``` And i get the following error messages ``` [Illuminate\Database\QueryException] SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'sessions' already exists (SQL: create table `sessions` (`id` varchar(255) not null, `payload` text not null, `last_activity` int not null) default character set utf8 collate utf8_unicode_ci) [PDOException] SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'sessions' already exists ``` I know i should run ``` composer dump-autoload ``` But i've tried with and without it and i got the same results. I've also tried the Blueprint type before the $table argument. It bahaves as if it was accessing some different database than the one it uses when i ran the project<issue_comment>username_1: As you syntax looks right now, it will run on a variable-by-variable basis. You are submitting/running the `RENAME VARIABLES` command as many times as the number of variables in your list. On one hand, this is in-efficient, as it takes longer to run than what I am suggesting below. On the other (and more important) hand, doing it variable by variable, does not guard against duplicate variables. I am guessing that you already have in your datafile a variable named `dg_mnpfs`, and you are attempting to create a new one by renaming `v23_1_dg_mnpfs`. Just check your datafile, after your python code breaks. A more efficient way of writing you code would be to create lists with the old names, and new names, and submit the syntax with only one command. ``` begin program. import spss,spssaux vdict=spssaux.VariableDict() mylist=vdict.range(start="v23_1_dg_mnpdocid", end="v23_1_phq9t0_asku3t0") nvars = len(mylist) my_new_list=[] for i in range(nvars): myvar = mylist[i] mynewvar = myvar.strip("v23_1_") my_new_list.append(mynewvar) my_syntax="ren var (" + " ".join(mylist) + "=" + " ".join(my_new_list) +")." spss.Submit(my_syntax) end program. ``` And one more thing: the `strip` function removes the text from both ends of the variables. If you only want to remove the prefix, consider using `lstrip`. Details can be found [here, in the official documentation.](https://docs.python.org/2/library/string.html#string.lstrip) Upvotes: 3 [selected_answer]<issue_comment>username_2: Here's a version of the process using SPSS macro. Using `SPSSINC SELECT VARIABLES` lets you get the whole list of all relevant variables, whatever order they are in, without naming them in the command: ``` *this is just to create a sample data to play with. data list list/v23_1_var1 to v23_1_var6. begin data end data. ``` The following creates a list of the relevant variables: ``` SPSSINC SELECT VARIABLES MACRONAME="!list" /PROPERTIES PATTERN = "v23_1_*". * the following macro creates one rename command for all the list. define !doRename () rename variables (!eval(!list)=!do !i !in(!eval(!list)) !substr(!i, 7) !doend). !enddefine. !doRename . ``` Upvotes: 1
2018/03/16
757
2,538
<issue_start>username_0: I have this function below, where I want to define T as a class. Is this possible. The IsActive and RecordStatusCode are in every model class. Is it possible to query this way. Thanks ``` public IQueryable GetActive() { return DbContext.Set().Where(x => x.IsActive && x.RecordStatusCode == "A"); } ```<issue_comment>username_1: As you syntax looks right now, it will run on a variable-by-variable basis. You are submitting/running the `RENAME VARIABLES` command as many times as the number of variables in your list. On one hand, this is in-efficient, as it takes longer to run than what I am suggesting below. On the other (and more important) hand, doing it variable by variable, does not guard against duplicate variables. I am guessing that you already have in your datafile a variable named `dg_mnpfs`, and you are attempting to create a new one by renaming `v23_1_dg_mnpfs`. Just check your datafile, after your python code breaks. A more efficient way of writing you code would be to create lists with the old names, and new names, and submit the syntax with only one command. ``` begin program. import spss,spssaux vdict=spssaux.VariableDict() mylist=vdict.range(start="v23_1_dg_mnpdocid", end="v23_1_phq9t0_asku3t0") nvars = len(mylist) my_new_list=[] for i in range(nvars): myvar = mylist[i] mynewvar = myvar.strip("v23_1_") my_new_list.append(mynewvar) my_syntax="ren var (" + " ".join(mylist) + "=" + " ".join(my_new_list) +")." spss.Submit(my_syntax) end program. ``` And one more thing: the `strip` function removes the text from both ends of the variables. If you only want to remove the prefix, consider using `lstrip`. Details can be found [here, in the official documentation.](https://docs.python.org/2/library/string.html#string.lstrip) Upvotes: 3 [selected_answer]<issue_comment>username_2: Here's a version of the process using SPSS macro. Using `SPSSINC SELECT VARIABLES` lets you get the whole list of all relevant variables, whatever order they are in, without naming them in the command: ``` *this is just to create a sample data to play with. data list list/v23_1_var1 to v23_1_var6. begin data end data. ``` The following creates a list of the relevant variables: ``` SPSSINC SELECT VARIABLES MACRONAME="!list" /PROPERTIES PATTERN = "v23_1_*". * the following macro creates one rename command for all the list. define !doRename () rename variables (!eval(!list)=!do !i !in(!eval(!list)) !substr(!i, 7) !doend). !enddefine. !doRename . ``` Upvotes: 1
2018/03/16
1,525
4,551
<issue_start>username_0: I am currently having trouble with some styling and i'm looking for some help. Currently i have a couple of divs which are separated by a grey line, however the content of the div doesn't sit vertically in the middle (i have looked to implement other things online but still can't get it to work for some reason). I also have an image that needs to be to the left of the title and text (and centred as above) but just can't get it to work! I have attached my code and screenshots to make it a bit clearer :) Any help would be appreciated - thanks! ```css .search-result__grey-seperator { padding: 10px 0; border-bottom: 1px solid #e2e2e2; width: 100%; font-size: 16px; line-height: 26px; list-style-type: none; margin: 5 0; } .search-result__question { font-size: 22px; font-weight: normal; text-transform: uppercase; } .search-result__answer { font-size: 20px; } .search-result__image { height: auto; width: 100px; float: left; display: inline-block; margin-right: 20px; } .search-result__info-container { display: inline-block; } /* //Search.scss .search-result__grey-seperator { padding: 10px 0; border-bottom: 1px solid #e2e2e2; width: 100%; font-size: 16px; line-height: 26px; list-style-type: none; margin: $vr*5 0; } .search-result__question { font-size: 22px; font-weight: normal; text-transform: uppercase; } .search-result__answer { font-size: 20px; } .search-result__image { height: auto; width: 100px; float: left; display: inline-block; margin-right: 20px; } .search-result__info-container { display: inline-block; }*/ ``` ```html ![](http://via.placeholder.com/240x180) ### some text some text lorem ipsum lorem ipsum lorem ipsum - ``` //The image looks centred on this example but needs to be consistent rather than its side, as you can tell the spacing above the grey line is larger and needs to be the same across all divs (if that makes sense, let me know if it doesn't) [![enter image description here](https://i.stack.imgur.com/1a62Z.png)](https://i.stack.imgur.com/1a62Z.png) //Image needs to be to the left and content to the right at all times, at the minute it wraps incorrectly [![enter image description here](https://i.stack.imgur.com/uzUyj.png)](https://i.stack.imgur.com/uzUyj.png)<issue_comment>username_1: If the {result.Title} and {result.Summary} are single line you could try to do it like this: ```css .search-result__info-container { display: inline-block; top: calc(50% - 73px); position: absolute; } ``` Edit: I'm not sure what you want with the images, but at least one of them should be static of size. See below for another possible implementation. ```css .search-result{ position: relative; } .search-result__question { font-size: 22px; font-weight: normal; text-transform: uppercase; margin-top: 18px; } .search-result__info-container { display: inline-block; width: calc(100% - 120px); height: 95px; margin-left: 120px; } .search-result__image { width: 100px; float: left; display: inline-block; margin-right: 20px; max-width: 100px; position: absolute; top: calc(50% - 43px); height: 75px; } .search-result__grey-seperator { padding: 11px 0; border-bottom: 1px solid #e2e2e2; width: 100%; font-size: 16px; line-height: 27px; list-style-type: none; } ``` ```html ![](http://via.placeholder.com/240x180) ### some text some text lorem ipsum lorem ipsum lorem ipsum - ``` Upvotes: 1 <issue_comment>username_2: Something like this? I don't know if you can change the image to a div and set it with `background-image` like I did though. **Edit:** I guess not. ```css .search-result { display: flex; } .search-result__image { background-image: url('http://via.placeholder.com/240x180'); background-repeat: no-repeat; background-size: cover; background-position: center; flex: 0 0 100px; margin-right: 20px; } .search-result__question { font-size: 22px; font-weight: normal; text-transform: uppercase; margin: 0; } .search-result__answer { font-size: 20px; margin: 5px 0 0 0; } .search-result__grey-seperator { padding: 10px 0; border-bottom: 1px solid #e2e2e2; } ``` ```html ### some text some text some text some text some text lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum ``` Upvotes: -1
2018/03/16
717
2,785
<issue_start>username_0: I am trying to obtain some effeciency improvements by changing this line in my fsharp syntax file (from [this](https://github.com/fsharp/vim-fsharp) plugin) from: ``` syn match fsharpModule "\%(\ ``` to ``` syn match fsharpModule "\%(\ ``` since the docs on the "\@<=" construct states that: > > For speed it's often much better to avoid this multi. Try using "\zs" instead |/\zs|. > > > However, this doesn't work and there is no highligting for ``` open SomeModule ``` How can this be? Doing a regular search in vim (with /) highligts the 'SomeModule' both when using the first and the second match pattern.<issue_comment>username_1: In the [Vim docs for the `\@<=` construct](http://vimdoc.sourceforge.net/htmldoc/pattern.html#/%5C@%3C=), the example of using `\zs` omits the parentheses that had been present in the equivalent pattern match using `\@<=`. I'm just guessing, but what happens if you try the following syntax match? ``` syn match fsharpModule "\ ``` Upvotes: 2 <issue_comment>username_2: As described in `:help syn-mult-line`, `\zs` has a few restrictions in a syntax command: > > When using a start pattern with an offset, the start of the match is not allowed to start in a following line. The highlighting can start in a following line though. Using the "\zs" item also requires that the start of the match doesn't move to another line. > > > so very likely `@<=` is is the best possible solution. Upvotes: 0 <issue_comment>username_3: This is caused by the syntax containment and because another syntax group exists for the `open` keyword that you're trying to assert. Within syntax highlighting, `\zs` only affects the result (what Vim will highlight with the syntax group); the whole pattern (i.e. including the text before the `\zs`) is treated as the match when it comes to relationships with other syntax groups. (This implementation detail is not explicitly documented in the help.) The *positive lookbehind assertion* (`\%(...\)\@<=`), by contrast, is neither included in the result nor the actual match. That explains the difference in behavior that you see. (It has nothing to do with the optional grouping, as @username_1 suspected, nor with multiple lines as per @Sergio's answer, as `\s\+` will not allow a linebreak in between.) I think ease of implementation is more important here, so it should be fine to use `\@<=`, even though the help recommends `\zs`. If you're willing to completely restructure the syntax script, this could be solved with something along these lines, assuming there's a `syntax keyword fsharpOpen open` somewhere: ``` syntax keyword fsharpOpen nextgroup=fsharpModule skipwhite open syntax match fsharpModule "[a-zA-Z.]\+" contained ``` Upvotes: 2
2018/03/16
757
2,635
<issue_start>username_0: I am using <https://github.com/daneden/animate.css> this css class to animate the boxes in grid.If a user clicks on "Fahrenheit to Celsius conversion" then the box with fahtocel id moves.Same for second box , It works well what I have written but Itmakes no sense to write javascript function for each box, Is there a way to get id of clicked div and relate it with the box which has to move in one function. ```js function bounce() { $("#fahtocel").addClass("animated bounce"); setTimeout(function() { $("#fahtocel").removeClass("animated"); $("#fahtocel").removeClass("bounce"); }, 1000); setTimeout(genQuote(), 5000); } function bounce2() { $("#box2").addClass("animated bounce"); setTimeout(function() { $("#box2").removeClass("animated"); $("#box2").removeClass("bounce"); }, 1000); setTimeout(genQuote(), 5000); } ``` ```html * Fahrenheit to Celsius conversion * Box 2 * Lorem 3 ```<issue_comment>username_1: You can make this function, and call it twice when needed: ``` function bounceBox($box){ $box.addClass("animated bounce"); setTimeout(function(){ $box.removeClass("animated"); $box.removeClass("bounce"); }, 1000); setTimeout(genQuote, 5000); } bounceBox($('#fahtocel')); bounceBox($('#box2')); ``` There is probably more that can be done, but you didn't show the code for it. Upvotes: 2 <issue_comment>username_2: You can pass the ID (as a string/text) for the DIVs you want to change as a parameter to the function. HTML `onclick="bounce('fahtocel')"` JavaScript `function bounce( elementID ){ ... }` jQuery `$('#' + elementID)` As an aside, I also turned your first DIVs into buttons -- not something that you have to do, its just nice to use buttons for things that need to be clicked instead of shoe-horning that functionality into a DIV. ```js function bounce( elementID ) { var target = $('#' + elementID ); target.addClass("animated bounce"); setTimeout(function() { target.removeClass("animated"); target.removeClass("bounce"); }, 1000); setTimeout(function(){ genQuote( elementID ); }, 5000); } function genQuote( elementID ){ // you can pass the string for the ID to another // function. it's just like a variable, but you // need to make sure your function will send and // receive them as nessecary. $('#' + elementID ).html( new Date() ); // this is just randomly putting in the current date // and time to show an update. } ``` ```html * Fahrenheit to Celsius conversion * Box 2 * Lorem 3 ``` Upvotes: 1 [selected_answer]
2018/03/16
508
2,022
<issue_start>username_0: Comparing these statements ``` SELECT * FROM Table WHERE (field IS NULL OR field = 'empty_value') ``` vs. ``` SELECT * FROM Table WHERE COALESCE(field, 'empty_value') = 'empty_value' ``` in terms of performance, which one is better? Is there any difference? I already know the first one requires a slightly more complex filter operation, while the second one needs +1 scalar computation prior the filter. The performance impacts of doing this in a single table are insignificant, but what may happen when the query is complex? And when there are multiple fields in this situation? Should I prefer one over the other? PS: I am using `'empty_value'` as a generic way to describe a situation where the absence of a particular value (`=NULL`) and a particular value (`='empty_value'`) have the same meaning for the query. Changing anything in the table design or how it stores its values is not an option. PS2: I am using SQL Server, but I would like to get a more generic answer about this issue. But, I would stick to SQL Server if the answer is implementation dependent.<issue_comment>username_1: The `COALESCE()` precludes the use of an index (i.e. it is not sargable). The `OR` offers the chance of using an index. However, this might get complicated if there are other conditions in the query. Benchmarking the solution in one case will not give a definitive answer. If indexes are not an issue, I would not expect the performance to differ very much. However, the short-circuiting of the `OR` would give it an advantage even in that case. Upvotes: 2 <issue_comment>username_2: Not an answer as such, but this is too much information for a comment and it is relevant to the question. There is a third option which springs to mind in this instance: ``` SELECT * FROM Table WHERE field IS NULL UNION ALL SELECT * FROM Table WHERE field = 'empty_value' ``` This is sargable but splits the query into two parts, so it's up to you to test all the alternatives you have. Upvotes: 0
2018/03/16
491
1,814
<issue_start>username_0: I am building a game, and would like to know: How to know if an Android device is plugged-in (i.e. battery is charging) using C# pure code in Unity?<issue_comment>username_1: In Android, you can use [SystemInfo.batteryStatus](https://docs.unity3d.com/ScriptReference/SystemInfo-batteryStatus.html), checking for the value [BatteryStatus.Charging](https://docs.unity3d.com/ScriptReference/BatteryStatus.Charging.html). Look here for the other possible status: <https://docs.unity3d.com/ScriptReference/BatteryStatus.html> Upvotes: 2 <issue_comment>username_2: Device is plugged in: ``` SystemInfo.batteryStatus == BatteryStatus.Charging || SystemInfo.batteryStatus == BatteryStatus.Full || SystemInfo.batteryStatus == BatteryStatus.NotCharging ``` Battery is charging: ``` SystemInfo.batteryStatus == BatteryStatus.Charging ``` Sources: <https://docs.unity3d.com/ScriptReference/SystemInfo-batteryStatus.html> > > Returns the current status of the device's battery (Read Only). > > > See the BatteryStatus enumeration for possible values. > > > **The battery status includes information about whether the device is plugged in to a power source and whether the battery is charging**. If battery status is not available on your target platform, this property returns BatteryStatus.Unknown. > > > <https://docs.unity3d.com/ScriptReference/BatteryStatus.html> * Unknown The device's battery status cannot be determined. If battery status is not available on your target platform, SystemInfo.batteryStatus will return this value. * **Charging Device is plugged in and charging.** * Discharging Device is unplugged and discharging. * **NotCharging Device is plugged in, but is not charging.** * **Full Device is plugged in and the battery is full.** Upvotes: 4 [selected_answer]
2018/03/16
235
793
<issue_start>username_0: I have a list ``` *ngFor="let h of list" ``` Depending on the type of the item "h.type" I want to use a different component to display details. How do I load the component?<issue_comment>username_1: You can use ng-template for that. E.g. ``` ``` Upvotes: 0 <issue_comment>username_2: You can accomplish this by using \*ngIf And load components with their selectors directly in html. ``` ``` Component 1 is going to be displayed when h.type is car and component 2 is going to be displayed when h.type is truck. Upvotes: 0 <issue_comment>username_3: Here is how you could do it with an [`NgSwitch`](https://angular.io/api/common/NgSwitch): ``` ``` You might be able to skip the `ng-container` but I haven't tested that: ``` ``` Upvotes: 2 [selected_answer]
2018/03/16
636
2,468
<issue_start>username_0: In this code I implement to add sale, in one sale I have and produts, these products I has in an array Products, and display in this table. My problem is, when I add some products, my value, price, quantity and total display ok, but I can't change my total automatic when I can change quantity or price. I tired to use [(ngModel)] in [Value] I can change my total, but my value are the same, like in photo [![enter image description here](https://i.stack.imgur.com/CyzBe.png)](https://i.stack.imgur.com/CyzBe.png) Edit code html ``` | | | | | Total {{total}} ALL ``` For `{{total}}` I call this function in ts: Code ts: ``` this.addsale = this.fb.group({ 'invoice_number': new FormControl('', [Validators.required, Validators.nullValidator]), 'amount_paid': new FormControl('', Validators.required), 'notes': new FormControl('', Validators.required), 'Subtotal': new FormControl('', Validators.required), 'products': this.fb.array([]), 'total': new FormControl('', Validators.required), 'Unit_price': new FormControl('', Validators.required), 'Quantity': new FormControl('', Validators.required), 'Description': new FormControl('', Validators.required) }); } ngOnInit() { this.products = this.ps.getProduct(); console.log(this.products) this.pts.getAllProductType().subscribe( producttype => { this.producttype = producttype; } ); } onaddsale() { } get total() { let Total = 0; for (let p of this.products) { Total += p.Unit_price * p.Quantity; } return Total; } } ``` Can you suggest me how to implement update total when I change quantity or unie\_price? Thank you<issue_comment>username_1: You can use ng-template for that. E.g. ``` ``` Upvotes: 0 <issue_comment>username_2: You can accomplish this by using \*ngIf And load components with their selectors directly in html. ``` ``` Component 1 is going to be displayed when h.type is car and component 2 is going to be displayed when h.type is truck. Upvotes: 0 <issue_comment>username_3: Here is how you could do it with an [`NgSwitch`](https://angular.io/api/common/NgSwitch): ``` ``` You might be able to skip the `ng-container` but I haven't tested that: ``` ``` Upvotes: 2 [selected_answer]
2018/03/16
265
954
<issue_start>username_0: I have installed Azure VM Agents plugin. I want to use a customized VM image as source. (VM with Visual studio and some other tools installed). There is an option in "Image Configuration" to use "Custom Image URI". How can I prepare a vhd from a well provisioned/Configured VM in Azure to be used as "Custom Image URL" in this case.<issue_comment>username_1: You can use ng-template for that. E.g. ``` ``` Upvotes: 0 <issue_comment>username_2: You can accomplish this by using \*ngIf And load components with their selectors directly in html. ``` ``` Component 1 is going to be displayed when h.type is car and component 2 is going to be displayed when h.type is truck. Upvotes: 0 <issue_comment>username_3: Here is how you could do it with an [`NgSwitch`](https://angular.io/api/common/NgSwitch): ``` ``` You might be able to skip the `ng-container` but I haven't tested that: ``` ``` Upvotes: 2 [selected_answer]
2018/03/16
481
1,670
<issue_start>username_0: I'm new to this. I have created a navigation form with 3 tabs. when I click on one tab it opens a pop-up form where I chose a record from a drop-down. when I click on a command button to "open file" I want the form to open in the tabs 'sub-form window'. at the moment all it does is opens in a separate window. how do I get the form to open in the navigation sub-form window where it is linked, with the correct information in the fields based on the combo box? ``` Private Sub Amend_record_Click() On Error GoTo Err_Amend_record_Click Dim stDocName As String Dim stLinkCriteria As String vFormName = Screen.ActiveForm.Name stDocName = "invoice_amend" vtest = Me![Combo0] stLinkCriteria = "[InvoiceID]=" & Me![Combo0] DoCmd.OpenForm stDocName, acNormal, , , acFormEdit, , stLinkCriteria Forms![navigation_form]!NavigationButton18.SetFocus DoCmd.Close acForm, vFormName Exit_Amend_record_Click: Exit Sub Err_Amend_record_Click: MsgBox Err.Description Resume Exit_Amend_record_Click End Sub ```<issue_comment>username_1: You can use ng-template for that. E.g. ``` ``` Upvotes: 0 <issue_comment>username_2: You can accomplish this by using \*ngIf And load components with their selectors directly in html. ``` ``` Component 1 is going to be displayed when h.type is car and component 2 is going to be displayed when h.type is truck. Upvotes: 0 <issue_comment>username_3: Here is how you could do it with an [`NgSwitch`](https://angular.io/api/common/NgSwitch): ``` ``` You might be able to skip the `ng-container` but I haven't tested that: ``` ``` Upvotes: 2 [selected_answer]
2018/03/16
493
1,475
<issue_start>username_0: I want to make a switch statement for in my code whose cases go over a wide span of integers (1-15000) split into 3 sections: 1-5000,5001-10000,10001-15000. I tried it once like this: ``` switch(number) { case 1 ... 1000: (statement here); ``` This gave me a syntax error on the "..."- "expected a :". Then I tried: ``` switch (number) { case 1: case 5000: (statement); break; ``` This method did compile but didn't work as intended, wrong answer for the cases which were not explicitly listed. Couldn't find any other suggestions online. Can anyone help?<issue_comment>username_1: This is not possible in standard C, although some compilers offer switching on a range as a compiler extension1. The idiomatic way in your case is to write ``` if (number < 1){ // oops } else if (number <= 5000){ // ToDo } else if (number <= 10000){ // ToDo } else if (number <= 15000){ // ToDo } else { // oops } ``` Or a very crude way would be to write `switch((number - 1) / 5000)` which exploits integer division: mapping the cases you need to deal with to 0, 1, and 2. --- 1 <https://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html> Upvotes: 4 [selected_answer]<issue_comment>username_2: As @UnholySheep said in the comments, you cannot do this. Not with standard C. Try using if: ``` if (my_variable >= minumum_value && my_variable <= maximum_value) { // Do something } else { // Do something else } ``` Upvotes: 1
2018/03/16
2,040
7,805
<issue_start>username_0: i've been trying to solve this problem for a while, tried other solutions used for the same error code but it isn't working. It's a team project and the same code works for one person but gradle bootrun gives this error to 3 other people when trying it on our own computers. Stacktrace: ``` FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':bootRun'. > Process 'command 'C:\Program Files\Java\jdk1.8.0_162\bin\java.exe'' finished with non-zero exit value 1 * Try: Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Exception is: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':bootRun'. at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:103) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:73) at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51) at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59) at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54) at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59) at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101) at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44) at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:88) at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54) at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43) at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34) at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248) at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336) at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328) at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199) at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110) at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241) at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98) at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:623) at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:578) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63) at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46) at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55) Caused by: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_162\bin\java.exe'' finished with non-zero exit value 1 at org.gradle.process.internal.DefaultExecHandle$ExecResultImpl.assertNormalExitValue(DefaultExecHandle.java:389) at org.gradle.process.internal.DefaultJavaExecAction.execute(DefaultJavaExecAction.java:36) at org.gradle.api.tasks.JavaExec.exec(JavaExec.java:74) at org.springframework.boot.gradle.tasks.run.BootRun.exec(BootRun.java:51) at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73) at org.gradle.api.internal.project.taskfactory.StandardTaskAction.doExecute(StandardTaskAction.java:46) at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39) at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26) at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:788) at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:755) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:124) at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336) at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328) at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199) at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:113) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:95) ... 30 more * Get more help at https://help.gradle.org BUILD FAILED in 10s 3 actionable tasks: 1 executed, 2 up-to-date ```<issue_comment>username_1: It means the *run()* method inside your Spring boot application threw an exception. My guess is that some spring bean failed to initialize due to differences in how your environments are set up. There's no way tell though based on gradle stacktrace. Post the code/error from the actual springboot app. Upvotes: 2 <issue_comment>username_2: I think the internal tomcat is busy with another instance server. If you are running multiple projects or instances via Intellij Idea .. just stop them. Upvotes: 0 <issue_comment>username_3: It looks like that your application is exiting with 1 and the application is not logging the reason for some reason. (Probably the issue was happened before your logger was initialized.) To find out the root cause of the error put your Spring Boot Application's main function's content in a try-catch and in the catch: ``` catch (Throwable t) { System.out.println(t.getMessage()); t.printStackTrace(); } ``` Upvotes: 2
2018/03/16
799
2,101
<issue_start>username_0: I have a string as `key1(value1) key2(vallue2) key3(value3) key4(value4) key5(value5) k` and would like to extract them into a dictionary as below. I am able to extract values inside and outside of parentheses separately but not able to correlate and create the dictionary in python. Please assist. ``` result = { "key1" : "value1", "key2" : "value2", "key3" : "value3", "key4" : "value4", "key5" : "value5", } ```<issue_comment>username_1: 1. Your key-value pairs are apparently delimited with the sequence `') '` between them, so `re.split()` is a nice choice for the first step, with `'\)\s\+'` as a pattern. And remember to first trim the trailing ')', to not corrupt the last value. 2. When you split the string on that regular expression, well, simply iterate through the results list and push each key-value pair into the dictionary. String's `split()` method can be used to split a list item into a key-value pair with `'('` as separator (and maxsplit 1, for you don't expect any more opening parentheses in the item). Upvotes: 0 <issue_comment>username_2: A solution using `regex`: ``` import re s = "key1(value1) key2(value2) key3(value3) key4(value4) key5(value5)" keys = re.findall(r"([A-Za-z0-9_]+)\(", s) values = re.findall(r"\(([A-Za-z0-9_]+)\)", s) result = {k: v for k, v in zip(keys, values)} print(result) # {'key1': 'value1', # 'key2': 'value2', # 'key3': 'value3', # 'key4': 'value4', # 'key5': 'value5'} ``` Upvotes: 0 <issue_comment>username_3: [See code in use here](https://tio.run/##VczN<KEY>) ``` import re s = "key1(value1) key2(vallue2) key3(value3) key4(value4) key5(value5) k" r = re.findall(r"(\w+)\(([^)]+)", s) print(dict(zip([x[0] for x in r], [x[1] for x in r]))) ``` Result: ``` {'key1': 'value1', 'key2': 'vallue2', 'key3': 'value3', 'key4': 'value4', 'key5': 'value5'} ``` Upvotes: 2 [selected_answer]
2018/03/16
1,456
3,761
<issue_start>username_0: I'm currently collecting timestamp's using an android application which for some users stored the timezone as for example "GMT+03:00" browsing online I found this is not a proper timezone and because of that when trying to build a datetime object in python using ``` from datetime import datetime from dateutil import tz import pandas as pd filename="data.csv" data=pd.read_csv(filename) [ datetime.fromtimestamp(data['timestamp'].iloc[i], tz=tz.gettz(data['timezone'].iloc[i])) for i in range(data.shape[0]) ] ``` does not work well. For example using that datetime object as index to create a Pandas dataframe in order to use the rolling window feature does not work. Any idea how to transform the "GMT+03:00" into a proper timezone or some way to incorporate that information to build correctly a datetime object? update: Here is a sample of `data['timestamps']`: ``` [1520719558.0, 1520719558.0, 1520719558.0, 1520719558.0, 1520719561.0, 1520719561.0, 1520719561.0, 1520719561.0, 1520719562.0, 1520719562.0] ``` and a sample of `data['timezone']`: ``` ['GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00'] ```<issue_comment>username_1: ``` #!/usr/bin/python3.5 import pandas as pd import re import datetime as dt # From username_2 solution def get_tz(s): '''Returns a datetime.timezone object. Uses regular expression to extract the UTC offset from s. Assumes s is in the form of "GMT+03:00" or "GMT-03:00". Does NOT have exception handling. ''' pattern = r'GMT([+-])(\d{1,2}):(\d{1,2})' match = re.match(pattern, s) sign, hh, mm = match.groups() hh, mm = map(int, (hh, mm)) t_delta = dt.timedelta(hours=hh, minutes=mm) t_delta = t_delta * (1 if sign == '+' else -1) return dt.timezone(t_delta) timestamps = [1520719558.0, 1520719558.0, 1520719558.0, 1520719558.0, 1520719561.0, 1520719561.0, 1520719561.0, 1520719561.0, 1520719562.0, 1520719562.0] timezones = ['GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00', 'GMT+03:00'] data = zip(timestamps, timezones) data_df = pd.DataFrame(list(data), columns=['timestamp', 'timezone']) # Converts timezone to date object data_df['timezone'] = data_df['timezone'].apply(lambda x:get_tz(x)) # Adding a new-column in the dataframe with the datetime format requested data_df['date_time'] = [dt.datetime.fromtimestamp(row['timestamp'], row['timezone']) for (_, row) in data_df[['timestamp', 'timezone']].iterrows() ] ``` Upvotes: 1 <issue_comment>username_2: GMT and UTC are the same. You could do it *manually*: write a function to extract the offset and return a `datetime.timezone`. ``` import datetime, re def get_tz(s): '''Returns a datetime.timezone object. Uses regular expression to extract the UTC offset from s. Assumes s is in the form of "GMT+03:00" or "GMT-03:00". Does NOT have exception handling. ''' pattern = r'GMT([+-])(\d{1,2}):(\d{1,2})' match = re.match(pattern, s) sign, hh, mm = match.groups() hh, mm = map(int, (hh, mm)) t_delta = datetime.timedelta(hours=hh, minutes=mm) t_delta = t_delta * (1 if sign == '+' else -1) return datetime.timezone(t_delta) ``` Usage: ``` >>> timestamp = 1520719558.0 >>> timezone = 'GMT+03:00' >>> dt = datetime.datetime.fromtimestamp(timestamp, get_tz(timezone)) >>> dt.isoformat() '2018-03-11T01:05:58+03:00' >>> timezone = 'GMT-03:00' >>> dt = datetime.datetime.fromtimestamp(timestamp, get_tz(timezone)) >>> dt.isoformat() '2018-03-10T19:05:58-03:00' ``` Upvotes: 2
2018/03/16
796
3,094
<issue_start>username_0: There are some huge legacy systems whose dependencies on PHPs' `mcrypt` are extremely important and vital (including the data storage in database). I need to find a way to maintain this library while upgrading to PHP 7.2 (which already worked fine). My local test environment is Windows. The live environment is run on CentOS. Some of the answers I have seen is decrypting and change mcrypt to openssl (*I think that's not possible at the moment since there's a lot of data to decrypt*). Another way lights to download a lower PHP version with `mcrypt`-support, copy the extension and add it to php.ini (I do not even know the folder). Downgrading PHP to 5.6 it's not suitable due to security issues. Any light in what could be done in this scenario?<issue_comment>username_1: Basically I think you have mentioned all possibilities and you do not have a choice. ***Do not downgrade to PHP 5.6 this approach has no future***. MCrypt was removed from PHP for one of the main reasons why you want to upgrade PHP: Security. The MCrypt library is not maintained anymore. ***Therefore installing the MCrypt extension is also a bad idea***. But it can be a temporary solution (follow e.g. those instructions <https://serverpilot.io/community/articles/how-to-install-the-php-mcrypt-extension.html>). The ***only good solution is migrating from mcrypt to something*** else. There are questions regarding this topic on Stackoverflow already (e.g. [Upgrading my encryption library from Mcrypt to OpenSSL](https://stackoverflow.com/questions/43329513/upgrading-my-encryption-library-from-mcrypt-to-openssl)). Alternativly you could use some encryption library. Migrating a large amount of code/data might be a pain but this is the most future-oriented approach in this case. Upvotes: 4 [selected_answer]<issue_comment>username_2: Note that no code or information about the `mcrypt` options/code. Probably the only problems non-standard null padding used by `mcrypt`. To decrypt with another implementation that does not support null padding (it is non-standard) just decrypt with no padding and then remove the null padding. If you also must encrypt the same as `mcrypt` just add null padding and encrypt with no-padding. Really consider migrating the current encryption or adding some flag that the encryption is (or not) `mcrypt` compatible. Upvotes: 0 <issue_comment>username_3: Despite all the warnings and suggestions if you still need to make it work, try this: 1. Locate your PHP directory. Usually it is located on C:\Program Files\PHP\v7.2 2. Then go to this url: <http://pecl.php.net/package/mcrypt/1.0.3/windows> 3. Download the package that better meets your requirements. For example if you are using FastCGI and have a 64 bit Windows installation pick *7.2 Non Thread Safe (NTS) x64* 4. Open the zip and copy php\_mcrypt.dll file to the C:\Program Files\PHP\v7.2\ext directory. 5. Edit the php.ini file and add this to the Dynamic extensions section: *extension=php\_mcrypt.dll* 6. Save php.ini and restart your web server. Hope it helps. Upvotes: 2
2018/03/16
708
1,469
<issue_start>username_0: I have two arrays: ``` a = [50, 17, 54, 26] b = [19, 7, 8, 18, 36, 8, 18, 36, 18, 14] ``` I want to add to the elements of `b` the corresponding elements of `a`. When the elements of `a` runs out, I want to cycle through `a` to supply the elements. The result should be: ``` c = [69, 24, 62, 44, 86, 25, 72, 62, 68, 31] ``` How could I go about this?<issue_comment>username_1: EDIT: Only works in rails ``` def add_arrays(array_a, array_b) results = [] array_b.in_groups_of(4).each do |group| group.each_with_index do |record, j| results << (record + array_a[j]) end end results end ``` Not tested it but that should do the trick Upvotes: -1 <issue_comment>username_2: ``` b.zip(a * (b.size / a.size + 1)).map { |o| o.reduce(:+) } #⇒ [69, 24, 62, 44, 86, 25, 72, 62, 68, 31] ``` Or, much better and more concise from @SimpleLime: ``` b.zip(a.cycle).map(&:sum) ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Another one, using [`map`](http://ruby-doc.org/core-2.5.0/Array.html#method-i-map), [`with_index`](http://ruby-doc.org/core-2.5.0/Enumerator.html#method-i-with_index) and modulo: ``` b.map.with_index { |e, i| e + a[i % a.size] } #=> [69, 24, 62, 44, 86, 25, 72, 62, 68, 31] ``` Upvotes: 0 <issue_comment>username_4: ``` a = [50, 17, 54, 26] b = [19, 7, 8, 18, 36, 8, 18, 36, 18, 14] enum = a.cycle b.map { |e| e + enum.next } #=> [69, 24, 62, 44, 86, 25, 72, 62, 68, 31] ``` Upvotes: 2
2018/03/16
624
1,423
<issue_start>username_0: I am currently using this code: **< input type="text" id="employeeid" name="employeeid" value="${c.employee\_id}">** What i wanted to do is pass the value of employeeid to my java code on the same jsp page **< % int empid = (value of employeeid) % >** Is there an easy way to do this? Thanks for any help<issue_comment>username_1: EDIT: Only works in rails ``` def add_arrays(array_a, array_b) results = [] array_b.in_groups_of(4).each do |group| group.each_with_index do |record, j| results << (record + array_a[j]) end end results end ``` Not tested it but that should do the trick Upvotes: -1 <issue_comment>username_2: ``` b.zip(a * (b.size / a.size + 1)).map { |o| o.reduce(:+) } #⇒ [69, 24, 62, 44, 86, 25, 72, 62, 68, 31] ``` Or, much better and more concise from @SimpleLime: ``` b.zip(a.cycle).map(&:sum) ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Another one, using [`map`](http://ruby-doc.org/core-2.5.0/Array.html#method-i-map), [`with_index`](http://ruby-doc.org/core-2.5.0/Enumerator.html#method-i-with_index) and modulo: ``` b.map.with_index { |e, i| e + a[i % a.size] } #=> [69, 24, 62, 44, 86, 25, 72, 62, 68, 31] ``` Upvotes: 0 <issue_comment>username_4: ``` a = [50, 17, 54, 26] b = [19, 7, 8, 18, 36, 8, 18, 36, 18, 14] enum = a.cycle b.map { |e| e + enum.next } #=> [69, 24, 62, 44, 86, 25, 72, 62, 68, 31] ``` Upvotes: 2
2018/03/16
883
3,183
<issue_start>username_0: I have a Dictionary whose key values (string type) are as below: * mark * mark a * mark b * orange * apple * apple a I also have a List(Of String) which contains: * mark * apple I want to delete any entry in the Dictionary where any value in the List is a substring of the Dictionary item's key. In the example above, the entries with the following keys will be removed from the Dictionary: * mark * mark a * mark b * apple * apple a How do I filter and delete those entries from the Dictionary without multiple loops? Here is the sample code/pseudocode I have tried: ``` For Each whatKVP In whatDict If IsSubstringFoundInAList(whatKVP.Key, listName) = True Then listKeyDel.Add(whatKVP.Key) End If Next For Each whatKey In listKeyDel whatDict.Remove(whatKey) Next Private Function IsSubstringFoundInAList(ByVal strIp As String, ByVal listStr As List(Of String)) As Boolean Dim whatStr As String For Each whatStr In listStr If strIp.Contains(whatStr) = True Then Return True End If Next Return False End Function ``` In the code above, I need to use many (3) loops to complete the task. Is there any better way/neater code to complete it?<issue_comment>username_1: You can use List.Any() looks much cleaner in my opinion ``` Dim findString = "foo" listOfString.Any(Function(stringInList) Return stringInList.Equals(findString) End Function) ``` if your looking for performance though, id suggest using [Linq](https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/linq/introduction-to-linq) Upvotes: 1 <issue_comment>username_2: You can do this in a single statement. The following assumes that `whatDict` is your dictionary and `listName` is your list of key substrings. ``` whatDict = whatDict.Where(Function(kvp) Not listName.Any(Function(n) kvp.Key.Contains(n))) _ .ToDictionary(Function(kvp) kvp.Key, Function(kvp) kvp.Value) ``` This creates a new Dictionary containing only the KeyValuePairs from the existing Dictionary where the key does not contain any of the substrings in `listName`. Upvotes: 2 [selected_answer]<issue_comment>username_3: This function should do the trick: ``` Public Function FilterDictionary(Of T, K)(Dictionary As IDictionary(Of T, K), FilterList As ICollection(Of T)) As IDictionary(Of T, k) Return (From Item In Dictionary Where Not FilterList.Any(Function(x) Item.Key.ToString.Contains(x.ToString))). ToDictionary(Function(x) x.Key, Function(x) x.Value) End Function ``` Usage: ``` Dim MyDictionary As New Dictionary(Of String, Integer) Dim FilterList As New List(Of String) 'Fill Collections... Dim FilteredDictionary = FilterDictionary(MyDictionary, FilterList) ``` Upvotes: 0 <issue_comment>username_4: You would need something like this. I used 'StartsWith' but you can change to 'Contains' ``` Dim outList As New List(Of String) outList.Add("mark") outList.Add("apple") whatDict = whatDict.Where(Function(x) Not outList.Exists(Function(y) x.Key.StartsWith(y))).ToDictionary(Function(x) x.Key, Function(x) x.Value) ``` Upvotes: 1
2018/03/16
2,033
7,048
<issue_start>username_0: i am trying insert picture caption using Apache POI, but i dont have any ideas for it. I'm using ``` doc.createParagraph().createRun().addPicture(input, Document.PICTURE_TYPE_PNG, "picture.png", Units.pixelToEMU(603), Units.pixelToEMU(226)); ``` to insert picture and now i would like to add caption for it to be able create Table of Figure. I have tried use some styles paragraph.setStyle("Legends"); but it changes only fonts i doesnt work like with "Header1" (I have template). I have looked into styles.xml (in my template where i inserted picture caption using word) and there is ``` - ``` so it looks like i just have to set paragraph w:name w:val as "caption". Am i right? How can i reach it?<issue_comment>username_1: What one should know about how the [inserting a table of figures](https://support.office.com/en-us/article/insert-a-table-of-figures-c5ea59c5-487c-4fb2-bd48-e34dd57f0ec1?ui=en-US&rs=en-US&ad=US) works in `Word`: When we [add captions](https://support.office.com/en-us/article/add-format-or-delete-captions-in-word-82fa82a4-f0f3-438f-a422-34bb5cef9c81?ui=en-US&rs=en-US&ad=US), then each caption paragraph contains a sequence field `{SEQ figure \* ARABIC}`. The name "figure" is the name of the sequence field. Then, if a table of figures shall be created, `Word` collects all paragraphs which contains such a field to build the table of figures from those. Until now (`apache poi` version 3.17) does not provide adding captions to figures nor inserting or creating a table of figures, at least as far as I know. So we must do it ourself using the low level [CTSimpleField](http://grepcode.com/file/repo1.maven.org/maven2/org.apache.poi/ooxml-schemas/1.1/org/openxmlformats/schemas/wordprocessingml/x2006/main/CTSimpleField.java). Example: ``` import java.io.InputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.xwpf.usermodel.*; import org.apache.poi.util.Units; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff; public class CreateWordTableOfFigures { public static void main(String[] args) throws Exception { XWPFDocument document = new XWPFDocument(); XWPFParagraph paragraph; XWPFRun run; InputStream in; CTSimpleField seq; paragraph = document.createParagraph(); run = paragraph.createRun(); run.setText("Document containing figures"); paragraph = document.createParagraph(); run = paragraph.createRun(); run.setText("Lorem ipsum..."); //create paragraph containing figure paragraph = document.createParagraph(); paragraph.setSpacingAfter(0); //Set spacing after to 0. So caption will follow immediately under the figure. run = paragraph.createRun(); in = new FileInputStream("samplePict1.png"); run.addPicture(in, Document.PICTURE_TYPE_PNG, "samplePict1.png", Units.toEMU(150), Units.toEMU(100)); in.close(); paragraph = document.createParagraph(); //caption for figure run = paragraph.createRun(); run.setText("Picture "); seq = paragraph.getCTP().addNewFldSimple(); seq.setInstr("SEQ figure \\* ARABIC"); //This field is important for creating the table of figures then. run = paragraph.createRun(); run.setText(": Description of sample picture 1"); paragraph = document.createParagraph(); run = paragraph.createRun(); run.setText("Lorem ipsum..."); paragraph = document.createParagraph(); paragraph.setSpacingAfter(0); run = paragraph.createRun(); in = new FileInputStream("samplePict2.png"); run.addPicture(in, Document.PICTURE_TYPE_PNG, "samplePict1.png", Units.toEMU(150), Units.toEMU(100)); in.close(); paragraph = document.createParagraph(); run = paragraph.createRun(); run.setText("Picture "); seq = paragraph.getCTP().addNewFldSimple(); seq.setInstr("SEQ figure \\* ARABIC"); run = paragraph.createRun(); run.setText(": Description of sample picture 2"); paragraph = document.createParagraph(); run = paragraph.createRun(); run.setText("Index of figures:"); //Create table of figures field. Word will updating that field while opening the file. paragraph = document.createParagraph(); CTSimpleField toc = paragraph.getCTP().addNewFldSimple(); toc.setInstr("TOC \\c \"figure\" \\* MERGEFORMAT"); toc.setDirty(STOnOff.TRUE); //set dirty to forcing update FileOutputStream out = new FileOutputStream("CreateWordTableOfFigures.docx"); document.write(out); document.close(); } } ``` Note, the inserted field `{TOC \c "figure" \* MERGEFORMAT}`, because it is set dirty, only forces updating that field while opening the file in `Word`. Creating the whole table of figures using `apache poi` without forcing `Word` doing that will be much more effort. Upvotes: 3 [selected_answer]<issue_comment>username_2: Taking it a step further, I needed to have the caption figure sequence follow my header sequencing. So for header1/header2 I neeed captions to be 1.1.1, 1.1.2, etc. Then adding another header2 they would restart at 1.2.1, 1.2.2. Here is the code for that. It also does not require you to create a table of contents as the answer from Richter (who I thank for pointing me in the right direction with this). ``` public void addCaption(String text) { paragraph = doc.createParagraph(); paragraph.setStyle(STYLE_CAPTION); paragraph.setSpacingAfter(0); // Set spacing after to 0. So caption will follow immediately under the figure. run = paragraph.createRun(); run.setText("Figure "); CTR ctr; CTRPr ctrpr; CTText ctText; CTSimpleField seq = getParagraph().getCTP().addNewFldSimple(); String figureText1 = " STYLEREF 2 \\s "; seq.setInstr(figureText1); ctr = seq.addNewR(); ctrpr = ctr.addNewRPr(); ctrpr.addNewNoProof(); ctText = ctr.addNewT(); ctText.setStringValue("1"); ctr = paragraph.getCTP().addNewR(); ctr.addNewNoBreakHyphen(); seq = getParagraph().getCTP().addNewFldSimple(); String figureText = " SEQ Figure \\* ARABIC \\s 2 "; seq.setInstr(figureText); ctr = seq.addNewR(); ctrpr = ctr.addNewRPr(); ctrpr.addNewNoProof(); ctText = ctr.addNewT(); ctText.setStringValue("1"); run = paragraph.createRun(); // needed or numbers are at end, ie Figure : some text1.1 run.setText(": " + text); } ``` Upvotes: 0 <issue_comment>username_3: right... so in the document xml belonging to a document generated by @AxelRichter 's code, i've manually inserted a table of figures. The resulting xml extracts show that ms word generates this slightly differently... axel's result: ``` Picture 2: Description of sample picture 2 PAGEREF \_Toc521591239 \h 1 ``` manual insert result ``` Picture 2: Description of sample picture 2 PAGEREF \_Toc521591266 \h 1 ``` Having skimmed this thing, it seems that the run should be enveloped in a hyperlink object. ... and there are several subtle differences just to make things interesting. Upvotes: 0
2018/03/16
1,155
4,843
<issue_start>username_0: I am a beginner in android studio. For weeks I have been stuck trying to read data from my database to my activity (Available Rides). Right now I am only transfering the data from one activiy to the other and puting it into text view. In a previous activity I alreadt managed to save the data on the database. Idealy I would like to have table view showing 3 columns. The first one beeing "Deprture" the next one "Arrival" and the third one "Time". Then in each line have each child. I would be really thankful if anyone could help me! Thank you in advance! **Available Rides Activity:** ``` public class AvailableRides extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_available_rides); // Get the Intent that started this activity Intent intent = getIntent(); String messageTime = intent.getStringExtra(DisplayMessageActivity.EXTRA_MESSAGE); String messageDep = intent.getStringExtra(DisplayMessageActivity.EXTRA_MESSAGE1); String messageArr = intent.getStringExtra(DisplayMessageActivity.EXTRA_MESSAGE2); // Capture the layout's TextView and set the string as its text TextView textView1 = findViewById(R.id.textView26); textView1.setText(messageTime); TextView textView2 = findViewById(R.id.textView2); textView2.setText(messageDep); TextView textView3 = findViewById(R.id.textView4); textView3.setText(messageArr); } ``` Firebase database [![enter image description here](https://i.stack.imgur.com/vQfhy.png)](https://i.stack.imgur.com/vQfhy.png)<issue_comment>username_1: You can create a root and select it. Then Retrieve all your respective data in your snapshot within that root. Here is a sample code: ``` Firebase yourDataRef = mRootRef.child("data"); yourDataRef .addValueEventListener(new com.firebase.client.ValueEventListener() { @Override public void onDataChange(com.firebase.client.DataSnapshot dataSnapshot) { for (DataSnapshot snapm: dataSnapshot.getChildren()) { String messageTime = snapm.child("0").getValue(String.class); String messageDep = snapm.child("1").getValue(String.class); String messageArr = snapm.child("2").getValue(String.class); } } @Override public void onCancelled(FirebaseError firebaseError) { throw firebaseError.toException(); } }); ``` Upvotes: 0 <issue_comment>username_2: Assuming that the `Trips` node is a direct child of your Firebase root, to display that data, please use the following code: ``` DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference tripsRef = rootRef.child("Trips"); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { List list = new ArrayList<>(); for(DataSnapshot ds : dataSnapshot.getChildren()) { String arrival = ds.child("Arrival").getValue(String.class); String departure = ds.child("Departure").getValue(String.class); String time = ds.child("Time").getValue(String.class); Log.d("TAG", arrival + " / " + departure + " / " + time); list.add(time); } Log.d("TAG", time); } @Override public void onCancelled(DatabaseError databaseError) {} }; tripsRef.addListenerForSingleValueEvent(valueEventListener); ``` Your output will be: ``` aaaaaa / abababa / 10:00 bbbb / bcbc / 10:00 ``` Upvotes: 4 [selected_answer]<issue_comment>username_3: ``` enter code here content1 = (TextView)findViewById(R.id.con); course = (TextView)findViewById(R.id.co); reset_button = (Button)findViewById(R.id.reset); reference = FirebaseDatabase.getInstance().getReference().child("course data").child("1"); reset_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { reference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { try { String couure_details = dataSnapshot.child("title").getValue(String.class); String course_content =dataSnapshot.child("contant").getValue(String.class); content1.setText(course_content); course.setText(couure_details); }catch (Exception e) { Toast.makeText(userActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); ``` Upvotes: 0
2018/03/16
814
3,439
<issue_start>username_0: Is there a way to apply a customSort to only one column with TurboTables and allow the other columns to use the default sorting? The documentation applies the customSort to the entire table. <https://www.primefaces.org/primeng/#/table/sort><issue_comment>username_1: You can create a root and select it. Then Retrieve all your respective data in your snapshot within that root. Here is a sample code: ``` Firebase yourDataRef = mRootRef.child("data"); yourDataRef .addValueEventListener(new com.firebase.client.ValueEventListener() { @Override public void onDataChange(com.firebase.client.DataSnapshot dataSnapshot) { for (DataSnapshot snapm: dataSnapshot.getChildren()) { String messageTime = snapm.child("0").getValue(String.class); String messageDep = snapm.child("1").getValue(String.class); String messageArr = snapm.child("2").getValue(String.class); } } @Override public void onCancelled(FirebaseError firebaseError) { throw firebaseError.toException(); } }); ``` Upvotes: 0 <issue_comment>username_2: Assuming that the `Trips` node is a direct child of your Firebase root, to display that data, please use the following code: ``` DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference tripsRef = rootRef.child("Trips"); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { List list = new ArrayList<>(); for(DataSnapshot ds : dataSnapshot.getChildren()) { String arrival = ds.child("Arrival").getValue(String.class); String departure = ds.child("Departure").getValue(String.class); String time = ds.child("Time").getValue(String.class); Log.d("TAG", arrival + " / " + departure + " / " + time); list.add(time); } Log.d("TAG", time); } @Override public void onCancelled(DatabaseError databaseError) {} }; tripsRef.addListenerForSingleValueEvent(valueEventListener); ``` Your output will be: ``` aaaaaa / abababa / 10:00 bbbb / bcbc / 10:00 ``` Upvotes: 4 [selected_answer]<issue_comment>username_3: ``` enter code here content1 = (TextView)findViewById(R.id.con); course = (TextView)findViewById(R.id.co); reset_button = (Button)findViewById(R.id.reset); reference = FirebaseDatabase.getInstance().getReference().child("course data").child("1"); reset_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { reference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { try { String couure_details = dataSnapshot.child("title").getValue(String.class); String course_content =dataSnapshot.child("contant").getValue(String.class); content1.setText(course_content); course.setText(couure_details); }catch (Exception e) { Toast.makeText(userActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); ``` Upvotes: 0
2018/03/16
641
2,182
<issue_start>username_0: In an interview I face this problem, how can I call static member here: ``` public class PermenatEmployee { public static string/void sayGoodBye() { return "GoodBye"; } } static void Main(string[] args) { var gsgsg = PermenatEmployee.sayGoodBye; } ``` Here I have choice of using `string` or `void` in the method.<issue_comment>username_1: I'm quite confused by the syntax here: `string/void`, if it's to indicate that it could be either, then to make a static function call you need to invoke the function with `()`, i.e.: ``` var gsgsg = PermenatEmployee.sayGoodBye() ``` That being said, you can't assign the return value of a `void` to a `var`. You also can't have a method outside of class scope, so your example will fail to compile. Upvotes: 0 <issue_comment>username_2: you can just call it by it's name, ``` public class PermenatEmployee { public static string/void sayGoodBye() { return "GoodBye"; } } static void Main(string[] args) { var gsgsg = sayGoodBye(); // your answer } ``` Upvotes: -1 <issue_comment>username_3: remove the string/void. Code will look like this: ``` public class PermenatEmployee { public static string sayGoodBye() { return "GoodBye"; } private static void Main(string[] args) { var gsgsg = PermenatEmployee.sayGoodBye(); } } ``` If you really wanted to return a string and a void you could use return type of void on the method then use an out parameter of string like this: ``` public class PermenatEmployee { public static void SayGoodBye(out string action) { action = "GoodBye"; } private static void Main(string[] args) { PermenatEmployee.SayGoodBye(out var action); Console.WriteLine(action); } } ``` Upvotes: 2 [selected_answer]<issue_comment>username_4: In your class PermenatEmployee: ``` public class PermenatEmployee { public static string sayGoodBye() { return "GoodBye"; } } ``` In your program class: ``` static void Main(string[] args) { Console.WriteLine(PermenatEmployee.sayGoodBye()); } ``` Upvotes: 0
2018/03/16
640
2,313
<issue_start>username_0: Bellow my code. div height not increasing when resize the window. can any one help me. -------------------------------------------------------------------------------------- ``` $(document).ready(function(){ resizeContent(); $(window).resize(function() { $(".js-tile").each(function(){ var tileHeight = 0; if ($(this).height() > tileheight) { tileheight = $(this).height(); } }); $(".js-tile").height(tileheight); }); }); ```<issue_comment>username_1: I'm quite confused by the syntax here: `string/void`, if it's to indicate that it could be either, then to make a static function call you need to invoke the function with `()`, i.e.: ``` var gsgsg = PermenatEmployee.sayGoodBye() ``` That being said, you can't assign the return value of a `void` to a `var`. You also can't have a method outside of class scope, so your example will fail to compile. Upvotes: 0 <issue_comment>username_2: you can just call it by it's name, ``` public class PermenatEmployee { public static string/void sayGoodBye() { return "GoodBye"; } } static void Main(string[] args) { var gsgsg = sayGoodBye(); // your answer } ``` Upvotes: -1 <issue_comment>username_3: remove the string/void. Code will look like this: ``` public class PermenatEmployee { public static string sayGoodBye() { return "GoodBye"; } private static void Main(string[] args) { var gsgsg = PermenatEmployee.sayGoodBye(); } } ``` If you really wanted to return a string and a void you could use return type of void on the method then use an out parameter of string like this: ``` public class PermenatEmployee { public static void SayGoodBye(out string action) { action = "GoodBye"; } private static void Main(string[] args) { PermenatEmployee.SayGoodBye(out var action); Console.WriteLine(action); } } ``` Upvotes: 2 [selected_answer]<issue_comment>username_4: In your class PermenatEmployee: ``` public class PermenatEmployee { public static string sayGoodBye() { return "GoodBye"; } } ``` In your program class: ``` static void Main(string[] args) { Console.WriteLine(PermenatEmployee.sayGoodBye()); } ``` Upvotes: 0
2018/03/16
892
3,285
<issue_start>username_0: I am using the Native Geocoder in my Ionic app. Documented here > > [Ionic documentation](https://ionicframework.com/docs/native/native-geocoder/) > > > [Github Repo](https://github.com/sebastianbaar/cordova-plugin-nativegeocoder) > > > This is the method in my provider - ```js //This calls the Native geocoder and returns the geocoordinates. getGeoCode(address: string): Promise { console.log('The address key is - ' + address); return new Promise((resolve, reject) => { this.nativeGeocoder.forwardGeocode(address) .then((nativegeocoordinates: NativeGeocoderForwardResult) => { console.log('The coordinates are - ' + JSON.stringify(nativegeocoordinates)); let addressCoordinates: DeliveryAddressCoordinates = nativegeocoordinates; resolve(addressCoordinates); }) .catch((error: any) => { console.log(JSON.stringify(error)); reject(error); }); }) } ``` The method accepts an address string as input. So I get the address from google places API, and pass the description here. Now, for certain addresses, it just doesn't seem to find the coordinates, and returns a "Cannot find a location" message. For e.g. *"Bhadra Brookefields Apartment B Block, Kundanahalli Lake Road, Kundalahalli, Brookefield, Bengaluru, Karnataka, India"* is a valid address and returns the coordinates, while *"Times Square 42 Street Station, New York, NY, USA"* does not find a match and returns a message saying - "Cannot find a location". For more information the "Cannot find a location" seems to be originating from the [cordova plugin code here on line #182.](https://github.com/sebastianbaar/cordova-plugin-nativegeocoder/blob/master/src/android/NativeGeocoder.java), where it is referencing the Android class. Is this a known issue? Or is there something that I am doing wrong?<issue_comment>username_1: At least one other person believes the plugin seems to be a bit of a hit/miss - a comment on this article below [Ionic 2 – Geolocation and GeocodingIonic 2 – Geolocation and Geocoding](http://tphangout.com/ionic-2-geolocation-and-geocoding/) The comment is from one Mr. Purple Edge, and I cannot link the comment itself because it is a disq, and not allowed by Stack. So, I have resorted to what can be interpreted both as a solution or as a workaround. Instead of using the plugin, I am simply using the api, thus making a Http request to get the information. Method to get the information (in a provider): ```js getGeoCodefromGoogleAPI(address: string): Observable { return this.\_http.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + address) .map(res => res.json()); } ``` Method call -> ```js this._deliveryAddressService.getGeoCodefromGoogleAPI(event.description).subscribe(addressData => { let latitude: string = addressData.results[0].geometry.location.lat; let longitude: string = addressData.results[0].geometry.location.lng; } ``` Of course, there needs to be the due process of registering for the key. Upvotes: 2 [selected_answer]<issue_comment>username_2: It is not a problem of the plugin. You need just to add more one so you can ask permission to activate the `High Accuracy` in the phone. <https://ionicframework.com/docs/native/location-accuracy/> Upvotes: 0
2018/03/16
2,111
6,766
<issue_start>username_0: I am replacing standard input checkboxes with images and am running into two main issues with the code below: 1. No matter which image I click on (checkbox input), the value stays the same, instead of changing. (See the console for the printed value). 2. When an input is active, I am wanting to background color to change, but for some reason, on page load, all inputs have the red background color (there shouldn't be any background color). Then if I click on the input, nothing changes. Does anyone see what I am doing wrong? [Jsfiddle](https://jsfiddle.net/vdg6ka4d/1/) ```js var interest = $('.interest'); interest.click(function() { $('.interestCheck').prop('checked', true); var check = $('.interestCheck').val(); console.log(check); }); if ($('.interestCheck').prop('checked', true)) { $('.interestBox').addClass('active'); } ``` ```css .interest { width: 250px; height: auto; cursor: pointer; } .interestBox { width: 100%; border: 1px solid #CFCFCF; border-radius: 2px; } .interestBox.active { background: red; } .interestBox img { width: 100%; } .interestTitle { font-size: 1.3rem; text-align: center; margin: 5px 0 0 0; } .interestCheck { display: none; } ``` ```html ![Linear Motion](https://s3.us-east-2.amazonaws.com/mbkitsystems/linearIcon.png) ### Linear Motion ![Linear Motion](https://s3.us-east-2.amazonaws.com/mbkitsystems/linearIcon.png) ### Material Handling ![Linear Motion](https://s3.us-east-2.amazonaws.com/mbkitsystems/linearIcon.png) ### Enclosures ```<issue_comment>username_1: You have to do it like this: If you don't use `$(this)` inside your click function, then the code doesn't know what element you clicked, because `$('.interestCheck').val()` will return the first objects value. You can also just `$('.interestCheck',this)` ``` var interest = $('.interest'); interest.click(function() { $(this).find('.interestCheck').prop('checked', !$(this).find('.interestCheck').prop('checked')); var check = $(this).find('.interestCheck').val(); $(this).find(".interestBox").toggleClass("active") console.log(check); }); ``` **Demo** ```js var interest = $('.interest'); interest.click(function() { $(this).find('.interestCheck').prop('checked', !$(this).find('.interestCheck').prop('checked')); var check = $(this).find('.interestCheck').val(); $(this).find(".interestBox").toggleClass("active") console.log(check); }); ``` ```css .interest { width: 250px; height: auto; cursor: pointer; } .interestBox { width: 100%; border: 1px solid #CFCFCF; border-radius: 2px; } .interestBox.active { background: red; } .interestBox img { width: 100%; } .interestTitle { font-size: 1.3rem; text-align: center; margin: 5px 0 0 0; } .interestCheck { display: none; } ``` ```html ![Linear Motion](https://s3.us-east-2.amazonaws.com/mbkitsystems/linearIcon.png) ### Linear Motion ![Linear Motion](https://s3.us-east-2.amazonaws.com/mbkitsystems/linearIcon.png) ### Material Handling ![Linear Motion](https://s3.us-east-2.amazonaws.com/mbkitsystems/linearIcon.png) ### Enclosures ``` Upvotes: 1 <issue_comment>username_2: * You need to add a context to your jQuery selectors. You can do that by adding `this` as the second parameter of your jQuery selectors : `$('yourSelector',this)`. * If you want to check/uncheck the checkboxes at every click, you need to replace `$('.interestCheck', this).prop('checked',true)` By `$('.interestCheck', this).prop('checked', !$('.interestCheck', this).prop('checked'));` * Plus, your last `if` can be replaced by a simple `.toggleClass` and needs to be inside your `click` handler. ```js var interest = $('.interest'); interest.click(function() { $('.interestCheck', this).prop('checked', !$('.interestCheck', this).prop('checked')); var check = $('.interestCheck', this).val(); console.log(check); $('.interestBox', this).toggleClass('active'); }); ``` ```css .interest { width: 250px; height: auto; cursor: pointer; } .interestBox { width: 100%; border: 1px solid #CFCFCF; border-radius: 2px; } .interestBox.active { background: red; } .interestBox img { width: 100%; } .interestTitle { font-size: 1.3rem; text-align: center; margin: 5px 0 0 0; } .interestCheck { display: none; } ``` ```html ![Linear Motion](https://s3.us-east-2.amazonaws.com/mbkitsystems/linearIcon.png) ### Linear Motion ![Linear Motion](https://s3.us-east-2.amazonaws.com/mbkitsystems/linearIcon.png) ### Material Handling ![Linear Motion](https://s3.us-east-2.amazonaws.com/mbkitsystems/linearIcon.png) ### Enclosures ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: I made you a very simple code of how you can click and get class active ( also checked true ) and then remove it when clicking on other images . So only one at the same time is active. You need to make use of `this` keyword which means the element on which the event happens. You can then find the checkbox inside that element, change it's checked status and also find the `interestBox` you want to activate. Also you find the other elements that may have been activated and deactivate them. Your whole logic must be inside the click function. If you use the `if` outside the function, that condition will be executed on `window.load` or `dom.ready` etc, but it will executed BEFORE you click on the item. So the `if` is useless. It checks, sees that the checkbox is not checked and doesn't update and re-check the condition after the click event occurs. ```js let interest = $('.interest'); interest.click(function() { let targetCheck = $(this).find('.interestCheck'), notCheck = $('.interestCheck').not(targetCheck) notCheck.prop('checked', false); notCheck.siblings(".interestBox").removeClass('active'); targetCheck.prop('checked', true); targetCheck.siblings(".interestBox").addClass('active'); }); ``` ```css .interest { width: 250px; height: auto; cursor: pointer; } .interestBox { width: 100%; border: 1px solid #CFCFCF; border-radius: 2px; } .interestBox.active { background: red; } .interestBox img { width: 100%; } .interestTitle { font-size: 1.3rem; text-align: center; margin: 5px 0 0 0; } .interestCheck { display: none; } ``` ```html ![Linear Motion](https://s3.us-east-2.amazonaws.com/mbkitsystems/linearIcon.png) ### Linear Motion ![Material Handling](https://s3.us-east-2.amazonaws.com/mbkitsystems/linearIcon.png) ### Material Handling ![Enclosures](https://s3.us-east-2.amazonaws.com/mbkitsystems/linearIcon.png) ### Enclosures ``` Upvotes: 0
2018/03/16
1,327
3,990
<issue_start>username_0: I have a matrix A and I want to find per column the last two non-NaN values. For example, generate the following matrix: ``` A = [NaN, 3, NaN; 5 5 5; NaN 1 9; 4 1 4; NaN 6 NaN; 6 2 9] ``` I want to get the following result: ``` B = 4 6 4 6 2 9 ``` **How can I do this in the most efficient way, without a for-loop?** --- I tried the following: `[row,col,v] = find(A,3,'last')`, but this returns something that I do not understand: ``` row = 5 6 col = 3 3 v = NaN 9 ```<issue_comment>username_1: This is how: ``` A = [NaN, 3, NaN; 5 5 5; NaN 1 9; 4 1 4; NaN 6 NaN; 6 2 9] N=2; %last 2 IsOK=~isnan(A); [~,I]=sort(IsOK); Iok=I(end-N+1:end,:); %get last N LinearIndxs=sub2ind(size(A), Iok, repmat(1:size(A,2),N,1)); Result=A(LinearIndxs) ``` Upvotes: 2 <issue_comment>username_2: The third parameter of `find` actually finds the actual locations that are non-zero. It searches on a column-wise basis and returns the row and column locations of the last three non-zero values and their actual values. `NaN` is technically non-zero, which is why it is returned to you. First start off with finding all locations that are not `NaN` in your matrix with `find`: ``` [I,J] = find(~isnan(A)); ``` This will now return row and column locations of the values that were not `NaN`. We now get: ``` >> [I,J] ans = 2 1 4 1 6 1 1 2 2 2 3 2 4 2 5 2 6 2 2 3 3 3 4 3 6 3 ``` We can see a nice pattern forming. The left column shows you all row locations that were not `NaN` and the right column tells you which column that was. Next what we can do is for the second column, find the point where we transition from one column to another. That will give us the locations of last element that was not `NaN` for each column. We can then subtract these indices by 1 to give us the locations of the second last element that was not `NaN`. We can use the [`diff`](https://www.mathworks.com/help/matlab/ref/diff.html) function to help us do that and checking to see when the distance is non-zero. Note that this will decrease the size of the output by 1 because we're computing pairwise distances, but simply pad a 1 at the end because this signifies the end of the last column and this is where we want to find the last two elements of the column: ``` >> d = [diff(J) ~= 0; 1]; >> [J d] ans = 1 0 1 0 1 1 2 0 2 0 2 0 2 0 2 0 2 1 3 0 3 0 3 0 3 1 ``` Now let's take the output of `diff` and also shift everything up by 1: ``` d(1:end-1) = d(1:end-1) | d(2:end); ``` This will allow us to mark the second last element of each column to capture: ``` >> [I J d] ans = 2 1 0 4 1 1 6 1 1 1 2 0 2 2 0 3 2 0 4 2 0 5 2 1 6 2 1 2 3 0 3 3 0 4 3 1 6 3 1 ``` Last but not least, we now sample the first two columns of the above matrix where the third column is non-zero, convert these into linear indices and sample our matrix. We'll use a combination of [`reshape`](https://www.mathworks.com/help/matlab/ref/reshape.html) and [`sub2ind`](https://www.mathworks.com/help/matlab/ref/sub2ind.html) for that: ``` loc = d ~= 0; out = reshape(A(sub2ind(size(A), I(loc), J(loc))), 2, size(A,2)); ``` Thus: ``` >> out out = 4 6 4 6 2 9 ``` The final code is thus: ``` [I,J] = find(~isnan(A)); d = [diff(J) ~= 0; 1]; d(1:end-1) = d(1:end-1) | d(2:end); loc = d ~= 0; out = reshape(A(sub2ind(size(A), I(loc), J(loc))), 2, size(A,2)); ``` Warning ======= This assumes that you have at least two elements per column that are not `NaN`. Upvotes: 2
2018/03/16
766
3,059
<issue_start>username_0: I have a webpage that has an animated flash gallery on its homepage. By default, google chrome/firefox/safari ... does not let this page enable the flash plugin, so the gallery doesn't show. Not only this happens, but also there is no prompt from the webpage requesting the user to enable flash, and the gallery completely disappear when flash is not enabled, so there's not even an error message saying that you need to enable flash to see the gallery. What do I need to do on the page so that it requests the user to enable flash? Something like button to enable and then request permission from a browser. Here is the sample which asks this permission in a browser. <https://quickfire.gcontent.eu/aurora/default.aspx> Cheers!<issue_comment>username_1: you should take the hint...Flash is dead...not supported...on its last legs.. covert your gaming/gambling website to html5>Canvas>SVG>scripting. IE also has ActiveX filtering that blocks ActiveX controls from running on websites. see Tools ActiveX filtering. The common design pattern for embedded plugins/ActiveX controls is to provide a fallback (link, image) nested INSIDE the parent object. ``` Opps.... your browser does not support flash, or it is disabled or it is blocked by ActiveX filtering. ``` For activeX filtering feature detection.. place a hidden div at the top of your document.... directly after the body. eg. ``` ActiveX filtering for this site is turned on... ``` and at the bottom of the document (so it executes when the onload event fires) the following script block. ``` // Best Practice: First detect if ActiveX Filtering is enabled if(document.documentMode&&document.documentMode>8){ if (typeof window.external.msActiveXFilteringEnabled == "unknown" && window.external.msActiveXFilteringEnabled() == true) { document.getElementById('AXon').style.display = 'block'; //document.write("ActiveX Filtering has hidden this content."); } else { // Either the browser isn’t IE, or ActiveX Filtering is not enabled in IE //document.write('<a style=\"text-decoration: none;\" href=\"http://go.microsoft.com/fwlink/?LinkID=124807\"><img alt=\"Get Microsoft Silverlight\" src=\"http://go.microsoft.com/fwlink/?LinkId=108181\"/><\/a>'); } } ``` But the only best answer is to put Flash out of its misery. Upvotes: 0 <issue_comment>username_2: I found a solution, I make a flash button and embed to my page overlayer with HTML button, then the user clicks on button, it event fire the flash button event and then the browser will ask for permission to run the flash on a browser. This is work if a flash has been already installed on the browser. If not it will show the only text and can not find any solution to make this process in a browser. Upvotes: 0 <issue_comment>username_3: This will request to enable the flash player if its already installed otherwise, it will direct you to adobe page to download the flash player. ``` [Click here to activate it](https://get.adobe.com/flashplayer/) ``` Upvotes: 3 [selected_answer]
2018/03/16
690
2,753
<issue_start>username_0: I'm creating a online mess application where there are two logins one for mess owner and another for user so when mess owner put location in his data there should be marker on map in user side. here is structure of database in image[Database structure](https://i.stack.imgur.com/rNDCO.png) please suggest me code to access those latitude n longitude values and create marker on map for each mess registered with location values.<issue_comment>username_1: you should take the hint...Flash is dead...not supported...on its last legs.. covert your gaming/gambling website to html5>Canvas>SVG>scripting. IE also has ActiveX filtering that blocks ActiveX controls from running on websites. see Tools ActiveX filtering. The common design pattern for embedded plugins/ActiveX controls is to provide a fallback (link, image) nested INSIDE the parent object. ``` Opps.... your browser does not support flash, or it is disabled or it is blocked by ActiveX filtering. ``` For activeX filtering feature detection.. place a hidden div at the top of your document.... directly after the body. eg. ``` ActiveX filtering for this site is turned on... ``` and at the bottom of the document (so it executes when the onload event fires) the following script block. ``` // Best Practice: First detect if ActiveX Filtering is enabled if(document.documentMode&&document.documentMode>8){ if (typeof window.external.msActiveXFilteringEnabled == "unknown" && window.external.msActiveXFilteringEnabled() == true) { document.getElementById('AXon').style.display = 'block'; //document.write("ActiveX Filtering has hidden this content."); } else { // Either the browser isn’t IE, or ActiveX Filtering is not enabled in IE //document.write('<a style=\"text-decoration: none;\" href=\"http://go.microsoft.com/fwlink/?LinkID=124807\"><img alt=\"Get Microsoft Silverlight\" src=\"http://go.microsoft.com/fwlink/?LinkId=108181\"/><\/a>'); } } ``` But the only best answer is to put Flash out of its misery. Upvotes: 0 <issue_comment>username_2: I found a solution, I make a flash button and embed to my page overlayer with HTML button, then the user clicks on button, it event fire the flash button event and then the browser will ask for permission to run the flash on a browser. This is work if a flash has been already installed on the browser. If not it will show the only text and can not find any solution to make this process in a browser. Upvotes: 0 <issue_comment>username_3: This will request to enable the flash player if its already installed otherwise, it will direct you to adobe page to download the flash player. ``` [Click here to activate it](https://get.adobe.com/flashplayer/) ``` Upvotes: 3 [selected_answer]
2018/03/16
2,836
8,061
<issue_start>username_0: I am using altbeacon: <https://altbeacon.github.io/android-beacon-library/> I bind my beaconManager. and then I call this: ``` public void startListeningForBeacons(RangeNotifier rangeNotifier) { try { Region region = new Region("all-beacons-region", null, null, null); // Tells the BeaconService to start looking for beacons that match the passed Region object beaconManager.startRangingBeaconsInRegion(region); } catch (RemoteException e) { e.printStackTrace(); } // Specifies a class that should be called each time the BeaconService gets ranging data, once per second by default beaconManager.addRangeNotifier(rangeNotifier); } ``` Which starts calling this function inside my application class: ``` @Override public void didRangeBeaconsInRegion(final Collection beacons, Region region) { if (beacons.size() > 0) { Log.i("BluetoothService", "BluetoothService region The first beacon I see is about " + beacons.iterator().next().getDistance() + " meters away."); if (didRangeBeaconsCallback != null) didRangeBeaconsCallback.rangeCalled(beacons, region); }else { Log.i("BluetoothService", "BluetoothService region NO BEACONS: " + beacons.size()); if(PSBluetoothService.getInstance(PSApplicationClass.this).beaconUUID != null){ if (didRangeBeaconsCallback != null) didRangeBeaconsCallback.rangeCalled(null, null); } } } ``` But a lot of times, I get back o collection of size 0. Even thought I have 2 beacons in range. I also tried with a LG Nexus 5 and a LeEco LePro2 and both return the correct list of beacons. What might go wrong when it comes to the Huawei? If it helps, this is the list of beacon layouts I configure: ``` //sets the types of beacons that the library is searching for public void setNeededTypesOfBeacons() { beaconManager.getBeaconParsers().add(new BeaconParser(). setBeaconLayout(BeaconParser.EDDYSTONE_UID_LAYOUT)); beaconManager.getBeaconParsers().add(new BeaconParser(). setBeaconLayout(BeaconParser.EDDYSTONE_TLM_LAYOUT)); beaconManager.getBeaconParsers().add(new BeaconParser(). setBeaconLayout(BeaconParser.EDDYSTONE_URL_LAYOUT)); beaconManager.getBeaconParsers().add(new BeaconParser(). setBeaconLayout(BeaconParser.ALTBEACON_LAYOUT)); beaconManager.getBeaconParsers().add(new BeaconParser(). setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24")); beaconManager.getBeaconParsers().add(new BeaconParser() .setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25")); } ``` And I use this beacons: <https://nl.aliexpress.com/item/3-pcs-BLE-4-0-Base-Station-Ebeoo-iBeacon-USB/32752285433.html?spm=a2g0s.9042311.0.0.g1aZkv> This is a picture showing what it finds, compared to the others: <https://s3.amazonaws.com/uploads.hipchat.com/39260/829560/5FNgB6ARACpywWv/upload.png> EDIT: ===== Made a sample app, just with this logic, if it helps: <https://www.dropbox.com/s/4ddt9mhn7zdi9gd/Beacon.zip?dl=0> Even when leaving it scan for a long time, still no results, when it doesn't find them: ``` 03-20 12:30:24.542: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:25.644: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:26.749: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:27.855: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:28.960: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:30.071: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:31.174: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:32.277: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:33.379: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:34.486: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:35.588: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:36.696: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:37.803: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:38.906: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:40.012: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:41.210: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:42.313: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:43.418: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:44.522: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:45.628: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:46.734: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:47.839: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:48.943: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:50.061: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:50.061: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:51.165: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:52.268: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:53.372: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 03-20 12:30:54.476: I/BluetoothService(10806): BluetoothService region NO BEACONS: 0 ```<issue_comment>username_1: Any device with Android 4.3+ and a Bluetooth Low Energy chipset can detect beacons with this library. As of August 2017, this is approximately 92 percent of Android devices according to the Google Play Store. To transmit as a beacon, Android 5.0+ and firmware supporting Bluetooth Low Energy Peripheral Mode are required. > > To find out if your smart phone or tablet can work with Bluetooth LE: > Go to the Google Play store and install the free app “[BLE Checker](https://play.google.com/store/apps/details?id=com.magicalboy.btd)” on > your Android device. The app is simple – it tells you whether your > device supports Bluetooth LE or not and that is all it does. > > > I cant test your code on Mate10 because I didn't have one now but I think your problem for about the android 8 read this link about the changes on android 8 <http://www.username_2tech.com/2017/08/07/beacon-detection-with-android-8> Apps that use the library will need to upgrade to version 2.12+ in order to detect in the background on Android 8 devices. Version 2.13+ adds further enhancements for Android 8.1 restrictions of scanning with the screen off. ``` dependencies { compile 'org.altbeacon:android-beacon-library:2+' } ``` Upvotes: 0 <issue_comment>username_2: Based on comments below the question, the detection is *intermittent* on Huawei and the code only has a 5-10% chance of detecting a beacon in 5 seconds of scanning, at which point the code gives up. There are some bluetooth chips that are slow to detect the first beacon after starting scanning. This may be a hardware limitation that you must learn to live with. I would suggest you rework the code to: 1. Look for beacons for much longer than 5 seconds and show results as soon as you find one. This way it will be fast on fast devices and slow on slow devices. 2. Don't unbind from the beacon manager until the app goes to the background. This way, it is already scanning in case you hit retry, and there won't be a delay in starting up scanning. 3. If you have control over the configuration of the hardware beacon, make sure it is transmitting at the highest rate possible. Some beacons are set to transmit only once every 1-5 seconds, which decreases the chance of detecting a packet within a short time interval. The more often you make the beacon transmit, the greater the odds of it getting detected within 5 seconds. Upvotes: 2 [selected_answer]
2018/03/16
785
2,562
<issue_start>username_0: I have a problem with regex lookbehind! here is my sample text: ``` href="dermatitis>" "blah blah blah >" href="lichen-planus>" ``` I want to match all `>"` if and only if there is an `href=` somewhere before it and yet there is another rule! The `href=` must be immediately before the previous Quotation mark. (for example the second `&ght` in text has an `href=` before it but the `href=` is not immediately before the previous Quotation mark and I dont want it to be matched) In my text, there is 3 `&ght` and I want first and 3rd one to be matched and the second one not matched based on ruled I described above. I hope the question is explained enough! and I work on some offline text files and I can use notepad++, powershell or any other suitable engine. Any help will be appreciated.<issue_comment>username_1: One way you could do it in PowerShell, if your inputs always have spaces between each item: ``` $a = '"href="dermatitis>" "blah blah blah >" href="lichen-planus>"' $b = $a.Split(" ") $c = $b | ? { $_ -match 'href="' } Write-Output $c ``` Upvotes: -1 <issue_comment>username_1: Another way of attacking it through PowerShell that also removes the undesired `>` ``` # Set the regular expression $regex = '(?<=href\=")(.*?)(?=")' $sampleText = 'href="dermatitis>&ght" "blah blah blah >" href="lichen-planus>&ght"' # Separate the single line string into 3 entities with " " as the delimiter $sampleTextSplit = $sampleText.Split(" ") $sampleMatches = $sampleTextSplit | Where-Object {$_ -match $regex} | Foreach-Object { $_.Replace(">","") } # Show the results $sampleMatches ``` This returns two objects: ``` href="dermatitis>" href="lichen-planus>" ``` Upvotes: -1 <issue_comment>username_2: Notepad++ doesn't understand lookbehind, you have to use `\K` instead. * `Ctrl`+`F` * Find what: `href="[^"]*\K>(?=")` * *check Wrap around* * *check Regular expression* * `Search in document` **Explanation:** ``` href="[^"]* : search for href=" followed by 0 or more any charcater but " \K : forget all we have seen until this position > : literally > (?=") : lookahead, make sure we have '"' after ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: I know I'm 2 years late, but anyway :) Here's solution: ``` $string = 'href="dermatitis>" "blah blah blah >" href="lichen-planus>"' $value = '>"' $regex = 'href=".+?(' + $value + ')' ([regex]::matches($string,$regex).groups.value) | ? {$_ -eq $value} ``` Which will return 1st and 3rd values: ``` >" >" ``` Upvotes: 0
2018/03/16
1,111
3,866
<issue_start>username_0: <https://finance.google.com/finance/converter> now redirects to <https://www.google.com/search> Have they changed the url ?<issue_comment>username_1: I found a workaround this url is working: <https://finance.google.co.uk/bctzjpnsun/converter> you can view old pages by inserting this 'bctzjpnsun' in the url. For instance portfolio view with issues in the layout: <https://finance.google.co.uk/bctzjpnsun/portfolio?action=view&pid=1&pview=sview> They are unfortunately in the process of removing it to push a new sleek layout www.google.com/finance without portfolio management features. Obviously many are complaining but that did not help when they said the would terminate Google Reader loved by millions which means you should plan for an alternative. EDIT: They should have communicated more on this. Most feature are easily replicable in google spreadsheets using `=GOOGLEFINANCE` function. Upvotes: 4 <issue_comment>username_2: To add to above answer, can confirm it works if you change url to .co.uk ``` https://finance.google.co.uk/finance/converter?a=1&from=USD&to=EUR ``` Upvotes: 1 <issue_comment>username_3: It's not working in Argentina, just redirects to Google Finance... (finance.google.com) I guess you could use google search instead... just google something like "1 USD to ARS" (1 us dollar to argentine peso) and grab the result from there... The search query would be something like <https://www.google.com.ar/search?q=1+usd+to+ars> and you would be grabbing the result from the corresponding DIV tag... EDIT: In this particular case, the source code shows ```html 1 U.S. dollar =20.2675314 Argentine pesos ``` so you would grab the div with the **vk\_ans** class. Upvotes: 1 <issue_comment>username_4: In my case, I've found very useful Fixer.io and Open Exchange Rates API's. I've tested and compared both to Yahoo, XE and Google rates and the difference is about 3 to 5 cents! Both API's offer free 1000 requests per month with 1 hour refresh. Payed plans offer more requests and more updates per hour. Open Exchange Rates also offers HTTPS requests with free plan. Both API's responds in JSON format so it's very easy to parse the response data. More info here: --------------- **Open Exchange Rates** <https://openexchangerates.org/> **Fixer.io** <https://fixer.io/> How to convert currencies using free plan? ========================================== In free plans, both API's give you access to currency rates list only. Can't use currency exchange endpoints, so to be able to convert currencies, you need to apply this formula, `toCurrency * (1 / fromCurrency)` Using Open Exchange Rates and PHP: ---------------------------------- ``` $url = 'https://openexchangerates.org/api/latest.json?app_id=YOUR_APP_ID'; $useragent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:37.0) Gecko/20100101 Firefox/37.0'; $rawdata = ''; if (function_exists('curl_exec')) { $conn = curl_init($url); curl_setopt($conn, CURLOPT_USERAGENT, $useragent); curl_setopt($conn, CURLOPT_FRESH_CONNECT, true); curl_setopt($conn, CURLOPT_RETURNTRANSFER, true); $rawdata = curl_exec($conn); curl_close($conn); } else { $options = array('http' => array('user_agent' => $useragent)); $context = stream_context_create($options); if (function_exists('file_get_contents')) { $rawdata = file_get_contents($url, false, $context); } else if (function_exists('fopen') && function_exists('stream_get_contents')) { $handle = fopen($url, "r", false, $context); if ($handle) { $rawdata = stream_get_contents($handle); fclose($handle); } } } if ($rawdata) { $rawdata = json_decode($rawdata); $convertedCurrency = false; $convertedCurrency = $rawdata->rates->$currB * (1 / $rawdata->rates->$currA); } ``` Upvotes: 1
2018/03/16
1,042
3,484
<issue_start>username_0: I'm using Javascript to summarise data from a sharepoint list. I've got the query working and returning OK, and i can see from the console that it is returning everything I need, however I cannot work out how to parse it. `jQuery.fromJSON` returns an error, as does the significant number of other things i've tried. Other than doing some regex or something i'm at a loss. Can anyone suggest how this type of sharepoint response can be parsed so i can use the objects/data in each row. Thanks ``` function GetProductInformation(){ var query = ' 2017-07-012018-06-29 '; console.log("Query is " + query); var clientContext = new SP.ClientContext.get_current(); var oList = clientContext.get_web().get_lists().getByTitle('Work tracker - Products'); console.log("GetProductInformation Async Request") jsonResult = oList.renderListData(query); clientContext.executeQueryAsync(Function.createDelegate(this, this.onGetProductQuerySucceeded), Function.createDelegate(this, this.onGetProductQueryFailed)); //clientContext.executeQueryAsync(onGetProductQuerySucceeded, onGetProductQueryFailed); console.log("GetProductInformation Async Requested") } function onGetProductQuerySucceeded(sender, args) { console.log('Query Success'); var dataFromYou = jsonResult console.log(dataFromYou); var data = dataFromYou.Row[0]; //This bit doesn't work console.log(data) ``` Find below some example output: ``` "{ "Row" : [{ "Analyser": [{"lookupId":1,"lookupValue":"Accounts Payable Analyser","isSecretFieldValue":false}], "Analyser.urlencoded": "%3B%23Accounts%20Payable%20Analyser%3B%23", "Analyser.COUNT.group": "363", "Analyser.newgroup": "1", "Analyser.groupindex": "1_", "Number_x0020_of_x0020_products.SUM": "14,694", "Number_x0020_of_x0020_products.SUM.agg": "658" } ,{ "Analyser": [{"lookupId":2,"lookupValue":"Accounts Receivable Analyser","isSecretFieldValue":false}], "Analyser.urlencoded": "%3B%23Accounts%20Receivable%20Analyser%3B%23", ```<issue_comment>username_1: In the example: ``` var result = list.renderListData(qry.get_viewXml()); ``` [`SP.List.renderListData` method](https://msdn.microsoft.com/en-us/library/office/jj247244.aspx) returns [`SP.Result`](https://msdn.microsoft.com/en-us/library/office/ff411273(v=office.14).aspx) object and the list data could be retrieved like this: ``` var listData = result.get_value(); ``` Since the list data is returned as a JSON string it could be easily parsed like this: ``` var jsonVal = JSON.parse(result.get_value()); if(jsonVal.Row.length > 0) console.log(jsonVal.Row[0]); //get first row data ``` **Example** ``` var ctx = SP.ClientContext.get_current(); var list = ctx.get_web().get_lists().getByTitle(listTitle); var qry = SP.CamlQuery.createAllItemsQuery(); var result = list.renderListData(qry.get_viewXml()); ctx.executeQueryAsync( function(){ var jsonVal = JSON.parse(result.get_value()); if(jsonVal.Row.length > 0) console.log(jsonVal.Row[0]); }, function(sender,args){ console.log(args.get_message()); }); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: I found solution for same problem by using: ``` var results = JSON.parse(data.d.RenderListData).Row; ``` This gives me an array of returned listdata objects. Upvotes: -1
2018/03/16
630
1,975
<issue_start>username_0: I'm running the code below in hive trying to join two tables on a field "word". It's taking forever and I'm wondering what I could do to speed it up. In one table the "word" field has a mix of upper and lower case letters, in the other table it is all upper case. ``` Code: set hive.exec.compress.output=false; set hive.mapred.mode=nonstrict; DROP TABLE IF EXISTS newTable; CREATE TABLE newTable AS SELECT bh.inkey, bh.prid, bh.hname, bh.ptype, bh.band, bh.sles, bh.num_ducts, urg.R_NM from table1 AS bh INNER JOIN table2 AS urg ON LOWER(bh.word)=LOWER(urg.word); ```<issue_comment>username_1: In the example: ``` var result = list.renderListData(qry.get_viewXml()); ``` [`SP.List.renderListData` method](https://msdn.microsoft.com/en-us/library/office/jj247244.aspx) returns [`SP.Result`](https://msdn.microsoft.com/en-us/library/office/ff411273(v=office.14).aspx) object and the list data could be retrieved like this: ``` var listData = result.get_value(); ``` Since the list data is returned as a JSON string it could be easily parsed like this: ``` var jsonVal = JSON.parse(result.get_value()); if(jsonVal.Row.length > 0) console.log(jsonVal.Row[0]); //get first row data ``` **Example** ``` var ctx = SP.ClientContext.get_current(); var list = ctx.get_web().get_lists().getByTitle(listTitle); var qry = SP.CamlQuery.createAllItemsQuery(); var result = list.renderListData(qry.get_viewXml()); ctx.executeQueryAsync( function(){ var jsonVal = JSON.parse(result.get_value()); if(jsonVal.Row.length > 0) console.log(jsonVal.Row[0]); }, function(sender,args){ console.log(args.get_message()); }); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: I found solution for same problem by using: ``` var results = JSON.parse(data.d.RenderListData).Row; ``` This gives me an array of returned listdata objects. Upvotes: -1
2018/03/16
390
1,262
<issue_start>username_0: In a design there is a bus with 4 bits, thus `alfa[3:0]`, and I want to make a covergroup that shows if all bit have been both 0 and 1. One way to do this coule be to write it out like: ``` covergroup alfa_cv @(posedge clk); coverpoint alfa[0]; coverpoint alfa[1]; coverpoint alfa[2]; coverpoint alfa[3]; endgroup alfa_cv alfa_covergroup = new; ``` But is there an easier way to make coverpoints to cover each of the bits in a bus?<issue_comment>username_1: Usually code coverage includes toggle coverage. You shouldn't have to create a covergroup for this. But you can create an array of covergroups ``` covergroup cg(input int index, ref bit [31:0] bus) @(posedge clk); each_bit: coverpoint bus[index]; option.per_instance = 1; endgroup cg cgbits[32]; for (int index=0; index<$size(alfa);index++) cgbits[index] = new(index,alfa); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: As everyone mentioned over here, you don't need to write a covergroup for this purpose, as the toggle coverage will take care of it. However, if you want to write a covergroup then you can directly use `alfa` as coverpoint, as follow. ``` covergroup alfa_cv @(posedge clk); coverpoint alfa; endgroup ``` Upvotes: 0
2018/03/16
568
2,148
<issue_start>username_0: i need to save an image on my server i have tried the following: ``` func saveImageOnServer(_ image: UIImage) { let fileid:String = files id here let parameters : NSMutableDictionary? = [ "fileId": fileid] let filename:String = filename here let url = url here let afHTTP : AFHTTPRequestSerializer = AFHTTPRequestSerializer() let request: NSMutableURLRequest = afHTTP.multipartFormRequest(withMethod: "POST", urlString: url, parameters: parameters as? [String : Any], constructingBodyWith: {(formData: AFMultipartFormData) in let imageData = UIImageJPEGRepresentation(image as UIImage, 0.5)! formData.appendPart(withFileData: imageData, name: "uploaded_file", fileName: filename, mimeType: "image/*") }, error: nil) let manager = AFURLSessionManager() let uploadTask:URLSessionUploadTask = manager.uploadTask(withStreamedRequest: request as URLRequest, progress: nil, completionHandler: { (response, responseObject, error) in print(responseObject as Any) }) uploadTask.resume() } ``` but for some reason the responseObject is always returning nil no matter what i change in my PHP code even if i have something as simple as the following: ``` public function uploadColoringImage () { return "1"; } ``` any help will be much appreciated!<issue_comment>username_1: Usually code coverage includes toggle coverage. You shouldn't have to create a covergroup for this. But you can create an array of covergroups ``` covergroup cg(input int index, ref bit [31:0] bus) @(posedge clk); each_bit: coverpoint bus[index]; option.per_instance = 1; endgroup cg cgbits[32]; for (int index=0; index<$size(alfa);index++) cgbits[index] = new(index,alfa); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: As everyone mentioned over here, you don't need to write a covergroup for this purpose, as the toggle coverage will take care of it. However, if you want to write a covergroup then you can directly use `alfa` as coverpoint, as follow. ``` covergroup alfa_cv @(posedge clk); coverpoint alfa; endgroup ``` Upvotes: 0
2018/03/16
795
2,823
<issue_start>username_0: I can set 2 different databases in **config\database.php** with `'conection' => ['database01' => [ ...` `'conection' => ['database02' => [ ...` And in the **model** with `protected $connection = '1database';` `protected $connection = '2database';` However, I want to use one **controller** and insert a conditional something like below ``` php namespace App\Http\Controllers; use Illuminate\Http\Request; if (\Session::get('db')=='database01'){ use App\Model01; }else{ use App\Model02; } </code ``` Unfortunately, this solution does not work. ``` public function index() { if ($baseDat1){ $data= Data01::orderBy('id', 'desc')->take(25)->get(); }else{ $data= Data02::orderBy('id', 'desc')->take(25)->get(); } } ``` Is it possible to do something like I want?<issue_comment>username_1: You can set the default DB connection inside \App\Providers\AppServiceProvider::boot() method. ``` /** * Bootstrap any application services. * * @return void */ public function boot() { if (true) { $this->app['db']->setDefaultConnection('database_01'); } else { $this->app['db']->setDefaultConnection('database_02'); } } ``` Upvotes: 0 <issue_comment>username_2: You can change the config database file with a helper function 1 - create helper function `changeDatabases($database)` 2 - change you config database ``` if(database == 'baseDat1'){ config(['database.connections.mysql.host' => 'newHost']); config(['database.connections.mysql.database' => 'newDatabase']); config(['database.connections.mysql.username' => 'newUsername']); config(['database.connections.mysql.password' => '<PASSWORD>']); } ``` 3 - you must create two different model if they are not equal the change is good the duration of the session Upvotes: 0 <issue_comment>username_3: Import both of them. And then just initiate the correct one within the `if` statement. Something like this: ``` namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Model01; use App\Model02; // ... // Your controller if (\Session::get('db')=='database01'){ $model = app()->make(Model01::class); } else { $model = app()->make(Model02::class); } // And now you can make queries with your $model like this $results = $model->where(condition)->get(); ``` Upvotes: 1 <issue_comment>username_1: You can implement trait for this purpose. And use it in your models. ``` php namespace App; trait UsesTenantConnection { /** * Get the current connection name for the model. * * @return string */ public function getConnectionName() { if (true) { //your condition here return 'database_01'; } else { return 'database_02'; } } } </code ``` Upvotes: 1
2018/03/16
607
2,405
<issue_start>username_0: I have an issue with posting data to Symfony to an endpoint that expects data formatted as a Symfony form. The endpoint validates the posted data with a Symfony form. Normally, when I have a rendered form with twig. A relationship field will have a structure like this: ``` ... A product Some other product Product Nice product Stupid product Interesting product ``` Now I don't have this, I just have an endpoint. Whenever I want to post a record with say, "Nice product" I could just post a body containing form[product]=4 and the relationship is handled properly. But I only know I should post 4 because I check the rendered form. The same goes when I need to update a record's relationship to product because I don't know what to send because the values are not related to anything, the option value is just an incremental value regardless of record id or anything. How is this normally done? How could I manually create a post body containing the relationship of my choice?<issue_comment>username_1: If you have control over the Symfony form class, you can make the `value` attributes predictable with the [choices](https://symfony.com/doc/current/reference/forms/types/choice.html#example-usage) option: ``` $builder->add('product', ChoiceType::class, array( 'choices' => array( 'Nice product' => 'nice-product', 'NOT nice product' => 'not-nice-product' ), )); ``` Being aware of this mapping beforehand, you'd then submit a POST with `form[product]='nice-product'`. Note: the `choices` option also works for the [EntityType form type](https://symfony.com/doc/current/reference/forms/types/entity.html#choices). Upvotes: 2 [selected_answer]<issue_comment>username_2: If you are using a REST endpoint I assume that you are building a web app with JavaScript, a phone app or similar. In this cases the normal procedure is that exists one endpoint to list this related entities and know it. For example, in a javascript web app I render a form that have a select of this relationated entities, before show this field I call to an endpoint who return the ids and labels from this entities: ``` { {“id”: 1, “label”: “value 1”}, {“id”: 2, “label”: “value 2”} } ``` After that we render the field with this values and the user select one, and this is if is finally sent to your endpoint. I hope this can help you Upvotes: 0
2018/03/16
763
3,025
<issue_start>username_0: Can we update the UWP TextBlock's text from **AppService**? Here I'm having the app service in different UWP Runtime Component project and that is added as reference to the UI project. So I don't have direct connection with UI. But I need to update UI if the App is running as active. **Note:** We may show the Toast and Live Tile instead. But want to know the possibility to directly update the UI. **Edited: [18/3/18]** I'm trying to merge existing WPF app within UWP using **DesktopBridge**. Here I need to have two way communication between both apps. So created two AppServices separately in WPF and UWP to send and receive data in form of ValueSet and based on the requested data need to update the UI. For WPF App having the UI and AppService in same project. For UWP App separated the AppServices as Runtime Component project (Out-Of-Proc). In this case both AppServices are working fine at runtime but cannot update the UWP UI (But able to update the WPF UI). Also I tried to have in-proc services, in this case both AppServices are working fine but I cannot establish a connection from UWP to WPF. So I cannot send request from UWP (WPF to UWP is working). So this is my actual problem. Want to know am I doing right? And is there any way to fix or any other better way to do it. Followings are the **.appmanifest** code. **As In-Proc service** ``` ``` **As Out-Of-Proc service** ``` ```<issue_comment>username_1: You could use an **In-process App Service** as described in the [documentation](https://learn.microsoft.com/en-us/windows/uwp/launch-resume/convert-app-service-in-process). > > App Services can now run in the same process as the foreground > application which makes communication between apps much easier and > removes the need to separate the service code into a separate project. > > > This means you don't even have to move the code to a separate Windows Runtime Component and you may communicate with the UI in case it is active via `Window.Current`. However, you need to remember to make sure that your code manipulating the UI runs on the UI thread using `Dispatcher`. Upvotes: 2 <issue_comment>username_2: If you have configured your AppService to run in-proc with the foreground app then you can update the UI directly. If the AppService is running out-of-proc, then you would need to send a request to the foreground app to update it's UI on your behalf, or go with toast/tile notifications. Here is some info on how to make your AppService run in-proc with the application process: <https://learn.microsoft.com/en-us/windows/uwp/launch-resume/convert-app-service-in-process> Regarding the edited question, the typical pattern to use is this: When the WPF app launches, open the app service connection to the UWP. Now on both sides keep a reference to the respective instance of the AppServiceConnection object. This way you can do two-way communication and either side (UWP and WPF) can establish a request to the other side. Upvotes: 2
2018/03/16
458
1,792
<issue_start>username_0: I have a content-type referring to an other content-type (a pair of articles), which refer to a content-type (an article). I would like to redirect to the article url when the article block is clicked on my twig, so I came up with the code below ``` {% for i, value in node.field_articles_pairs %} {% endfor %} function onArticleClick(link) { window.location.href = link; } ``` Unfortunately, this is not working, I've got an error saying that the route does not exists. How can I refer to my article url with that complex structure ?<issue_comment>username_1: There's two different approaches you can use to get the node/entity reference url for output: * **Option 1:** 1. Create a separate display mode (maybe name it "teaser") under the Structure > Content Types > [Parent Content Type] settings. 2. Then create a node-type and display-mode-specific twig template (article--teaser.html.twig). In it, you can output the `related_article` div with click handler. 3. Then in your existing parent node-type twig template, you can simply output `{{field_articles_pairs}}` as it will loop through and pull the custom twig template for each article entity referenced in the field. * **Option 2:** Add custom preprocess node functionality for the referencing/parent content type to include the urls with each field\_articles value. Upvotes: 3 [selected_answer]<issue_comment>username_2: I believe this should be the syntax? ``` {% for article_pair in node.field_articles_pairs %} {% for article in article_pair.entity.field_articles %} {{ path('entity.node.canonical', {'node': article.entity.id}) }} {% endfor %} {% endfor %} ``` I think the first parameter in path is a string defining the type of path, not a value of the entity. Upvotes: 3
2018/03/16
1,057
4,291
<issue_start>username_0: I'm trying to encrypt some information in two different files, the first with a String encrypted in AES and the second with a Key encrypted with RSA, but I'm having some trouble making it work. Here's my method: ``` public synchronized static void encrypToFile(KeyPair clauPublicaPrivada, SecretKey clauSecretaSimetrica) { String dades = null; byte[][] encWrappedData = new byte[2][]; byte[] dadesAEncriptarEnByte; dades = extreureRutesDB(); dadesAEncriptarEnByte = dades.getBytes(); try { try { File file = new File(FITXER_DADES_TRIPULANTS_XIFRADES_AES128); File file2 = new File(FITXER_DADES_TRIPULANTS_XIFRADES_AES128_CLAUS); boolean fvar = file.createNewFile(); boolean fvar2 = file2.createNewFile(); if (fvar2) { System.out.println("File2 has been created successfully"); } else { System.out.println("File2 already present at the specified location"); } if (fvar) { System.out.println("File1 has been created successfully"); } else { System.out.println("File1 already present at the specified location"); } } catch (IOException e) { System.out.println("Exception Occurred:"); e.printStackTrace(); } Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(IV_PARAM); cipher.init(Cipher.ENCRYPT_MODE, clauSecretaSimetrica, iv); encWrappedData[0] = cipher.doFinal(dadesAEncriptarEnByte); cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); PublicKey clauPublica = clauPublicaPrivada.getPublic(); cipher.init(Cipher.WRAP_MODE, clauPublica); encWrappedData[1] = cipher.wrap(clauSecretaSimetrica); CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(FITXER_DADES_TRIPULANTS_XIFRADES_AES128), cipher); cos.write(encWrappedData[0]); cos.close(); cos = new CipherOutputStream(new FileOutputStream(FITXER_DADES_TRIPULANTS_XIFRADES_AES128_CLAUS), cipher); cos.write(encWrappedData[1]); cos.close(); } catch (Exception ex) { ex.printStackTrace(); } finally { System.out.println("menu 21(): FINAL"); } } ``` The problem is that when I run it I get this error: **java.lang.IllegalStateException: Cipher not initialized for encryption/decryption** Any idea what I'm doing wrong and how to fix it?<issue_comment>username_1: Reusing the same `Cipher` variable for different purposes is poor programming practice and confusing, and led you to these errors. You last left the `cipher` instance in `WRAP_MODE` prior to calling `doWrap()`. Then you supply the same instance to the `CipherOutputStream` constructors. Those require that the `cipher` object be in either `ENCRYPT_MODE` or `DECRYPT_MODE`. Just call `Cipher.getInstance()` for every distinct use of a Cipher object. The overhead of that call will be insignificant in your program unless you're doing something very strange (and likely wrong) indeed. Upvotes: 2 <issue_comment>username_2: You're using the `CipherOutputStream` values incorrectly. To be precise, the way your code is setup you don't need to use them *at all*. These output streams are used to *encrypt* and *decrypt* the data. However, the data is already encrypted when calling `encWrappedData[0] = cipher.doFinal(dadesAEncriptarEnByte);` and `encWrappedData[1] = cipher.wrap(clauSecretaSimetrica);`. So you can simply directly write the result of those calls to file by just using the `FileOutputStream`. --- The RSA-wrapped AES key will always be limited in size, so it doesn't make sense to stream that information. If the message (`dades`) is large you may want to use streaming, and use the AES based cipher instance to perform the encryption, without putting all of the plaintext and ciphertext in a byte array in memory. In that case the `CipherOutputStream` could make sense. Upvotes: 1
2018/03/16
1,172
4,278
<issue_start>username_0: I am having a react-redux action creation problem. My props are an empty object when I log props at the life cycle method componentDidMount() ``` import React, { Component } from 'react'; import { connect } from 'react-redux'; import { fetchSurveys } from '../../actions/index'; export class SurveyList extends Component { componentDidMount() { console.log(this.props); this.props.fetchSurveys(); } renderSurveys() { return ( this.props.surveys.length && this.props.surveys.map(survey => { return ( {survey.title} {survey.body} Sent On: {new Date(survey.dateSent).toLocaleDateString()} Yes: {survey.yes} No: {survey.no} ); }) ); } render() { return {this.renderSurveys()}; } } function mapStateToProps({ surveys }) { return { surveys }; } export default connect(mapStateToProps, { fetchSurveys })(SurveyList); ``` Now according to the react-redux docs by default dispatch is included on the props so we do not need to explicitly call a mapDispatchToProps in the connect method in order to hit our action creators. fetchSurveys() is an action creator and I expect it to return a list of surveys which I then render. However this.props = {}; so of course I cannot call .map on undefined at renderSurveys() as I do not get the surveys property on props either. I am really troubled by why my props are empty. Can anybody shed some light onto this problem, I would be very grateful. I have tried using bindActionCreators and having my own mapDispatchToProps method, this doesn't work either. Here are my actions. ``` import axios from 'axios'; import { FETCH_USER, FETCH_SURVEYS } from './types'; export const fetchUser = () => async dispatch => { const res = await axios.get('/api/current_user'); dispatch({ type: FETCH_USER, payload: res.data }); }; export const handleToken = token => async dispatch => { const res = await axios.post('/api/stripe', token); dispatch({ type: FETCH_USER, payload: res.data }); }; export const submitSurvey = (values, history) => async dispatch => { const res = await axios.post('/api/surveys', values); history.push('/surveys'); dispatch({ type: FETCH_USER, payload: res.data }); }; export const fetchSurveys = () => async dispatch => { console.log('called'); const res = await axios.get('/api/surveys'); dispatch({ type: FETCH_SURVEYS, payload: res.data }); }; ``` My surveys reducer - ``` import { FETCH_SURVEYS } from '../actions/types'; export default function(state = [], action) { switch (action.type) { case FETCH_SURVEYS: return action.payload; default: return state; } } ``` [![enter image description here](https://i.stack.imgur.com/QVvUj.png)](https://i.stack.imgur.com/QVvUj.png) Props in console - [![enter image description here](https://i.stack.imgur.com/y98BI.png)](https://i.stack.imgur.com/y98BI.png) Combined reducer - ``` import { combineReducers } from 'redux'; import authReducer from './authReducer'; import { reducer as reduxForm } from 'redux-form'; import surveysReducer from './surveysReducer'; export default combineReducers({ auth: authReducer, form: reduxForm, surveys: surveysReducer }); ```<issue_comment>username_1: Have you used your reducer in combineReducers? you should have an index.js file in reducers folder (for example) which has something like this: ``` import {myreducer} from './myreducer'; const rootReducer = combineReducers( { myreducer: myreducer } ); export default rootReducer; ``` Do you have complete codebase somewhere? It looks like issue is not in provided code.. Upvotes: 0 <issue_comment>username_2: Seems that you forgot to add your reducer to main reducers file. So, it depends on your code it should be: ``` // reducers/index.js import { combineReducers } from 'redux'; import surveys from './surveysReducer'; const rootReducer = combineReducers({ surveys, }); export default rootReducer; ``` Hope it will helps. Upvotes: 0 <issue_comment>username_3: Just saw your code in the link. In Dashboard.js Shouldn't ``` import { SurveyList } from './surveys/SurveyList'; ``` be ``` import SurveyList from './surveys/SurveyList'; ``` Since the connected component is exported as default? Upvotes: 1
2018/03/16
1,022
3,004
<issue_start>username_0: I want to check if an input string follows a pattern and if it does extract information from it. My pattern is like this `Episode 000 (Season 00)`. The 00s are numbers that can range from 0-9. Now I want to check if this input `Episode 094 (Season 02)` matches this pattern and because it does it should then extract those two numbers, so I end up with two integer variables `94` & `2`: ``` string latestFile = "Episode 094 (Season 02)"; if (!Regex.IsMatch(latestFile, @"^(Episode)\s[0-9][0-9][0-9]\s\((Season)\s[0-9][0-9]\)$")) return int Episode = Int32.Parse(Regex.Match(latestFile, @"\d+").Value); int Season = Int32.Parse(Regex.Match(latestFile, @"\d+").Value); ``` The first part where I check if the overall string matches the pattern works, but I think it can be improved. For the second part, where I actually extract the numbers I'm stuck and what I posted above obviously doesn't works, because it grabs all digits from the string. So if anyone of you could help me figure out how to only extract the three number characters after `Episode` and the two characters after `Season` that would be great.<issue_comment>username_1: In your regex `^(Episode)\s[0-9][0-9][0-9]\s\((Season)\s[0-9][0-9]\)$` you are capturing `Episode` and `Season` in a capturing group, but what you actually want to capture is the digits. You could switch your capturing groups like this: [`^Episode\s([0-9][0-9][0-9])\s\(Season\s([0-9][0-9])\)$`](https://regex101.com/r/AotmAu/1) Matching 3 digits in this way `[0-9][0-9][0-9]` can be written as `\d{3}` and `[0-9][0-9]` as `\d{2}`. That would look like [`^Episode\s(\d{3})\s\(Season\s(\d{2})\)$`](https://regex101.com/r/AotmAu/2) To match one or more digits you could use `\d+`. The `\s` is a matches a [whitespace character](https://www.regular-expressions.info/shorthand.html). You could use `\s` or a whitespace. Your regex could look like: [`^Episode (\d{3}) \(Season (\d{2})\)$`](https://regex101.com/r/ICeS83/2) ``` string latestFile = "Episode 094 (Season 02)"; GroupCollection groups = Regex.Match(latestFile, @"^Episode (\d{3}) \(Season (\d{2})\)$").Groups; int Episode = Int32.Parse(groups[1].Value); int Season = Int32.Parse(groups[2].Value); Console.WriteLine(Episode); Console.WriteLine(Season); ``` That would result in: ``` 94 2 ``` [Demo C#](http://rextester.com/LDWRX89822) Upvotes: 2 <issue_comment>username_2: ``` ^Episode (\d{1,3}) \(Season (\d{1,2})\)$ ``` Captures the 2 numbers (even with length 1 to 3/2) and gives them back as a group. You can go even further and name your groups: ``` ^Episode (?\d{1,3}) \(Season (?\d{1,2})\)$ ``` and then call them. Example for using groups: ``` string pattern = @"abc(?\d{1,3})abc"; string input = "abc234abc"; Regex rgx = new Regex(pattern); Match match = rgx.Match(input); string result = match.Groups["firstGroup"].Value; //=> 234 ``` You can see what the expressions mean and test them [here](https://regex101.com/) Upvotes: 3 [selected_answer]
2018/03/16
523
1,692
<issue_start>username_0: My `Post` entity looks like this: ``` php // ... class Post { /** * The ID generated manually. * * @ORM\Id * @ORM\Column(type="integer", length=3) */ private $id; //... /** * One Post has One Post. * * @ORM\OneToOne(targetEntity="DovStone\Bundle\BlogAdminBundle\Entity\Post", fetch="EAGER") * @JoinColumn(name="parent_id", referencedColumnName="id") */ private $parent; </code ``` One insertion works as expected and I can even get the parent `$post->getParent()` of a given post. A problem occures when I try to make **another post insertion which has the same parent as the previous post inserted successfuly**. I'll make this following example so you can get clearly what I mean: Insertion #1: **Id**: 613 **Parent**: NULL `//success` Insertion #2: **Id**: 156 **Parent**: 613 `//success` Insertion #3: **Id**: 156 **Parent: 613** `//fail` Insertion #3 returns me `SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed` because I think insertion #2 has already its parent it as **613**. So what should I do to tell doctrine `parent_id` column must not be unique as `id` column.<issue_comment>username_1: If your $parent class could have more than one child, it should be usually mapped as ManyToOne relation Upvotes: 1 <issue_comment>username_2: You need to change your relation from ``` @ORM\OneToOne ``` to ``` @ORM\ManyToOne ``` Like this: ``` @ORM\ManyToOne(targetEntity="DovStone\Bundle\BlogAdminBundle\Entity\Post", inversedBy="DovStone\Bundle\BlogAdminBundle\Entity\Post", fetch="EAGER") @ORM\JoinColumn(name="parent_id", referencedColumnName="id") ``` Upvotes: 3 [selected_answer]
2018/03/16
791
2,440
<issue_start>username_0: I'm trying to get `Reticulate` working in `RMarkdown`, per the setup instructions. However, I am unable to share state between separate Python cells or Python and R cells, as the docs indicate I should be able to. Here is my setup and output: Cell 1 (Setup): ``` {r} library(reticulate) path_to_python <- "/Users/User/anaconda3/bin/python" use_python(path_to_python) knitr::knit_engines$set(python = reticulate::eng_python) py_available(initialize = TRUE) ``` Output: ``` [1] TRUE ``` Cell 2 (set variable in Python): ``` {python} x = 2 ``` Cell 3 (attempt to access Python variable in R): ``` {r} py$x ``` Output: ``` Error in py_get_attr_impl(x, name, silent) : AttributeError: module '__main__' has no attribute 'x' ``` Cell 4 (set variable in R): ``` {r} x <- 2 ``` Cell 5 (attempt to access R variable in Python): ``` {python} r.x ``` Output: ``` Traceback (most recent call last): File "/<KEY>R<KEY>/chunk-code-108b44104ec28.txt", line 1, in r.x NameError: name 'r' is not defined ``` Cell 6 (attempt to access previous Python variable in subsequent Python cell): ``` {python} x ``` Output: ``` Traceback (most recent call last): File "/<KEY>tmpTqIR6P/chunk-code-108b44520d158.txt", line 1, in x NameError: name 'x' is not defined ``` Any help or advice would be much-appreciated! I have already attempted pointing `reticulate` at different Conda environments and Python installations with no luck. Thanks!<issue_comment>username_1: I think I've figured this out. I misunderstood the reticulate documentation, taking it to mean I could share state between Python cells interactively in RStudio. After perusing the open issues on Github, it appears RStudio integration is still being worked on. When employing knitr directly to knit a document, I get the expected behavior with shared state between cells. Upvotes: 3 <issue_comment>username_2: This is fixed in current RStudio e.g. `1.2.1114`. But if you are like me stuck with RStudio Server Pro 1.1.456 a workaround is to use `reticulate::repl_python()` to run python chunks by copy pasting them into a python console. You can close and open the console again if you need to run an R chunk in between - the state will be maintained. When you are done hacking around you can knit the whole file without problems. Upvotes: 2
2018/03/16
817
2,791
<issue_start>username_0: Following the tutorial about Kafka Streams located at: <https://github.com/confluentinc/kafka-streams-examples/blob/4.0.0-post/src/main/java/io/confluent/examples/streams/WikipediaFeedAvroExample.java> There is a line: ``` import io.confluent.examples.streams.avro.WikiFeed ``` As I suppose it relates to this file: <https://github.com/confluentinc/kafka-streams-examples/blob/4.0.0-post/src/main/resources/avro/io/confluent/examples/streams/wikifeed.avsc> * How does Maven knows it is in `resource` not `java` folder? * Why *io/confluent/examples/streams/**avro**/wikifeed.avsc* instead of ***avro***/io/confluent/examples/streams/wikifeed.avsc? The other import is even more fantastic: ``` import io.confluent.kafka.serializers.AbstractKafkaAvroSerDeConfig; ``` * There is no `kafka` folder in the `java/io/confluent` folder. <https://github.com/confluentinc/kafka-streams-examples/tree/4.0.0-post/src/main/resources/avro/io/confluent>. How does all this magic suppose to work?<issue_comment>username_1: The `WikiFeed` class is created dynamically at build time using the `avro-maven-plugin` from the .avsc file you linked to. You can check how it's configured [in the section of pom.xml](https://github.com/confluentinc/kafka-streams-examples/blob/4.0.0-post/pom.xml#L346-L363). The `AbstractKafkaAvroSerDeConfig` class comes from the `kafka-avro-serializer` dependency. Eclipse has a nice way of navigating from the individual class in the Editor view back to the Package Explorer which includes the Maven dependencies, like this: [![package explorer: maven dependencies](https://i.stack.imgur.com/6UoTb.png)](https://i.stack.imgur.com/6UoTb.png) Upvotes: 1 <issue_comment>username_2: The *magic* is made by [avro-maven-plugin](https://github.com/phunt/avro-maven-plugin) which you can find in the [pom.xml](https://github.com/confluentinc/kafka-streams-examples/blob/4.0.0-post/pom.xml): ```xml org.apache.avro avro-maven-plugin ${avro.version} generate-sources schema src/main/resources/avro/io/confluent/examples/streams ${project.build.directory}/generated-sources String ``` Quoting from the documentation of the plugin: > > Simple integration with dynamic languages. Code generation is not required to read or write data files nor to use or implement RPC protocols. Code generation as an optional optimization, only worth implementing for statically typed languages. > > > This is, at pre compile time, the plugin reads the content of *avsc* files and generate binary sources (for this case, Java classes) that then can be used in the code. You can see the code generated by the plugin in `target/generated-sources`. There will be a folder structure and proper java (not class) files there. Upvotes: 3 [selected_answer]
2018/03/16
469
1,848
<issue_start>username_0: I'm new to machine learning. I've got a huge database of sensor data from weather stations. Those sensors can be broken or have odd values. Broken sensors influences the calculations that are being done with that data. The goal is to use machine-learning to detect if new sensor values are odd and mark them as broken if so. As said, I'm new to ML. Can somebody push me in the right direction or give feedback to my approach. The data has a datetime and a value. The sensor values are being pushed every hour. I appreciate any kind of help!<issue_comment>username_1: Since the question is pretty general in nature, I will provide some basic thoughts. Maybe you are already slightly familiar with them. 1. Set up a dataset that contains both broken sensors, as well as good sensors. That is the dependent variable. With that set you also have some variables that might predict the Y variable. Let's call them X. 2. You train a model to learn te relationship between X and Y. 3. You predict, based on X values where you do not know the outcome, what Y will be. Some useful insight on the basics, is here: <https://www.youtube.com/watch?v=elojMnjn4kk&list=PL5-da3qGB5ICeMbQuqbbCOQWcS6OYBr5A> Good Luck! Upvotes: 2 <issue_comment>username_2: You could use Isolation Forest to detect abnormal readings. Twitter has developed a algorithm called ESD (Extreme Studentized Deviate) also useful. <https://github.com/twitter/AnomalyDetection/> However a good EDA (Exploratory data analysis) is needed to define the types of abnormality found in the readings due to faulty sensors. 1) Step kind of trend, where suddenly the value increases and remains increased or decreased as well 2) Gradual increase in the value compared to other sensors and suddenly very high increase 3) Intermittent spike in the data Upvotes: 0
2018/03/16
1,549
4,651
<issue_start>username_0: I'm using `react`. `Material-ui` is for `Cards`. For `Grid` I'm using CSS Grid Layout. So far it looks like this: [![enter image description here](https://i.stack.imgur.com/0FDyY.png)](https://i.stack.imgur.com/0FDyY.png) But my goal is something like this: [![enter image description here](https://i.stack.imgur.com/Ue2TW.png)](https://i.stack.imgur.com/Ue2TW.png) And I have 2 problems: 1. I want to have all these `cards` the same height (415px). I tried height: 415px on `.BeerListingScroll-info-box` but it doesn't work. 2. Images of bottles and kegs are diffrent in size [keg (80px x 160px) vs. bottle (80px x 317px)]. Is there any way to make them more similar in rendered size? - Code: `BeerListingScroll` ``` import React, { Component } from 'react'; import ReduxLazyScroll from 'redux-lazy-scroll'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchBeers } from '../../actions/'; import BeersListItem from '../../components/BeersListItem'; import ProgressIndicator from '../../components/ProgressIndicator'; import './style.css'; class BeerListingScroll extends Component { constructor(props) { super(props); this.loadBeers = this.loadBeers.bind(this); } loadBeers() { const { skip, limit } = this.props.beers; this.props.fetchBeers(skip, limit); } render() { const { beersArray, isFetching, errorMessage, hasMore } = this.props.beers; return ( {beersArray.map(beer => ( ))} {isFetching && ( )} {!hasMore && !errorMessage && ( All the beers has been loaded successfully. )} ); } } function mapStateToProps(state) { return { beers: state.beers, }; } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchBeers }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(BeerListingScroll); ``` `BeerListingScroll css` ``` .BeerListingScroll-wrapper { display: grid; margin: 0; grid-gap: 10px; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr) ) ; background-color: #f7f7f7; } .BeerListingScroll-info-box { display: flex; align-items: center; justify-content: center; margin: 0 auto; color: #fff; border-radius: 5px; padding: 20px; font-size: 150%; width: 320px; } /* This applies from 600px onwards */ @media (min-width: 1820px) { .BeerListingScroll-wrapper { margin: 0 400px; } } @media (min-width: 1620px) { .BeerListingScroll-wrapper { margin: 0 300px; } } @media (min-width: 1366px) { .BeerListingScroll-wrapper { margin: 0 200px; } } ``` `BeerListItem` is the child of BeerListingScroll ``` import React from 'react'; import Card, { CardContent } from 'material-ui/Card'; import Typography from 'material-ui/Typography'; function BeerListItem(props) { return ( ![beer]({props.beer.image_url}) ); } export default BeerListItem; ``` Full project on github -> [Github](https://github.com/elminsterrr/beer-app-q2)<issue_comment>username_1: You should try exploring display:flex; Here is a link to a fantastic code pen that may help you achieve what you want: <https://codepen.io/enxaneta/full/adLPwv> More specifically here is an example I've created with what you might be trying to achieve. <https://jsfiddle.net/dalecarslaw/sxdr3eep/> Here is the areas of code you should focus on: ``` display:flex; align-items:space-between; justify-content:space-between; flex-wrap:wrap; ``` Upvotes: 1 <issue_comment>username_2: So for image sizes here I got great [answer](https://stackoverflow.com/questions/49325210/how-to-make-two-different-images-similar-in-size-without-distortion/49325270#49325270). And I added: ``` .BeerListItem-img { height: auto; max-height: 250px; width: auto; max-width: 250px; } ``` And for card size I just added inside `BeerListItem` class to `Card` like so (`.BeerListItem-main-card`): ``` function BeerListItem(props) { return ( ![beer]({props.beer.image_url}) {props.beer.name} {props.beer.tagline} ); } ``` And here is corresponding css to that component. ``` .BeerListItem-main-card { width: 320px; height: 415px; } .BeerListItem-img { height: auto; max-height: 250px; width: auto; max-width: 250px; } ``` With that two changes, I've managed to achieve my goal. Upvotes: 3 <issue_comment>username_3: by using display flex, my humble suggestion is adding "flex:1" to parent element of the card. This will allow your display to set the same size to each children and with that auto adjust each card to the same size, including the img. I solved that, using that property. Upvotes: 1
2018/03/16
1,138
3,973
<issue_start>username_0: Why does this happen? In the following example, when i ISNULL to compare a blank int and a blank varchar they equal each other. When the same logic is wrapped with a convert they do not equal each other. ``` DECLARE @myint int DECLARE @mychar VARCHAR(200) SET @myint = null SET @mychar = NULL SELECT CASE when CONVERT(VARCHAR(40),iSNULL(@myint,'')) = CONVERT(VARCHAR(40),ISNULL(@mychar,'')) THEN 1 ELSE 0 END AS 'poop' SELECT CASE when iSNULL(@myint,'') =ISNULL(@mychar,'') THEN 1 ELSE 0 END AS 'poop'` ``` The reason this is an issue is because I am creating hashkeys with several appended fields. I recently changed the data type of one field from a varchar to an int (the field only ever stores an int) and now when that field is null the generated hashkey is different because the Convert function somehow sees the data as being different.<issue_comment>username_1: It's instructive if you also print out the results of the smaller expressions: ``` DECLARE @myint int DECLARE @mychar VARCHAR(200) SET @myint = null SET @mychar = NULL SELECT CASE when CONVERT(VARCHAR(40),iSNULL(@myint,'')) = CONVERT(VARCHAR(40),ISNULL(@mychar,'')) THEN 1 ELSE 0 END AS 'poop', CONVERT(VARCHAR(40),iSNULL(@myint,'')), CONVERT(VARCHAR(40),ISNULL(@mychar,'')) SELECT CASE when iSNULL(@myint,'') =ISNULL(@mychar,'') THEN 1 ELSE 0 END AS 'poop', iSNULL(@myint,''), ISNULL(@mychar,'') ``` You should be able to see that even after the `ISNULL` checks, you end up with `@myint` replaced by `0` and `@mychar` an empty string. Why? Because `ISNULL` will always returns data of the same type as its first argument, which for `@myInt` is an `int`. And an `int` cannot store an empty string. When an empty string is converted to an `int`, it's interpreted as `0`. And that's also what's happening in your second comparison - we're comparing an `int` to a `varchar` and since `int` has higher precedence, that's the direction that the conversion happens in and so they compare equal. But in the first case, you're effectively forcing the data conversion to happen in the other direction. And `0` converted to a `varchar` does not become an empty string. Upvotes: 3 [selected_answer]<issue_comment>username_2: The reason is all to do with [Data type precedence (Transact-SQL)](https://learn.microsoft.com/en-us/sql/t-sql/data-types/data-type-precedence-transact-sql), and this is a documented part of SQL Server. For [`ISNULL`](https://learn.microsoft.com/en-us/sql/t-sql/functions/isnull-transact-sql), the data type used is the datatype of the first value. So for `ISNULL(@int,'')`, if the value of `@int` is *`NULL`*, then then value `''` will be used. `''` however, is `varchar`, and has a **lower** data type precedence than `int`; thus it is converted to an `int`. `''` as an int is `0`. So, (assuming again than `@int` has a value of *`NULL`*) `ISNULL(@int,'') = 0` would evaluate to true. If, however, `@int` was a (oddly) a `varchar`, then `ISNULL(@int,'')` would return `''`, not `0`. So, straight away, you can see a difference in behaviour because of the data types. *note, however, that `ISNULL(@int,'') = 0` would still evaluate to true, even if `@int` was a `varchar`, as data type precedence would again apply when resolving the expression.* Different functions handle data type precedence differently. So, for example `COALESCE` uses the highest data type precedence in used in the function. Thus `COALESCE('a',1)` would try return an `int` (and fail). On the other hand, `ISNULL('a',1)` would return a `varchar(1)`, as that's the datatype of the first parameter. Upvotes: 0 <issue_comment>username_3: This is because of implicit conversion. When you wrap an int in ISNULL and tell it to return an empty string there is an implicit conversion of that empty string to an int. When an empty string is converted to an int it becomes 0. Here is what I mean. ``` DECLARE @myint int SET @myint = null select iSNULL(@myint,'') ``` Upvotes: 0
2018/03/16
1,613
6,171
<issue_start>username_0: I use stackoverflow on a regular basis to find answers to my problems, but I cannot seem to solve this one. So here is my first question: I have a Google form that (amongst other things) asks for the duration of a job. I want the google spreadsheet to contain the form-answers, and add some columns. In this case, I want to add the cost of the job, using an hour rate of 126,- But I keep running into problems in calculating with the duration: my script either tells me its a text (if I use getDisplayValue in retrieving the data), or it gives me a #NUM error in the spreadsheet itself. Can anyone pinpoint me towards a solution how to retrieve the hours and the minutes from the form-field (time as duration), so I can do some basic math with it in the script? I've setup a small form and connected spreadsheet showing my problems. The example form only asks for the duration, and places this in the spreadsheet in column 2. In the spreadsheet I've setup a script that runs on form submit an I try to explain all steps I do. The script should take the form input, convert it to hours (as a num-field) and multiply that with the PricePerHour. The result should be placed in column 3 on the same row of the form submit. This is my script so far: ``` // CALCULATE COST OF JOB function calculatePriceDuration(e) { // get source data var sourceSheet = SpreadsheetApp.getActiveSheet(); // connect to source sheet var sourceRow = sourceSheet.getActiveRange().getRow(); // connect to event row (form submit) // get destination data var destinationSheet = sourceSheet; // connect to destination sheet var destinationRow = sourceRow; // connect to destination row var destinationColID = 3; // set column number of value to paste // set variables var colID_FormDuration = 2; // set column number where the form places the duration var formDuration = sourceSheet.getRange(sourceRow, colID_FormDuration).getDisplayValue(); // get value for duration // set price per hour var PricePerHour = 126; // calculate job price var PriceForJob = formDuration * PricePerHour; // set destination cell destinationSheet.getRange(destinationRow,destinationColID).setValue(PriceForJob); // paste value in the 3rd column of the same row of form submit } ``` the spreadsheet itself can be found [here](https://docs.google.com/spreadsheets/d/1jnLmIyjA15ll1bxEyQvJpMFVvC-qPpTR9202mJwyx1Y/edit#gid=480868069): the form can be found [here](https://docs.google.com/forms/d/e/1FAIpQLSdniHbIK13G2YXY3TcCjxSqXZ5vxDZl6aEID7wEJqi9QrVajQ/viewform): Any help is much appreciated! Kind regards, Rob<issue_comment>username_1: It's instructive if you also print out the results of the smaller expressions: ``` DECLARE @myint int DECLARE @mychar VARCHAR(200) SET @myint = null SET @mychar = NULL SELECT CASE when CONVERT(VARCHAR(40),iSNULL(@myint,'')) = CONVERT(VARCHAR(40),ISNULL(@mychar,'')) THEN 1 ELSE 0 END AS 'poop', CONVERT(VARCHAR(40),iSNULL(@myint,'')), CONVERT(VARCHAR(40),ISNULL(@mychar,'')) SELECT CASE when iSNULL(@myint,'') =ISNULL(@mychar,'') THEN 1 ELSE 0 END AS 'poop', iSNULL(@myint,''), ISNULL(@mychar,'') ``` You should be able to see that even after the `ISNULL` checks, you end up with `@myint` replaced by `0` and `@mychar` an empty string. Why? Because `ISNULL` will always returns data of the same type as its first argument, which for `@myInt` is an `int`. And an `int` cannot store an empty string. When an empty string is converted to an `int`, it's interpreted as `0`. And that's also what's happening in your second comparison - we're comparing an `int` to a `varchar` and since `int` has higher precedence, that's the direction that the conversion happens in and so they compare equal. But in the first case, you're effectively forcing the data conversion to happen in the other direction. And `0` converted to a `varchar` does not become an empty string. Upvotes: 3 [selected_answer]<issue_comment>username_2: The reason is all to do with [Data type precedence (Transact-SQL)](https://learn.microsoft.com/en-us/sql/t-sql/data-types/data-type-precedence-transact-sql), and this is a documented part of SQL Server. For [`ISNULL`](https://learn.microsoft.com/en-us/sql/t-sql/functions/isnull-transact-sql), the data type used is the datatype of the first value. So for `ISNULL(@int,'')`, if the value of `@int` is *`NULL`*, then then value `''` will be used. `''` however, is `varchar`, and has a **lower** data type precedence than `int`; thus it is converted to an `int`. `''` as an int is `0`. So, (assuming again than `@int` has a value of *`NULL`*) `ISNULL(@int,'') = 0` would evaluate to true. If, however, `@int` was a (oddly) a `varchar`, then `ISNULL(@int,'')` would return `''`, not `0`. So, straight away, you can see a difference in behaviour because of the data types. *note, however, that `ISNULL(@int,'') = 0` would still evaluate to true, even if `@int` was a `varchar`, as data type precedence would again apply when resolving the expression.* Different functions handle data type precedence differently. So, for example `COALESCE` uses the highest data type precedence in used in the function. Thus `COALESCE('a',1)` would try return an `int` (and fail). On the other hand, `ISNULL('a',1)` would return a `varchar(1)`, as that's the datatype of the first parameter. Upvotes: 0 <issue_comment>username_3: This is because of implicit conversion. When you wrap an int in ISNULL and tell it to return an empty string there is an implicit conversion of that empty string to an int. When an empty string is converted to an int it becomes 0. Here is what I mean. ``` DECLARE @myint int SET @myint = null select iSNULL(@myint,'') ``` Upvotes: 0
2018/03/16
1,164
4,238
<issue_start>username_0: This seems to be a duplicate question of an already asked one but not really. What I'm looking for is one or more regular expressions without the help of any programming language to change the following text `String.Concat( new string[] { "some", "random", "text", string1, string2, "end" })` into `"some" + "random" + "text" + string1 + string2 + "end"`. I was thinking of using two regular expressions, replacing the commas with pluses, and then removing the `String.Concat( new string[] { ... })`. The second part is quite easy, but I am struggling with the first regular expression. I used a positive look-behind expression, but it matches only the first comma: `(?<=String\.Concat\(new string\[\] \{[^,}]*),` I'm not an expert but I think that this is a limitation of the regular expression engine. Once the first comma is matched, the regular expression engine moves the starting matching index after the comma and it doesn't match anymore the look-behind group before it. --- Is there a regular expression to make this substitution, pluses instead of commas, without the help on any programming language?<issue_comment>username_1: It's instructive if you also print out the results of the smaller expressions: ``` DECLARE @myint int DECLARE @mychar VARCHAR(200) SET @myint = null SET @mychar = NULL SELECT CASE when CONVERT(VARCHAR(40),iSNULL(@myint,'')) = CONVERT(VARCHAR(40),ISNULL(@mychar,'')) THEN 1 ELSE 0 END AS 'poop', CONVERT(VARCHAR(40),iSNULL(@myint,'')), CONVERT(VARCHAR(40),ISNULL(@mychar,'')) SELECT CASE when iSNULL(@myint,'') =ISNULL(@mychar,'') THEN 1 ELSE 0 END AS 'poop', iSNULL(@myint,''), ISNULL(@mychar,'') ``` You should be able to see that even after the `ISNULL` checks, you end up with `@myint` replaced by `0` and `@mychar` an empty string. Why? Because `ISNULL` will always returns data of the same type as its first argument, which for `@myInt` is an `int`. And an `int` cannot store an empty string. When an empty string is converted to an `int`, it's interpreted as `0`. And that's also what's happening in your second comparison - we're comparing an `int` to a `varchar` and since `int` has higher precedence, that's the direction that the conversion happens in and so they compare equal. But in the first case, you're effectively forcing the data conversion to happen in the other direction. And `0` converted to a `varchar` does not become an empty string. Upvotes: 3 [selected_answer]<issue_comment>username_2: The reason is all to do with [Data type precedence (Transact-SQL)](https://learn.microsoft.com/en-us/sql/t-sql/data-types/data-type-precedence-transact-sql), and this is a documented part of SQL Server. For [`ISNULL`](https://learn.microsoft.com/en-us/sql/t-sql/functions/isnull-transact-sql), the data type used is the datatype of the first value. So for `ISNULL(@int,'')`, if the value of `@int` is *`NULL`*, then then value `''` will be used. `''` however, is `varchar`, and has a **lower** data type precedence than `int`; thus it is converted to an `int`. `''` as an int is `0`. So, (assuming again than `@int` has a value of *`NULL`*) `ISNULL(@int,'') = 0` would evaluate to true. If, however, `@int` was a (oddly) a `varchar`, then `ISNULL(@int,'')` would return `''`, not `0`. So, straight away, you can see a difference in behaviour because of the data types. *note, however, that `ISNULL(@int,'') = 0` would still evaluate to true, even if `@int` was a `varchar`, as data type precedence would again apply when resolving the expression.* Different functions handle data type precedence differently. So, for example `COALESCE` uses the highest data type precedence in used in the function. Thus `COALESCE('a',1)` would try return an `int` (and fail). On the other hand, `ISNULL('a',1)` would return a `varchar(1)`, as that's the datatype of the first parameter. Upvotes: 0 <issue_comment>username_3: This is because of implicit conversion. When you wrap an int in ISNULL and tell it to return an empty string there is an implicit conversion of that empty string to an int. When an empty string is converted to an int it becomes 0. Here is what I mean. ``` DECLARE @myint int SET @myint = null select iSNULL(@myint,'') ``` Upvotes: 0
2018/03/16
528
1,815
<issue_start>username_0: I created an arraylist with 4 items ``` val myList = arrayListOf("Item1", "Item2", "Item3", "Item4") ``` Then I printed a random item from myList ``` val randomNum = Random() val randomItem = randomNum.nextInt(myList.count()) println(myList[randomItem]) ``` Shouldn't this fail? Once randomItem is equal to 4? Ideally what I'm asking is that randomItem is returning an int from 0-4, correct? But the arraylist index is only 0-3. Should I do -1 to randomItem? I'm just confused because the program isn't throwing an error.<issue_comment>username_1: The [documentation](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-) explains it pretty well: > > `int nextInt(int bound)` > > > Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value **(exclusive)**, drawn from this random number generator's sequence. > > > Upvotes: 1 <issue_comment>username_2: See the API here [Random.nextInt(int bound)](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-) > > public int nextInt(int bound) > > > Returns a pseudorandom, **uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)**, drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All bound possible int values are produced with (approximately) equal probability. > > > **Parameters**: > bound - the upper bound (**exclusive**). Must be positive. > > > **Returns**: > the next pseudorandom, uniformly distributed int value between zero (inclusive) and bound (exclusive) from this random number generator's sequence > > > So in your case, you get 0, 1, 2 or 3 Upvotes: 2
2018/03/16
1,431
4,681
<issue_start>username_0: I am doing some entity matching based on string edit distance and my results are a dictionary with keys (query string) and values [list of similar strings] based on some scoring criteria. for example: ``` results = { 'ben' : ['benj', 'benjamin', 'benyamin'], 'benj': ['ben', 'beny', 'benjamin'], 'benjamin': ['benyamin'], 'benyamin': ['benjamin'], 'carl': ['karl'], 'karl': ['carl'], } ``` Each value also has a corresponding dictionary item, for which it is the key (e.g. 'carl' and 'karl'). I need to combine the elements that have shared values. Choosing one value as the new key (lets say the longest string). In the above example I would hope to get: ``` results = { 'benjamin': ['ben', 'benj', 'benyamin', 'beny', 'benjamin', 'benyamin'], 'carl': ['carl','karl'] } ``` I have tried iterating through the dictionary using the keys, but I can't wrap my head around how to iterate and compare through each dictionary item and its list of values (or single value).<issue_comment>username_1: This is one solution using `collections.defaultdict` and sets. The desired output is very similar to what you have, and can be easily manipulated to align. ``` from collections import defaultdict results = { 'ben' : ['benj', 'benjamin', 'benyamin'], 'benj': ['ben', 'beny', 'benjamin'], 'benjamin': 'benyamin', 'benyamin': 'benjamin', 'carl': 'karl', 'karl': 'carl', } d = defaultdict(set) for i, (k, v) in enumerate(results.items()): w = {k} | (set(v) if isinstance(v, list) else {v}) for m, n in d.items(): if not n.isdisjoint(w): d[m].update(w) break else: d[i] = w result = {max(v, key=len): v for k, v in d.items()} # {'benjamin': {'ben', 'benj', 'benjamin', 'beny', 'benyamin'}, # 'carl': {'carl', 'karl'}} ``` Credit to @username_2 for the idea of manipulating `v` to `w` in second loop. **Explanation** There are 3 main steps: 1. Convert values into a consistent set format, including keys and values from original dictionary. 2. Cycle through this dictionary and add values to a new dictionary. If there is an intersection with some key [i.e. sets are not disjoint], then use that key. Otherwise, add to new key determined via enumeration. 3. Create result dictionary in a final transformation by mapping max length key to values. Upvotes: 3 [selected_answer]<issue_comment>username_2: EDIT : Even though performance was not the question here, I took the liberty to perform some tests between username_1's answer, and mine... here is the full script. My script performs the tests in 17.79 seconds, and his in 23.5 seconds. ``` import timeit results = { 'ben' : ['benj', 'benjamin', 'benyamin'], 'benj': ['ben', 'beny', 'benjamin'], 'benjamin': ['benyamin'], 'benyamin': ['benjamin'], 'carl': ['karl'], 'karl': ['carl'], } def imcoins(result): new_dict = {} # .items() for python3x for k, v in results.iteritems(): flag = False # Checking if key exists... if k not in new_dict.keys(): # But then, we also need to check its values. for item in v: if item in new_dict.keys(): # If we update, set the flag to True, so we don't create a new value. new_dict[item].update(v) flag = True if flag == False: new_dict[k] = set(v) # Now, to sort our newly created dict... sorted_dict = {} for k, v in new_dict.iteritems(): max_string = max(v) if len(max_string) > len(k): sorted_dict[max(v, key=len)] = set(v) else: sorted_dict[k] = v return sorted_dict def username_1(result): from collections import defaultdict res = {i: {k} | (set(v) if isinstance(v, list) else {v}) \ for i, (k, v) in enumerate(results.items())} d = defaultdict(set) for i, (k, v) in enumerate(res.items()): for m, n in d.items(): if n & v: d[m].update(v) break else: d[i] = v result = {max(v, key=len): v for k, v in d.items()} return result iterations = 1000000 time1 = timeit.timeit(stmt='imcoins(results)', setup='from __main__ import imcoins, results', number=iterations) time2 = timeit.timeit(stmt='username_1(results)', setup='from __main__ import username_1, results', number=iterations) print time1 # Outputs : 17.7903265883 print time2 # Outputs : 23.5605850732 ``` If I move the import from his function to global scope, it gives... imcoins : 13.4129249463 seconds username_1 : 21.8191823393 seconds Upvotes: 2
2018/03/16
1,245
4,217
<issue_start>username_0: ``` client_id visittype 1 Comprehensive Eval 1 Psychotherapy 1 Case Management 2 CM Eval 3 Comprehensive Eval 3 Case Management 3 Psychotherapy 4 Comprehensive Eval 5 Comprehensive Eval 5 Psychotherapy ``` I’m new to Python. I need to read a csv file with the two columns above. I need a count of each `client_id` that has at least one `visittype` entry other than an entry with ‘Eval’ in the name. Even if a `client_id` has more than one entry other than ‘%Eval%’, it should only be counted once. I’ll also need a count of the `client_ids` that do not have a `visittype` other than ‘%Eval%’. And, I need the averages for both. In the above sample, `client_ids` 1, 3, and 5 will count as having the qualifying entry. 2 and 4 will not. Total with: 3 Total without: 2 The logic will be something like: ``` For each client_id If visittype NOT like '%Eval%' with_count += 1 client_count +=1 else without_count +=1 client_count +=1 endif avg_with = with_count/client_count avg_without = without_count/client_count ``` I realize that is not Python syntax. I usually post code that I’ve tried when asking a question. I’m choosing not to do that this time since it turned into a mess. Thanks in advance for any help. Feel free to post links to similar code that would help in learning Python.<issue_comment>username_1: A Python-Version of your Pseudo-Code would be like this: ``` for client in clients: if not "Eval" in client: with_count += 1 else: without_count += 1 client_count += 1 avg_with = with_count / client_count avg_witout = without_count / client_count ``` clients would be some kind of iterable from your csv and client would be from type string. To address your only counted once problem, you could use an array and push the user\_id of counted entries into it. ``` counted = [] for i in range(clients): if not "Eval" in clients[i].visittype and not clients[i].client_id in counted: with_count += 1 counted.append(client.id) else: without_count += 1 client_count += 1 avg_with = with_count / client_count avg_witout = without_count / client_count ``` Since we don't know how the structure of the data is you get from the csv, we cannot know how to implement it besides from theory. Upvotes: 1 <issue_comment>username_2: Here's a solution by reading the data into a python dictionary, and then iterating over the keys (Patient ID). ``` import csv with open("data.csv", "r") as f: reader = csv.reader(f, delimiter=",") patient_dict = {} for line in reader: key = line[0] patient_id = line[1] if key not in patient_dict: patient_dict[key] = [] patient_dict[key].append(patient_id) ``` Here the output: ``` {'1': ['Comprehensive Eval', ' Psychotherapy', 'Case Management'], '2': ['CM Eval'], '3': ['Comprehensive Eval', 'Case Management', 'Psychotherapy'], '4': ['Comprehensive Eval'], '5': ['Comprehensive Eval', ' Psychotherapy']} ``` Here's the rest of it ``` with_counter = 0 without_counter = 0 for k, v in patient_dict.items(): for item in v: if 'Eval' not in item: with_counter = with_counter + 1 break else: without_counter = without_counter + 1 print('With = ' + str(with_counter)) print('Without = ' + str(without_counter)) #With = 3 #Without = 2 ``` Upvotes: 1 <issue_comment>username_3: Did you try the pandas library ? If I understand your issue, you can try this (no use of loops here) ``` #import the library & read your file import pandas as pd temp = pd.read_csv("path/to/your/file/your_file.csv") # your condition is : "the type contains "Eval"" condition = temp["visittype"].str.contains("Eval") with_count = temp.loc[~condition, "client_id"].unique() # get the list of non "Eval" count without_count = list(set(temp.loc[condition, "client_id"].unique()) - set(with_count)) client_count = len(temp.client_id.unique()) avg_with = len(with_count) / client_count avg_witout = len(without_count) / client_count ``` Upvotes: 3 [selected_answer]
2018/03/16
735
1,861
<issue_start>username_0: I have a data frame with 29 rows and 26 column with a lot of NA's. Data looks somewhat like shown below( working on R studio) ``` df <- V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 a1 b1 d f d d na na na f a1 b2 d d d f na f na na a1 b3 d f d f na na d d a2 c1 f f d na na d d f a2 c2 f d d f na f na na a2 c3 d f d f na na f d ``` Here we have V1-V10 columns. a1 and a2 are 2 distinct values in column V1, b1-b3 in column V2 are distinct values related to a1 in V1 and c1-c3 related to a2. column V3- V10 we have distinct values in each rows related to a1 and a2 Result i want is as below- ``` NewV1 max.occurrence(V3-V10) a1 d a2 f ``` to summarize i want to get the value with maximum occurrence(max.occurrence(V3-V10)) across column V3-V10 based on V1. NOTE= NA to be excluded.<issue_comment>username_1: Another possiblity using the `data.table`-package: ``` library(data.table) melt(setDT(df), id = 1:2, na.rm = TRUE)[, .N, by = .(V1, value) ][order(-N), .(max.occ = value[1]), by = V1] ``` which gives: ``` V1 max.occ 1: a1 d 2: a2 f ``` A similar logic with the `tidyverse`-packages: ``` library(dplyr) library(tidyr) df %>% gather(k, v, V3:V10, na.rm = TRUE) %>% group_by(V1, v) %>% tally() %>% arrange(-n) %>% slice(1) %>% select(V1, max.occ = v) ``` Upvotes: 1 <issue_comment>username_2: If you like `dplyr`, this would work: ``` df %>% gather("key", "value", V3:V10) %>% group_by(V1) %>% dplyr::summarise(max.occurence = names(which.max(table(value)))) ``` This gives: ``` # A tibble: 2 x 2 V1 max.occurence 1 a1 d 2 a2 f ``` Upvotes: 0
2018/03/16
569
2,286
<issue_start>username_0: I just discovered screenshots possibilities using `client.content` property. So to test this functionnality, I put this code and bind it to the `XF86Reload` key : ``` awful.key({ }, "XF86Reload", function() local i = 0 for c in awful.client.iterate(function() return true end) do local f = c.name gears.surface(c.content):write_to_png( "/home/david/" .. string.format('%02i',i) .."-" .. f .. ".png") i=i+1 end end) ``` Unfortunately, some images are puzzled. Is the Cairo surface needs to be on the screen (ie non minimized) to be properly shot? (it seems it's also happening sometimes to visible windows) or maybe some other reason I can't see...<issue_comment>username_1: Another possiblity using the `data.table`-package: ``` library(data.table) melt(setDT(df), id = 1:2, na.rm = TRUE)[, .N, by = .(V1, value) ][order(-N), .(max.occ = value[1]), by = V1] ``` which gives: ``` V1 max.occ 1: a1 d 2: a2 f ``` A similar logic with the `tidyverse`-packages: ``` library(dplyr) library(tidyr) df %>% gather(k, v, V3:V10, na.rm = TRUE) %>% group_by(V1, v) %>% tally() %>% arrange(-n) %>% slice(1) %>% select(V1, max.occ = v) ``` Upvotes: 1 <issue_comment>username_2: If you like `dplyr`, this would work: ``` df %>% gather("key", "value", V3:V10) %>% group_by(V1) %>% dplyr::summarise(max.occurence = names(which.max(table(value)))) ``` This gives: ``` # A tibble: 2 x 2 V1 max.occurence 1 a1 d 2 a2 f ``` Upvotes: 0
2018/03/16
346
1,048
<issue_start>username_0: I use cx\_Oracle driver with SQLAlchemy to create engine. Succesfully create enine like: ``` conn_string = 'oracle+cx_oracle://user:pass@host:1521/?service_name=some_service' eng = create_engine(conn_string, encoding='utf8') ``` When I try to connect with: ``` eng.connect() ``` I catch the error: ``` DatabaseError: (cx_Oracle.DatabaseError) DPI-1004: unable to get error message ``` Using: ``` Python 3.5.2 cx-Oracle (6.2.1) SQLAlchemy (1.1.15) ``` Does anybody know solution?<issue_comment>username_1: Run a script that looks like this in order to determine the source of the issue: ``` import cx_Oracle try: cx_Oracle.connect("user/pw@dsn") except cx_Oracle.DatabaseError as e: obj, = e.args print("Context:", obj.context) print("Message:", obj.message) ``` Upvotes: 1 <issue_comment>username_2: The problem is solved. it needs to provide full TNS sting in create engine like: ``` eng = create_engine('oracle+cx_oracle://user:pass@full_TNS_string') ``` Upvotes: 1 [selected_answer]
2018/03/16
801
2,887
<issue_start>username_0: This worked at some point but I can't figure out what went wrong or how to correct course. I'm getting the following on my index page: NoMethodError in Admin::Locations#index undefined method `name' for nil:NilClass It's coming from the following: ``` <% @locations.each do |location| %> | <%= location.name %> | <%= location.state %> | <%= location.region.name %> | <% end %> ``` Specifically the location.region.name. My locations controller looks like: ``` class Admin::LocationsController < Admin::ApplicationController belongs_to_app :locations add_breadcrumb 'Locations', :admin_locations_path before_action :load_location, only: [:show, :edit, :update, :destroy] def index @locations = Location.ordered.paginate(page: params[:page]) @locations = @locations.search(params[:search]) if params[:search] respond_with @locations end def show respond_with @location end def new @location = Location.new respond_with @location end def create @location = Location.new(location_params) flash[:notice] = 'Location created successfully' if @location.save respond_with @location, location: admin_locations_path end def edit respond_with @location end def update flash[:notice] = 'Location updated successfully' if @location.update_attributes(location_params) respond_with @location, location: admin_locations_path end def destroy flash[:notice] = 'Location deleted successfully' if @location.destroy respond_with @location, location: admin_locations_path end private def load_location @location = Location.find_by!(id: params[:id]) end def location_params params.require(:location).permit(:name, :hours_operation, :abbreviation, :address_1, :address_2, :city, :state, :postal_code, :phone, :fax, :region, :region_id) end end ``` Now if I change `location.region.name` to `location.region`, it will actually generate something like ``` # ``` Really there's only one region being applied so I'm at a loss.<issue_comment>username_1: You should replace it to: ``` location.region.try(:name) ``` Upvotes: 0 <issue_comment>username_2: > > Now if I change location.region.name to location.region, it will actually generate something like > > > > ``` > # > > ``` > > Ah, but if you use simply use `location.region`, do you have that for all locations? I bet you $10 that there's at least one location without this. (meaning that this location's region is `nil`. Also meaning that it's a data problem and rolling code back likely wouldn't help) A quick fix would be to do what @Kwstas suggests. Or this one (called "safe navigation operator" or "lonely operator"): ``` location.region&.name ``` But this is just a band-aid. If regions are mandatory for all locations, I'd look into ways of ensuring that. Maybe put some activerecord validations in place, or something. Upvotes: 3 [selected_answer]
2018/03/16
1,071
3,159
<issue_start>username_0: I am using mongodb 3.6.3 on a centos 7 aws ec2 instance. 2 Questions (only one needs to be answered): 1. Why is the --logpath preventing the mongod command if done manually through the cli with `sudo mongod --storageEngine etc` 2. Why is `sudo service mongod status` showing the failure that it is? When I run the below command, (since currently, `sudo service mongod start` isn't working but the below works) it fails when I specify the `--logpath` but will run without it. Unfortunately, when I run it without it, all of my logs end up in the `/` which is absolutely the wrong location. `sudo mongod --storageEngine wiredTiger --dbpath /data --bind_ip 127.0.0.1,apiIP --logpath /var/log/mongodb/mongod.log --auth --fork` Below is what happens when I try to run that above line as is. `I CONTROL [main] log file "/var/log/mongodb/mongod.log" exists; moved to "/var/log/mongodb/mongod.log.2018-03-16T15-16-01".` From what I can tell, it is conflicting with the currently existent Just for reference, `sudo service mongod status` returns: ``` mongod.service - mongodb database Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Fri 2018-03-16 15:11:53 UTC; 9min ago Process: 26620 ExecStart=/usr/bin/mongod $OPTIONS run (code=exited, status=2) Main PID: 26620 (code=exited, status=2) Mar 16 15:11:53 ip-* systemd[1]: Started mongodb database. Mar 16 15:11:53 ip-* systemd[1]: Starting mongodb database... Mar 16 15:11:53 ip-* mongod[26620]: F CONTROL [main] Failed global initialization: FileNotOpen: Failed to open "/var/log/mongodb/mongod.log" Mar 16 15:11:53 ip-* systemd[1]: mongod.service: main process exited, code=exited, status=1/FAILURE Mar 16 15:11:53 ip-* systemd[1]: Unit mongod.service entered failed state. Mar 16 15:11:53 ip-* systemd[1]: mongod.service failed. ``` /etc/mongod.conf ``` # mongod.conf # for documentation of all options, see: # http://docs.mongodb.org/manual/reference/configuration-options/ # where to write logging data. systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log # Where and how to store data. storage: dbPath: /data # logpath: /log/mongod.log journal: enabled: true engine: wiredTiger # mmapv1: # wiredTiger: # how the process runs processManagement: # fork: true # fork and run in background pidFilePath: /var/run/mongodb/mongod.pid # location of pidfile timeZoneInfo: /usr/share/zoneinfo # network interfaces net: port: 27017 bindIp: 127.0.0.1, apiIP ``` Thanks to @AlexBlex for noticing the spacing issue in the yaml file. With that sorted, the status error has this line `Unrecognized option: storage.wiredTiger`<issue_comment>username_1: 1. `cd /var/log` 2. `sudo mkdir -m 777 mongodb` 3. `sudo service mongod start` 4. `sudo service mongod status` Hopefully, that's will do! Upvotes: 3 <issue_comment>username_2: ``` sudo systemctl enable mongod sudo systemctl restart mongod sudo journalctl -u mongod.service ``` Hopefully, that will do! Reference: <https://stackoverflow.com/a/51286526/122441> Upvotes: 1
2018/03/16
345
1,117
<issue_start>username_0: I'm trying to style points in a vector source in OpenLayers 4. I've defined a style: ``` var pStyle = new ol.style.Style({ stroke: new ol.style.Stroke({ width: 6, color: [255, 0, 0, 1] }) }); ``` and added the style in the layer definition ``` var pLayer = new ol.layer.Vector({ source: new ol.source.Vector({ features: [p] }), style: pStyle }); ``` Commenting the style definition makes the point appear on the map so I'm assuming the rest of the code is fine. But I can't get my point to appear in red on the map. fiddle at: <https://codepen.io/fundef/pen/VXKYjP> Where am I going wrong?<issue_comment>username_1: You can use `ol.style.icon` for that. This is a example: Upvotes: 0 <issue_comment>username_2: If you want to use `fill` and `stroke` ``` var myStyle = new ol.style.Style({ image: new ol.style.Circle({ radius: 7, fill: new ol.style.Fill({color: 'black'}), stroke: new ol.style.Stroke({ color: [255,0,0], width: 2 }) }) }) ``` Upvotes: 4
2018/03/16
5,332
18,647
<issue_start>username_0: I'm open to use a lib. I just want something simple to diff two collections on a different criteria than the normal equals function. Right now I use something like : ``` collection1.stream() .filter(element -> !collection2.stream() .anyMatch(element2 -> element2.equalsWithoutSomeField(element))) .collect(Collectors.toSet()); ``` and I would like something like : ``` Collections.diff(collection1, collection2, Foo::equalsWithoutSomeField); ``` (edit) More context: Should of mentioned that I'm looking for something that exists already and not to code it myself. I might code a small utils from your ideas if nothing exists. Also, Real duplicates aren't possible in my case: the collections are Sets. However, duplicates according to the custom equals are possible and should not be removed by this operation. It seems to be a limitation in a lot of possible solutions.<issue_comment>username_1: **Comparing** You can achieve this without the use of any library, just using java's [Comparator](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html) For instance, with the following object ``` public class A { private String a; private Double b; private String c; private int d; // getters and setters } ``` You can use a comparator like ``` Comparator comparator = Comparator.comparing(AA::getA) .thenComparing(AA::getB) .thenComparingInt(AA::getD); ``` This compares the fields `a`, `b` and the int `d`, skipping `c`. The only problem here is that this won't work with null values. --- **Comparing nulls** One possible solution to do a fine grained configuration, that is allow to check for specific null fields is using a `Comparator` class similar to: ``` // Comparator for properties only, only writed to be used with Comparator#comparing public final class PropertyNullComparator> implements Comparator { private PropertyNullComparator() { } public static > PropertyNullComparator of() { return new PropertyNullComparator<>(); } @Override public int compare(Object o1, Object o2) { if (o1 != null && o2 != null) { if (o1 instanceof Comparable) { @SuppressWarnings({ "unchecked" }) Comparable comparable = (Comparable) o1; return comparable.compareTo(o2); } else { // this will throw a ccn exception when object is not comparable @SuppressWarnings({ "unchecked" }) Comparable comparable = (Comparable) o2; return comparable.compareTo(o1) \* -1; // \* -1 to keep order } } else { return o1 == o2 ? 0 : (o1 == null ? -1 : 1); // nulls first } } } ``` This way you can use a comparator specifying the allowed null fields. ``` Comparator comparator = Comparator.comparing(AA::getA) .thenComparing(AA::getB, PropertyNullComparator.of()) .thenComparingInt(AA::getD); ``` --- If you don't want to define a custom comparator you can use something like: ``` Comparator comparator = Comparator.comparing(AA::getA) .thenComparing(AA::getB, Comparator.nullsFirst(Comparator.naturalOrder())) .thenComparingInt(AA::getD); ``` --- **Difference method** The difference (A - B) method could be implemented using two `TreeSets`. ``` static TreeSet difference(Collection c1, Collection c2, Comparator comparator) { TreeSet treeSet1 = new TreeSet<>(comparator); treeSet1.addAll(c1); if (treeSet1.size() > c2.size()) { treeSet1.removeAll(c2); } else { TreeSet treeSet2 = new TreeSet<>(comparator); treeSet2.addAll(c2); treeSet1.removeAll(treeSet2); } return treeSet1; } ``` note: a `TreeSet` makes sense to be used since we are talking of uniqueness with a specific comparator. Also could perform better, the `contains` method of `TreeSet` is `O(log(n))`, compared to a common `ArrayList` that is `O(n)`. Why only a `TreeSet` is used when `treeSet1.size() > c2.size()`, this is because when the condition is not met, the `TreeSet#removeAll`, uses the `contains` method of the second collection, this second collection could be any java collection and its `contains` method its not guaranteed to work exactly the same as the `contains` of the first `TreeSet` (with custom comparator). --- **Edit (Given the more context of the question)** Since collection1 is a set that could contains repeated elements acording to the custom `equals` (not the `equals` of the object) the solution already provided in the question could be used, since it does exactly that, without modifying any of the input collections and creating a new output set. So you can create your own static function (because at least i am not aware of a library that provides a similar method), and use the `Comparator` or a `BiPredicate`. ``` static Set difference(Collection collection1, Collection collection2, Comparator comparator) { collection1.stream() .filter(element1 -> !collection2.stream() .anyMatch(element2 -> comparator.compare(element1, element2) == 0)) .collect(Collectors.toSet()); } ``` **Edit (To Eugene)** *"Why would you want to implement a null safe comparator yourself"* At least to my knowledge there isn't a comparator to compare fields when this are a simple and common null, the closest that i know of is (to raplace my sugested `PropertyNullComparator.of()` [clearer/shorter/better name can be used]): ``` Comparator.nullsFirst(Comparator.naturalOrder()) ``` So you would have to write that line for every field that you want to compare. Is this doable?, of course it is, is it practical?, i think not. Easy solution, create a helper method. ``` static class ComparatorUtils { public static > Comparator shnp() { // super short null comparator return Comparator.nullsFirst(Comparator.naturalOrder()); } } ``` Do this work?, yes this works, is it practical?, it looks like, is it a great solution? well that depends, many people consider the exaggerated (and/or unnecessary) use of helper methods as an anti-pattern, (a good old article by [<NAME>](https://blogs.msdn.microsoft.com/nickmalik/2005/09/06/are-helper-classes-evil/)). There are some reasons listed there, but to make things short, this is an OO language, so OO solutions are normally preferred to static helper methods. --- *"As stated in the documentation : Note that the ordering maintained by a set (whether or not an explicit comparator is provided must be consistent with equals if it is to correctly implement the Set interface. Further, the same problem would arise in the other case, when size() > c.size() because ultimately this would still call equals in the remove method. So they both have to implement Comparator and equals consistently for this to work correctly"* The javadoc says of [TreeSet](https://docs.oracle.com/cd/E17802_01/j2se/j2se/1.5.0/jcp/beta1/apidiffs/java/util/TreeSet.html) the following, but with a clear if: > > Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals **if it is to correctly implement the Set interface** > > > Then says this: > > See Comparable or Comparator for a precise definition of consistent with equals > > > If you go to the [Comparable](https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html) javadoc says: > > It is strongly recommended (though not required) that natural orderings be consistent with equals > > > If we continue to read the javadoc again from Comparable (even in the same paragraph) says the following: > > This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all key comparisons using its compareTo (or compare ) method, so two keys that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface. > > > By this last quote and with a very simple code debug, or even a reading, you can see the use of an internal [TreeMap](https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html), and that all its derivated methods are based on the `comparator`, not the `equals` method; --- *"Why is this so implemented? because there is a difference when removing many elements from a little set and the other way around, as a matter of fact same stands for addAll"* If you go to the definition of `removeAll` you can see that its implementation is in `AbstractSet`, it is not overrided. And this implementation uses a `contains` from the argument collection when this is larger, the beavior of this `contains` is uncertain, it isn't necessary (nor probable) that the received collection (e.g. list, queue, etc) has/can define the same comparator. **Update 1:** This jdk bug is being discussed (and considerated to be fixed) in here <https://bugs.openjdk.java.net/browse/JDK-6394757> Upvotes: 0 <issue_comment>username_2: We use similar methods in our project to shorten repetitive collection filtering. We started with some basic building blocks: ``` static boolean anyMatch(Collection set, Predicate match) { for (T object : set) if (match.test(object)) return true; return false; } ``` Based on this, we can easily implement methods like `noneMatch` and more complicated ones like `isSubset` or your `diff`: ``` static Collection disjunctiveUnion(Collection c1, Collection c2, BiPredicate match) { ArrayList diff = new ArrayList<>(); diff.addAll(c1); diff.addAll(c2); diff.removeIf(e -> anyMatch(c1, e1 -> match.test(e, e1)) && anyMatch(c2, e2 -> match.test(e, e2))); return diff; } ``` *Note that there are for sure some possibilities for perfomance tuning. But keeping it separated into small methods help understanding and using them with ease. Used in code they read quite nice.* You would then use it as you already said: ``` CollectionUtils.disjunctiveUnion(collection1, collection2, Foo::equalsWithoutSomeField); ``` Taking <NAME>'s suggestion into account, you could even use `Comparator` to build your criteria on the fly: ``` Comparator special = Comparator.comparing(Foo::thisField) .thenComparing(Foo::thatField); BiPredicate specialMatch = (e1, e2) -> special.compare(e1, e2) == 0; ``` Upvotes: 2 <issue_comment>username_3: ``` static Collection diff(Collection minuend, Collection subtrahend, BiPredicate equals) { Set> w1 = minuend.stream().map(item -> new Wrapper<>(item, equals)).collect(Collectors.toSet()); Set> w2 = subtrahend.stream().map(item -> new Wrapper<>(item, equals)).collect(Collectors.toSet()); w1.removeAll(w2); return w1.stream().map(w -> w.item).collect(Collectors.toList()); } static class Wrapper { T item; BiPredicate equals; Wrapper(T item, BiPredicate equals) { this.item = item; this.equals = equals; } @Override public int hashCode() { // all items have same hash code, check equals return 1; } @Override public boolean equals(Object that) { return equals.test(this.item, ((Wrapper) that).item); } } ``` Upvotes: 0 <issue_comment>username_4: You can use `UnifiedSetWithHashingStrategy` from [Eclipse Collections](https://www.eclipse.org/collections/). `UnifiedSetWithHashingStrategy` allows you to create a Set with a custom `HashingStrategy`. `HashingStrategy` allows the user to use a custom `hashCode()` and `equals()`. The Object's `hashCode()` and `equals()` is not used. **Edit based on requirement from OP via comment**: You can use `reject()` or `removeIf()` depending on your requirement. **Code Example:** ``` // Common code Person person1 = new Person("A", "A"); Person person2 = new Person("B", "B"); Person person3 = new Person("C", "A"); Person person4 = new Person("A", "D"); Person person5 = new Person("E", "E"); MutableSet personSet1 = Sets.mutable.with(person1, person2, person3); MutableSet personSet2 = Sets.mutable.with(person2, person4, person5); HashingStrategy hashingStrategy = HashingStrategies.fromFunction(Person::getLastName); ``` 1) Using `reject()`: Creates a new `Set` which contains all the elements which do *not* satisfy the `Predicate`. ``` @Test public void reject() { MutableSet personHashingStrategySet = HashingStrategySets.mutable.withAll( hashingStrategy, personSet2); // reject creates a new copy MutableSet rejectSet = personSet1.reject(personHashingStrategySet::contains); Assert.assertEquals(Sets.mutable.with(person1, person3), rejectSet); } ``` 2) Using `removeIf()`: Mutates the original `Set` by *removing* the elements which satisfy the `Predicate`. ``` @Test public void removeIfTest() { MutableSet personHashingStrategySet = HashingStrategySets.mutable.withAll( hashingStrategy, personSet2); // removeIf mutates the personSet1 personSet1.removeIf(personHashingStrategySet::contains); Assert.assertEquals(Sets.mutable.with(person1, person3), personSet1); } ``` **Answer before requirement from OP via comment:** Kept for reference if others might find it useful. 3) Using `Sets.differenceInto()` API available in Eclipse Collections: In the code below, `set1` and `set2` are the two sets which use `Person`'s `equals()` and `hashCode()`. The `differenceSet` is a `UnifiedSetWithHashingStrategy` so, it uses the `lastNameHashingStrategy` to define uniqueness. Hence, even though `set2` does not contain `person3` however it has the same lastName as `person1` the `differenceSet` contains only `person1`. ``` @Test public void differenceTest() { MutableSet differenceSet = Sets.differenceInto( HashingStrategySets.mutable.with(hashingStrategy), set1, set2); Assert.assertEquals(Sets.mutable.with(person1), differenceSet); } ``` Person class common to both code blocks: ``` public class Person { private final String firstName; private final String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Person person = (Person) o; return Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName); } @Override public int hashCode() { return Objects.hash(firstName, lastName); } } ``` **Javadocs:** [MutableSet](https://www.eclipse.org/collections/javadoc/9.1.0/org/eclipse/collections/api/set/MutableSet.html), [UnifiedSet](https://www.eclipse.org/collections/javadoc/9.1.0/org/eclipse/collections/impl/set/mutable/UnifiedSet.html), [UnifiedSetWithHashingStrategy](https://www.eclipse.org/collections/javadoc/9.1.0/org/eclipse/collections/impl/set/strategy/mutable/UnifiedSetWithHashingStrategy.html), [HashingStrategy](https://www.eclipse.org/collections/javadoc/9.1.0/org/eclipse/collections/api/block/HashingStrategy.html), [Sets](https://www.eclipse.org/collections/javadoc/9.1.0/org/eclipse/collections/impl/factory/Sets.html), [reject](https://www.eclipse.org/collections/javadoc/9.1.0/org/eclipse/collections/impl/set/mutable/UnifiedSet.html#reject-org.eclipse.collections.api.block.predicate.Predicate-), [removeIf](https://www.eclipse.org/collections/javadoc/9.1.0/org/eclipse/collections/impl/collection/mutable/AbstractMutableCollection.html#removeIf-org.eclipse.collections.api.block.predicate.Predicate-) **Note:** I am a committer on Eclipse Collections Upvotes: 3 [selected_answer]<issue_comment>username_5: pom.xml: ``` org.apache.commons commons-collections4 4.4 ``` code/test: ``` package com.my; import lombok.Builder; import lombok.Getter; import lombok.ToString; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.Equator; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.function.Function; public class Diff { public static class FieldEquator implements Equator { private final Function[] functions; @SafeVarargs public FieldEquator(Function... functions) { if (Objects.isNull(functions) || functions.length < 1) { throw new UnsupportedOperationException(); } this.functions = functions; } @Override public boolean equate(T o1, T o2) { if (Objects.isNull(o1) && Objects.isNull(o2)) { return true; } if (Objects.isNull(o1) || Objects.isNull(o2)) { return false; } for (Function function : functions) { if (!Objects.equals(function.apply(o1), function.apply(o2))) { return false; } } return true; } @Override public int hash(T o) { if (Objects.isNull(o)) { return -1; } int i = 0; Object[] vals = new Object[functions.length]; for (Function function : functions) { vals[i] = function.apply(o); i++; } return Objects.hash(vals); } } @SafeVarargs private static Set difference(Collection a, Collection b, Function... functions) { if ((Objects.isNull(a) || a.isEmpty()) && Objects.nonNull(b) && !b.isEmpty()) { return new HashSet<>(b); } else if ((Objects.isNull(b) || b.isEmpty()) && Objects.nonNull(a) && !a.isEmpty()) { return new HashSet<>(a); } Equator eq = new FieldEquator<>(functions); Collection res = CollectionUtils.removeAll(a, b, eq); res.addAll(CollectionUtils.removeAll(b, a, eq)); return new HashSet<>(res); } /\*\* \* Test \*/ @Builder @Getter @ToString public static class A { String a; String b; String c; } public static void main(String[] args) { Setas1 = new HashSet<>(); Setas2 = new HashSet<>(); A a1 = A.builder().a("1").b("1").c("1").build(); A a2 = A.builder().a("1").b("1").c("2").build(); A a3 = A.builder().a("2").b("1").c("1").build(); A a4 = A.builder().a("1").b("3").c("1").build(); A a5 = A.builder().a("1").b("1").c("1").build(); A a6 = A.builder().a("1").b("1").c("2").build(); A a7 = A.builder().a("1").b("1").c("6").build(); as1.add(a1); as1.add(a2); as1.add(a3); as2.add(a4); as2.add(a5); as2.add(a6); as2.add(a7); System.out.println("Set1: " + as1); System.out.println("Set2: " + as2); // Check A::getA, A::getB ignore A::getC Collectiondifference = difference(as1, as2, A::getA, A::getB); System.out.println("Diff: " + difference); } } ``` result: ``` Set1: [Diff.A(a=2, b=1, c=1), Diff.A(a=1, b=1, c=1), Diff.A(a=1, b=1, c=2)] Set2: [Diff.A(a=1, b=1, c=6), Diff.A(a=1, b=1, c=2), Diff.A(a=1, b=3, c=1), Diff.A(a=1, b=1, c=1)] Diff: [Diff.A(a=1, b=3, c=1), Diff.A(a=2, b=1, c=1)] ``` Upvotes: 0
2018/03/16
1,262
4,858
<issue_start>username_0: I m making a small web/application to exercise what I m learning from Spring boot and ajax. I have a web page where I have a form that have two date inputs 'start date' and 'end date' I wanted to send the user input to a RestController and to get a response that I should show in a empty div here is what I have done till now My Form : ``` Resrvation de salle =================== [[#{homePage.envoyer}]] ``` Now I will show you my ajax script ``` $(document).ready(function () { //alert("is loading"); $("#searchSalle").submit(function (event) { //stop submit the form, we will post it manually. event.preventDefault(); fire_serach_salle(); }); $("#send_mail").submit(function (event) { //stop submit the form, we will post it manually. event.preventDefault(); fire_send_mail(); }); }); function fire_serach_salle(){ var searchReserv = {}; searchReserv["dateDebutAnnee"] = $("#dateDebut").val().split('-')[0]; searchReserv["dateDebutMois"] = $("#dateDebut").val().split('-')[1]; searchReserv["dateDebutJour"] = $("#dateDebut").val().split('-')[2]; searchReserv["dateFinAnnee"] = $("#dateFin").val().split('-')[0]; searchReserv["dateFinMois"] = $("#dateFin").val().split('-')[1]; searchReserv["dateFinJour"] = $("#dateFin").val().split('-')[2]; $("#searchSalle").prop("disabled",true); console.log(searchReserv); $.ajax({ type: "POST", contentType: "application/json", url: "/homePage/reservation/search", data: JSON.stringify(searchReserv), dataType: 'json', cache: false, timeout: 900000, success: function (result) { if (result.answer === "DONE") { /**/ var html ='<h2>Liste des salles </h2>'; html+='<ul class="w3-ul w3-hoverable">'; for(var i = 0 ;i<result.data.length;i++){ html += ' <li class="w3-display-container ">'+result.data[i].titre+'-'+result.data[i].id+'<span onclick="reserve('+result.data[i].id+')" class="w3-button w3-transparent w3-display-right w3-hover-green">reserver</span></li>'; } html+='</ul>'; /**/ $("#salleList").html(html); $("#searchSalle").prop("disabled",false); } } }); } ``` now I will show my controller ``` @RestController @PropertySource(ignoreResourceNotFound = true, value = "classpath:messages.properties") public class HomePageController { @RequestMapping(value = "/homePage/reservation/search", method = RequestMethod.POST) public @ResponseBody AjaxResponse doSearch(@RequestBody SearchReserv searchReserv, Model model) { try { System.out.println(searchReserv); ArrayList response = new ArrayList<>(); response.add(new ReservationSearchResponse(Long.valueOf(0), "hello 0")); response.add(new ReservationSearchResponse(Long.valueOf(1), "hello 1")); return new AjaxResponse("DONE", response); } catch (Exception e) { e.printStackTrace(); return new AjaxResponse("BAD", null); } } ``` Finally my two classes AjaxResponse and SearcheReserv ``` public class AjaxResponse { private String answer; private Object data; //geters setters and contructors } import org.springframework.stereotype.Component; /** * * @author taleb */ @Component public class SearchReserv { private int dateDebutAnnee; private int dateDebutMois; private int dateDebutJour; private int dateFinAnnee; private int dateFinMois; private int dateFinJour; //geters setters and contructors } ``` What I can't understand that I m using this way to implement a send mail using spring mail and it working fine but in this one I still getting > > There was an unexpected error (type=Method Not Allowed, status=405). > Request method 'GET' not supported > > > there is no GET in my code I m using latest Spring Boot 2.0.0.M7 I have no configuration handmade on the apache server<issue_comment>username_1: Try using annotation **@RequestMapping(method=GET)** and share the result after that. It should resolve this issue. Upvotes: 1 <issue_comment>username_2: After hours of hard the issue was stupid, When attaching Ajax request we do it to the form Id not the Button I fixed this by updating my ajax script from ``` $("#searchSalle").submit(function (event) ``` to ``` $("#reserver_salle_form").submit(function (event) ``` and it is working like a charm Upvotes: 1 [selected_answer]
2018/03/16
627
2,606
<issue_start>username_0: I have a straightforward XPage that lets a user answer a question with a simple Yes/No/NA response using radio buttons. I have restyled the radio buttons to look like a bootstrap button group to make it visually more interesting for the user. If the user chooses "Fail" then they are informed that they need to do something else - easily done with a simple partial refresh to a div further down the page. This all works fine. The problem I'm having is that I'd like it so that when the user selects an option, I would like to add a new class of "active" to the selected option so that it highlights in a pretty colour. But for the life of me I can't get this to work and though I'm sure it's a straight forward problem, I can no longer see the wood for the trees. My current (abridged) iteration of the radio button code is this: ``` XSP.partialRefreshPost('#{id:edit-result}'); ``` This was attempting to do a chained partial refresh on the radio button container so that the EL would evaluate and apply/remove the 'active' style based on the document datasource ('item') value. I have also tried using dojo.addClass, dojo.removeClass, XSP.partialRefreshGet and other options. I don't mind what the solution is as long as it's efficient and works. I'd prefer not to move the actionAlert panel to within the same container as the radio buttons and I can't do a full page refresh because there are other fields which will lose their values. Some notes: * I'm not using a RadioGroup control because it outputs a table and I haven't got around to writing my own renderer for it yet. Single Radio button controls work fine for what I need them to do. * I originally tried using the full Bootstrap solution of using "data-toggle='buttons'" ([source](https://getbootstrap.com/docs/3.3/javascript/#buttons)) which sorts out applying the "active" style fine but then, inevitably, prevents the partial refresh from working. * the radio button styles are clearly not Bootstrap standard Any assistance pointers or, preferably, working solutions would be appreciated.<issue_comment>username_1: Try using annotation **@RequestMapping(method=GET)** and share the result after that. It should resolve this issue. Upvotes: 1 <issue_comment>username_2: After hours of hard the issue was stupid, When attaching Ajax request we do it to the form Id not the Button I fixed this by updating my ajax script from ``` $("#searchSalle").submit(function (event) ``` to ``` $("#reserver_salle_form").submit(function (event) ``` and it is working like a charm Upvotes: 1 [selected_answer]
2018/03/16
527
2,007
<issue_start>username_0: I am trying to use `react-dates` with `redux-form`. Did a `render` thing for it. I have handled `text` `input` and `select` fields pretty much the same way. Those are working fine. Getting a funky error on either `DateRangePicker` or even `SingleDatePicker`, which I cannot make sense of. Any ideas/suggestions are greatly appreciated. Did a render component as: ``` const renderDateRangePicker = ({ input, focusedInput, onFocusChange, startDatePlaceholderText, endDatePlaceholderText }) => ( input.onChange(start, end)} onFocusChange={onFocusChange} startDatePlaceholderText={startDatePlaceholderText} endDatePlaceholderText={endDatePlaceholderText} focusedInput={focusedInput} startDate={(input.value && input.value.startDate) || null} startDateId="startDateId" endDateId="endDateId" endDate={(input.value && input.value.endDate) || null} minimumNights={0} /> ) ``` My class is just a form as: ``` class ActivityForm extends Component { // values: ['startDate', 'endDate'] state = { focusedInput: null } onFocusChange(focusedInput) { this.setState({ focusedInput }); } render () { const { focusedInput } = this.state const { handleSubmit, teams } = this.props return ( Save ) } } export default reduxForm({ form: 'activity' })(ActivityForm) ``` For some reason, DateRangePicker causes a strange error: `Uncaught TypeError: Cannot read property 'createLTR' of undefined`. What am I missing?<issue_comment>username_1: Try using annotation **@RequestMapping(method=GET)** and share the result after that. It should resolve this issue. Upvotes: 1 <issue_comment>username_2: After hours of hard the issue was stupid, When attaching Ajax request we do it to the form Id not the Button I fixed this by updating my ajax script from ``` $("#searchSalle").submit(function (event) ``` to ``` $("#reserver_salle_form").submit(function (event) ``` and it is working like a charm Upvotes: 1 [selected_answer]
2018/03/16
628
2,389
<issue_start>username_0: My Json is ``` { Id: 1, Name:'Alex', ConnectedObjectName:'Obj', ConnectedObjectId: 99 } ``` I want this JSON to be converted to the following object ``` Class Response { int Id, string Name, ConnectedObject Obj } Class ConnectedObject { string COName, int COId } ``` Is there a way to achieve this using DataContractJsonSerializer<issue_comment>username_1: Most serializers want the object and the data to share a layout - so most json serializers would want `ConnectedObjectName` and `ConnectedObjectId` to exist on the root object, not an inner object. Usually, if the data isn't a good "fit" for what you want to map it into, the best approach is to use a separate DTO model that matches the data and the serializer, then map from the DTO model to the *actual* model you want programatically, or using a tool like auto-mapper. If you used the DTO approach, *just about any* JSON deserializer would be fine here. `Json.NET` is a good default. DataContractJsonSerializer would be *way way* down on my list of JSONserializers to consider. Upvotes: 3 <issue_comment>username_2: To expand on what username_1 has said, most JSON serializers would expect your JSON to look like the following, which would map correctly to your classes: ``` { "Id": 1, "Name": "Alex", "Obj" : { "COName": "Obj", "COId": 99 } } ``` The way to get around this would be to read your JSON into an object that matches it, and then map it form that object to the object that you want: Deserialize to this object: ``` class COJson { public int Id; public string Name; public string ConnectedObjectName; public int ConnectedObjectId; } ``` Then map to this object: ``` class Response { public int Id; public string Name; public ConnectedObject Obj; } class ConnectedObject { public string COName; public string COId; } ``` Like this: ``` using(var stream = new MemoryStream(Encoding.Unicode.GetBytes(json))) { var serializer = new DataContractJsonSerializer(typeof(COJson)); var jsonDto = (COJson)ser.ReadObject(stream); var dto = new Response(){ Id = jsonDto.Id, Name = jsonDto.Name, Obj = new ConnectedObject(){ COName = jsonDto.ConnectedObjectName, COId = jsonDto.ConnectedObjectId } }; return dto; } ``` Upvotes: 0
2018/03/16
235
788
<issue_start>username_0: RecyclerView 27.1.0 and android.arch.paging 1.0.0-alpha4-1 both contains android/support/v7/recyclerview/extensions/ListAdapter.class Does any body know how to exclude ListAdapter.class from paging component?<issue_comment>username_1: I think you can do it like this ``` implementation("your dependency"){ exclude group:'com.android.support' module:'recyclerview-v7' } ``` Upvotes: 0 <issue_comment>username_2: Per the [Architecture Components Release Notes](https://developer.android.com/topic/libraries/architecture/release-notes.html#february_27_2018), you must upgrade to Paging 1.0.0-alpha6 to use Support Library 27.1.0: > > apps using Paging must upgrade to Alpha 6, and Support Library 27.1.0 at the same time > > > Upvotes: 3 [selected_answer]
2018/03/16
1,586
3,296
<issue_start>username_0: I am having an error printing the ouput of a summary function to a file. I have a column "bin" with three factor levels and want to return 5 number summary for each level. The five number summary prints to the screen but won't write to file? Error reports I have > > Empty data.table (0 rows) of 1 col: bin > > > Data: ``` A B info C bin 1: 10-60494 0.66392100 0.001833330 1 MAF0.01 2: rs148087467 0.35274000 0.000716240 1 MAF0.01 3: rs187110906 0.40586900 0.004488040 1 MAF0.01 4: rs192025213 0.00743299 0.000000000 1 MAF0.01 5: rs115033199 0.32829300 0.000614316 1 MAF0.01 6: rs183305313 0.51721200 0.002892520 1 MAF0.01 s <- df2[, print(summary(info)), by='bin'] print(s) write.table(as.data.frame(s), quote=FALSE,file=paste(i,"sum_out.txt",sep='')) ``` Ouput: ``` Min. 1st Qu. Median Mean 3rd Qu. Max. 0.0009998 0.0371300 0.2016000 0.2700000 0.4477000 1.0000000 ```<issue_comment>username_1: The reason you are getting zero rows is because the only thing you do in `j` is print the outcome of the `summary` command. Considering the following example data: ``` set.seed(2018) dt <- data.table(bin = rep(c('A','B'), 5), val = rnorm(10,3,1)) ``` Now when you do (like in your question): ``` s <- dt[, print(summary(val)), by = bin] ``` the summary statistics are printed to the console but it results in an empty *data.table*: > > > ``` > > s <- dt[, print(summary(val)), by = bin] > Min. 1st Qu. Median Mean 3rd Qu. Max. > 2.389 2.577 2.936 3.547 4.735 5.099 > Min. 1st Qu. Median Mean 3rd Qu. Max. > 1.450 2.735 3.271 2.991 3.637 3.863 > > s > Empty data.table (0 rows) of 1 col: bin > > ``` > > Removing the `print`-command doesn't help: > > > ``` > > dt[, summary(val), by = bin] > bin V1 > 1: A 2.389 > 2: A 2.577 > 3: A 2.936 > 4: A 3.547 > 5: A 4.735 > 6: A 5.099 > 7: B 1.450 > 8: B 2.735 > 9: B 3.271 > 10: B 2.991 > 11: B 3.637 > 12: B 3.863 > > ``` > > because `summary` returns a table-object which is treated a vector by `data.table`. Instead of using `print`, you should use `as.list` to get the elements of `summary` as columns in a *data.table*: ``` s <- dt[, as.list(summary(val)), by = bin] ``` now the summary statistics are included in the resulting *data.table*: > > > ``` > > s > bin Min. 1st Qu. Median Mean 3rd Qu. Max. > 1: A 2.389413 2.577016 2.935571 3.547351 4.735284 5.099471 > 2: B 1.450122 2.735289 3.270881 2.991340 3.637056 3.863351 > > ``` > > Because the summary statistics are stored in the non-empty *data.table* `s`, you can write `s` to a file with for example `fwrite` (the fast write function the`data.table`-package). Upvotes: 3 [selected_answer]<issue_comment>username_2: This can be achieved using `sapply()` - here is an example using the iris data frame: ``` levels <- unique(iris$Species) result <- data.frame(t(sapply(levels, function (x) summary(subset(iris, Species == levels[x])$Petal.Width)))) > result Min. X1st.Qu. Median Mean X3rd.Qu. Max. 1 0.1 0.2 0.2 0.246 0.3 0.6 2 1.0 1.2 1.3 1.326 1.5 1.8 3 1.4 1.8 2.0 2.026 2.3 2.5 ``` Upvotes: 0
2018/03/16
286
1,111
<issue_start>username_0: I'm trying to use the Datastore Admin API v1 that was recently announced GA and wanted to wonder where can I find protobufs for the related API? I have found some protobufs within the [googleapis](https://github.com/googleapis/googleapis/tree/master/google/datastore) repository, but there are only protobufs for the Datastore Admin API v1beta1 that is already deprecated. Moreover, I wanted to ask if anyone knows why Admin API protos are not published in Maven Central? The general Datastore API protos [are](https://mvnrepository.com/artifact/com.google.api.grpc/proto-google-cloud-datastore-v1).<issue_comment>username_1: Oops. In the meantime, you can take that existing proto and change one line: From: `package google.datastore.admin.v1beta1;` To: `package google.datastore.admin.v1;` Upvotes: 2 <issue_comment>username_2: Looks like protobuf definitions for the Admin API are now available through the [googleapis](https://github.com/googleapis/googleapis/tree/master/google/datastore/admin/v1) repository. But they are not yet published to the Maven Central. Upvotes: 0
2018/03/16
423
1,332
<issue_start>username_0: **UPDATED** I create some SCNTubes with following materials: ``` let radius: CGFloat = 0.3 let height: CGFloat = 0.5 let color: UIColor = UIColor(red:0.17, green:0.62, blue:0.76, alpha:1.0) let geometryTube = SCNTube(innerRadius: (radius - 0.1), outerRadius: radius, height: height) let matOuter = SCNMaterial() matOuter.diffuse.contents = color matOuter.transparency = 0.1 let matInner = SCNMaterial() matInner.diffuse.contents = color matInner.transparency = 0.6 let matTop = SCNMaterial() matTop.diffuse.contents = color geometryTube.materials = [matOuter, matInner, matTop] for index in 0...20 { let node = SCNNode(geometry: geometryTube) node.position = SCNVector3(1.0 + Double(index), -1.0, 0.0); sceneView.scene.rootNode.addChildNode(node) } ``` Depending on the angle the tubes are flickering.<issue_comment>username_1: Oops. In the meantime, you can take that existing proto and change one line: From: `package google.datastore.admin.v1beta1;` To: `package google.datastore.admin.v1;` Upvotes: 2 <issue_comment>username_2: Looks like protobuf definitions for the Admin API are now available through the [googleapis](https://github.com/googleapis/googleapis/tree/master/google/datastore/admin/v1) repository. But they are not yet published to the Maven Central. Upvotes: 0
2018/03/16
323
1,206
<issue_start>username_0: I'm making a game. On the main menu I have a button for "Start Game" "High Scores" "Options" "Store". I have various scenes for the different levels. Each of those scenes has a "pause button" which takes you to the "Options" scene. The Options scene has a "BACK" button. How do I get that "BACK" button to return to what have scene called it? Right now the "BACK" button only has the ability to return to the menu ie SceneSkip in my code, regardless of what scene called it: ``` func back(){ let sceneSkip = SceneSkip(fileNamed: "SceneSkip") sceneSkip?.scaleMode = .aspectFill self.view?.presentScene(sceneSkip!, transition: SKTransition.fade(withDuration: 0.5)) } ```<issue_comment>username_1: Oops. In the meantime, you can take that existing proto and change one line: From: `package google.datastore.admin.v1beta1;` To: `package google.datastore.admin.v1;` Upvotes: 2 <issue_comment>username_2: Looks like protobuf definitions for the Admin API are now available through the [googleapis](https://github.com/googleapis/googleapis/tree/master/google/datastore/admin/v1) repository. But they are not yet published to the Maven Central. Upvotes: 0
2018/03/16
636
2,347
<issue_start>username_0: I am a newbie using AWS sdk for video transfer.But i am getting the error "Failed to read S3TransferUtility please check your setup or awsconfiguration.json file". Here is my code. In my manifest file i have ``` ``` In my oncreate i am doing this. ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_upload_post); AWSMobileClient.getInstance().initialize(this).execute(); transferUtility = TransferUtility.builder() .context(this) .awsConfiguration(AWSMobileClient.getInstance().getConfiguration()) .s3Client(new AmazonS3Client(AWSMobileClient.getInstance().getCredentialsProvider())) .build(); } ``` The exception comes at .build. I debugged the code and it picks up the config file located at in folder perfectly cause i can see the data in debug but i think the transferutility.TransferService is not running. Can someone please help. Thanx<issue_comment>username_1: Add awsconfiguration.json on your project and change pool id and region attributes. You can read more about it [here](https://docs.aws.amazon.com/aws-mobile/latest/developerguide/how-to-cognito-integrate-an-existing-identity-pool.html#create-the-awsconfiguration-json-file). Upvotes: 3 <issue_comment>username_2: For some reason the auto generated "awsconfiguration" file doesn't include the most important section called "**S3TransferUtility**". So you have to add it manually. Your "awsconfiguration.json" file should look something like this: ``` { "UserAgent": "MobileHub/1.0", "Version": "1.0", "CredentialsProvider": { "CognitoIdentity": { "Default": { "PoolId": "us-east-1:", "Region": "us-east-1" } } }, "IdentityManager": { "Default": {} }, "PinpointAnalytics": { "Default": { "AppId": "", "Region": "us-east-1" } }, "PinpointTargeting": { "Default": { "Region": "us-east-1" } }, "S3TransferUtility": { "Default": { "Bucket": "", "Region": "us-east-1" } } } ``` Upvotes: 3 <issue_comment>username_3: In my **awsconfiguration.json** i add below lines then it's started working ``` "S3TransferUtility": { "Default": { "Bucket": "", "Region": "us-east-1" } } ``` Upvotes: 3
2018/03/16
677
2,479
<issue_start>username_0: I can't understand why I have a compilation error for this code: ``` private static Consumer f3() { return t -> {}; } private static Consumer super T f4() { return t -> {}; } @Test public void test() { Consumer action3 = f3(); Consumer action4 = f4(); // ERROR } ``` the error from javac 1.8.0\_161: > > Error:(84, 36) java: incompatible types: no instance(s) of type variable(s) `T` exist so that `java.util.function.Consumer super T` conforms to `java.util.function.Consumer` > > > Can anyone explain this error? Thanks. **EDIT** I tried to simplify my example, and I did an error by making it too simple. What I'm interested is an explanation for this error which is output by IntelliJ: ``` private static BiConsumer f1(Consumer super Throwable consumer) { return null; } private static BiConsumer super T, ? super Throwable f2(Consumer super Throwable consumer) { return null; } @Test public void test() { BiConsumer super Integer, ? super Throwable action1 = f1(throwable -> { }); BiConsumer super Integer, ? super Throwable action2 = f2(throwable -> { }); // ERROR HERE } ``` IntelliJ considers this an error because "inference variable T has incompatible bounds: equality constraints: T lower bounds: Integer". But when compiling it, it's fine, no error. Is this an actually valid Java code and just a bug in IntelliJ? Thanks.<issue_comment>username_1: A `Consumer super Something` isn't a `Consumer`. The compiler doesn't know that there are no producer methods on the `Consumer` class, so it stops you potentially using it as a producer. As far as the type inference rules are concerned, there is no difference between `Consumer` and `List`, for example. So the same rule which stops you writing the following also stops you in what you are doing: ``` List super Integer c = Arrays.asList(""); List d = c; // Compiler error; let's pretend it works. Integer i = d.get(0); // ClassCastException! ``` Upvotes: 3 <issue_comment>username_1: An answer for your edit: I suspect this is a bug in intellij. If I remove the variable declaration, and then select the expression and press `Ctrl`+`Alt`+`V` to extract a variable, it picks the following type: ``` BiConsumer super Object, ? super Throwable biConsumer = f2(throwable -> {}); ``` which, despite just having picked itself, it highlights the lambda as an error. Upvotes: 1 <issue_comment>username_2: Please try File->Invalidate Caches and restart. Upvotes: 0
2018/03/16
918
2,414
<issue_start>username_0: Lets say I have a list with three arrays as following: `[(1,2,0),(2,9,6),(2,3,6)]` Is it possible I get the average by diving each "slot" of the arrays in the list. For example: `(1+2+2)/3, (2+0+9)/3, (0+6+6)/3` and make it become new arraylist with only 3 integers.<issue_comment>username_1: Here are couple of ways you can do it. ``` data = [(1,2,0),(2,9,6),(2,3,6)] avg_array = [] for tu in data: avg_array.append(sum(tu)/len(tu)) print(avg_array) ``` using list comprehension ``` data = [(1,2,0),(2,9,6),(2,3,6)] comp = [ sum(i)/len(i) for i in data] print(comp) ``` Upvotes: 0 <issue_comment>username_2: Can be achieved by doing something like this. Create an empty array. Loop through your current array and use the sum and len functions to calculate averages. Then append the average to your new array. ``` array = [(1,2,0),(2,9,6),(2,3,6)] arraynew = [] for i in range(0,len(array)): arraynew.append(sum(array[i]) / len(array[i])) print arraynew ``` Upvotes: 0 <issue_comment>username_3: As you were told in the comments with `sum` and `len` it's pretty easy. But in python I would do something like this, assuming you want to maintain decimal precision: ``` list = [(1, 2, 0), (2, 9, 6), (2, 3, 6)] res = map(lambda l: round(float(sum(l)) / len(l), 2), list) ``` Output: ``` [1.0, 5.67, 3.67] ``` But as you said you wanted 3 `int`s in your question, would be like this: ``` res = map(lambda l: sum(l) / len(l), list) ``` Output: ``` [1, 5, 3] ``` Edit: To sum the same index of each tuple, the most elegant method is the solution provided by @PatrickHaugh. On the other hand, if you are not fond of list comprehensions and some built in functions as `zip` is, here's a little longer and less elegant version using a `for` loop: ``` arr = [] for i in range(0, len(list)): arr.append(sum(l[i] for l in list) / len(list)) print(arr) ``` Output: ``` [1, 4, 4] ``` Upvotes: 0 <issue_comment>username_4: You can use [`zip`](https://docs.python.org/3/library/functions.html#zip) to associate all of the elements in each of the interior tuples by index ``` tups = [(1,2,0),(2,9,6),(2,3,6)] print([sum(x)/len(x) for x in zip(*tups)]) # [1.6666666666666667, 4.666666666666667, 4.0] ``` You can also do something like `sum(x)//len(x)` or `round(sum(x)/len(x))` inside the list comprehension to get an integer. Upvotes: 3 [selected_answer]
2018/03/16
7,625
23,834
<issue_start>username_0: I am trying to build Milo to run the standalone examples. From the project root I run `mvn clean install` but maven complaints about all `org.opcfoundation.*` dependencies both in `bsd-parser-core` and `bsd-parser-gson`. Error message: ``` [INFO] 45 errors [INFO] ------------------------------------------------------------- [INFO] ------------------------------------------------------------------------ [INFO] Reactor Summary: [INFO] [INFO] Eclipse Milo Build Tools ........................... SUCCESS [ 1.134 s] [INFO] Eclipse Milo - OPC-UA (IEC 62541) .................. SUCCESS [ 1.420 s] [INFO] opc-ua-stack ....................................... SUCCESS [ 1.026 s] [INFO] stack-core ......................................... SUCCESS [ 13.145 s] [INFO] stack-client ....................................... SUCCESS [ 1.195 s] [INFO] opc-ua-sdk ......................................... SUCCESS [ 0.985 s] [INFO] sdk-core ........................................... SUCCESS [ 1.842 s] [INFO] bsd-parser ......................................... SUCCESS [ 0.240 s] [INFO] bsd-parser-core .................................... FAILURE [ 1.274 s] [INFO] sdk-client ......................................... SKIPPED [INFO] stack-server ....................................... SKIPPED [INFO] sdk-server ......................................... SKIPPED [INFO] milo-examples ...................................... SKIPPED [INFO] server-examples .................................... SKIPPED [INFO] client-examples .................................... SKIPPED [INFO] standalone-examples ................................ SKIPPED [INFO] bsd-parser-gson .................................... SKIPPED [INFO] stack-examples ..................................... SKIPPED [INFO] stack-tests ........................................ SKIPPED [INFO] sdk-tests .......................................... SKIPPED [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 22.517 s [INFO] Finished at: 2018-03-16T15:16:34+00:00 [INFO] Final Memory: 43M/575M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.5.1:compile (java-compile) on project bsd-parser-core: Compilation failure: Compilation failure: [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[50,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[51,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[52,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[169,19] cannot find symbol [ERROR] symbol: class StructuredType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[171,29] cannot find symbol [ERROR] symbol: class StructuredType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[352,29] cannot find symbol [ERROR] symbol: class FieldType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[374,36] cannot find symbol [ERROR] symbol: class FieldType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[398,68] cannot find symbol [ERROR] symbol: class SwitchOperand [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[419,42] cannot find symbol [ERROR] symbol: class FieldType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/GenericStructCodec.java:[23,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/GenericStructCodec.java:[27,31] cannot find symbol [ERROR] symbol: class StructuredType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.GenericStructCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/GenericEnumCodec.java:[21,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/GenericEnumCodec.java:[25,19] cannot find symbol [ERROR] symbol: class EnumeratedType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.GenericEnumCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/GenericEnumCodec.java:[27,29] cannot find symbol [ERROR] symbol: class EnumeratedType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.GenericEnumCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[22,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[23,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[24,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[25,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[78,65] cannot find symbol [ERROR] symbol: class EnumeratedType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.parser.BsdParser [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[86,67] cannot find symbol [ERROR] symbol: class StructuredType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.parser.BsdParser [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/GenericBsdParser.java:[18,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/GenericBsdParser.java:[19,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/GenericBsdParser.java:[24,56] cannot find symbol [ERROR] symbol: class EnumeratedType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.GenericBsdParser [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/GenericBsdParser.java:[29,58] cannot find symbol [ERROR] symbol: class StructuredType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.GenericBsdParser [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[182,25] cannot find symbol [ERROR] symbol: class FieldType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[186,13] cannot find symbol [ERROR] symbol: class FieldType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[259,25] cannot find symbol [ERROR] symbol: class FieldType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[263,13] cannot find symbol [ERROR] symbol: class FieldType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[391,13] cannot find symbol [ERROR] symbol: class SwitchOperand [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[392,44] cannot find symbol [ERROR] symbol: variable SwitchOperand [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[400,18] cannot find symbol [ERROR] symbol: variable EQUALS [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[402,18] cannot find symbol [ERROR] symbol: variable NOT\_EQUAL [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[404,18] cannot find symbol [ERROR] symbol: variable GREATER\_THAN [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[406,18] cannot find symbol [ERROR] symbol: variable GREATER\_THAN\_OR\_EQUAL [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[408,18] cannot find symbol [ERROR] symbol: variable LESS\_THAN [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[410,18] cannot find symbol [ERROR] symbol: variable LESS\_THAN\_OR\_EQUAL [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[43,55] cannot find symbol [ERROR] symbol: class ObjectFactory [ERROR] location: class org.eclipse.milo.opcua.binaryschema.parser.BsdParser [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[45,9] cannot find symbol [ERROR] symbol: class TypeDictionary [ERROR] location: class org.eclipse.milo.opcua.binaryschema.parser.BsdParser [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[45,42] cannot find symbol [ERROR] symbol: class TypeDictionary [ERROR] location: class org.eclipse.milo.opcua.binaryschema.parser.BsdParser [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[48,67] cannot find symbol [ERROR] symbol: class EnumeratedType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.parser.BsdParser [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[50,17] cannot find symbol [ERROR] symbol: class EnumeratedType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.parser.BsdParser [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[50,50] cannot find symbol [ERROR] symbol: class EnumeratedType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.parser.BsdParser [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[59,67] cannot find symbol [ERROR] symbol: class StructuredType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.parser.BsdParser [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[61,17] cannot find symbol [ERROR] symbol: class StructuredType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.parser.BsdParser [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/parser/BsdParser.java:[61,50] cannot find symbol [ERROR] symbol: class StructuredType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.parser.BsdParser ``` Do I need to fetch something from additional repositories? I am using Maven 3.3.9 and Java JDK version: 1.8.0\_111, from Oracle Corporation. EDIT 1 After execute `git pull` the project built run nicely, as show below: ``` Results : Tests run: 12, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] --- maven-failsafe-plugin:2.19.1:verify (default) @ sdk-tests --- [INFO] [INFO] --- maven-install-plugin:2.4:install (default-install) @ sdk-tests --- [INFO] Installing D:\PRODUTECH\Workspace\milo\opc-ua-sdk\sdk-tests\target\sdk-tests-0.2.2-SNAPSHOT.jar to C:\Users\User\.m2\repository\org\eclipse\milo\sdk-tests\0.2.2-SNAPSHOT\sdk-tests-0.2.2-SNAPSHOT.jar [INFO] Installing D:\PRODUTECH\Workspace\milo\opc-ua-sdk\sdk-tests\pom.xml to C:\Users\User\.m2\repository\org\eclipse\milo\sdk-tests\0.2.2-SNAPSHOT\sdk-tests-0.2.2-SNAPSHOT.pom [INFO] ------------------------------------------------------------------------ [INFO] Reactor Summary: [INFO] [INFO] Eclipse Milo Build Tools ........................... SUCCESS [ 1.207 s] [INFO] Eclipse Milo - OPC-UA (IEC 62541) .................. SUCCESS [ 1.337 s] [INFO] opc-ua-stack ....................................... SUCCESS [ 1.146 s] [INFO] stack-core ......................................... SUCCESS [ 19.878 s] [INFO] stack-client ....................................... SUCCESS [ 1.471 s] [INFO] opc-ua-sdk ......................................... SUCCESS [ 1.037 s] [INFO] sdk-core ........................................... SUCCESS [ 2.381 s] [INFO] bsd-parser ......................................... SUCCESS [ 0.227 s] [INFO] bsd-parser-core .................................... SUCCESS [ 3.927 s] [INFO] sdk-client ......................................... SUCCESS [ 8.032 s] [INFO] stack-server ....................................... SUCCESS [ 1.538 s] [INFO] sdk-server ......................................... SUCCESS [ 13.693 s] [INFO] milo-examples ...................................... SUCCESS [ 0.203 s] [INFO] server-examples .................................... SUCCESS [ 3.474 s] [INFO] client-examples .................................... SUCCESS [ 1.059 s] [INFO] standalone-examples ................................ SUCCESS [ 0.756 s] [INFO] bsd-parser-gson .................................... SUCCESS [ 2.253 s] [INFO] stack-examples ..................................... SUCCESS [ 1.168 s] [INFO] stack-tests ........................................ SUCCESS [01:40 min] [INFO] sdk-tests .......................................... SUCCESS [ 20.385 s] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 03:06 min [INFO] Finished at: 2018-03-20T15:03:53+00:00 [INFO] Final Memory: 88M/2061M [INFO] ------------------------------------------------------------------------ ``` However, when I try to build the standalone examples, running `mvn package -P standalone` from the project root, the previous error shows up again, as shown below: ``` [INFO] 45 errors [INFO] ------------------------------------------------------------- [INFO] ------------------------------------------------------------------------ [INFO] Reactor Summary: [INFO] [INFO] Eclipse Milo Build Tools ........................... SUCCESS [ 1.034 s] [INFO] Eclipse Milo - OPC-UA (IEC 62541) .................. SUCCESS [ 1.414 s] [INFO] opc-ua-stack ....................................... SUCCESS [ 0.948 s] [INFO] stack-core ......................................... SUCCESS [ 14.015 s] [INFO] stack-client ....................................... SUCCESS [ 0.972 s] [INFO] opc-ua-sdk ......................................... SUCCESS [ 0.935 s] [INFO] sdk-core ........................................... SUCCESS [ 1.679 s] [INFO] bsd-parser ......................................... SUCCESS [ 0.187 s] [INFO] bsd-parser-core .................................... FAILURE [ 1.222 s] [INFO] sdk-client ......................................... SKIPPED [INFO] stack-server ....................................... SKIPPED [INFO] sdk-server ......................................... SKIPPED [INFO] milo-examples ...................................... SKIPPED [INFO] server-examples .................................... SKIPPED [INFO] client-examples .................................... SKIPPED [INFO] standalone-examples ................................ SKIPPED [INFO] bsd-parser-gson .................................... SKIPPED [INFO] stack-examples ..................................... SKIPPED [INFO] stack-tests ........................................ SKIPPED [INFO] sdk-tests .......................................... SKIPPED [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 22.650 s [INFO] Finished at: 2018-03-20T15:06:43+00:00 [INFO] Final Memory: 44M/1294M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.5.1:compile (java-compile) on project bsd-parser-core: Compilation failure: Compilation failure: [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[50,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[51,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[52,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[169,19] cannot find symbol [ERROR] symbol: class StructuredType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[171,29] cannot find symbol [ERROR] symbol: class StructuredType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[352,29] cannot find symbol [ERROR] symbol: class FieldType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[374,36] cannot find symbol [ERROR] symbol: class FieldType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[398,68] cannot find symbol [ERROR] symbol: class SwitchOperand [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/AbstractCodec.java:[419,42] cannot find symbol [ERROR] symbol: class FieldType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.AbstractCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/GenericStructCodec.java:[23,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/GenericStructCodec.java:[27,31] cannot find symbol [ERROR] symbol: class StructuredType [ERROR] location: class org.eclipse.milo.opcua.binaryschema.GenericStructCodec [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/GenericEnumCodec.java:[21,44] package org.opcfoundation.opcua.binaryschema does not exist [ERROR] /D:/PRODUTECH/Workspace/milo/opc-ua-stack/bsd-parser/bsd-parser-core/src/main/java/org/eclipse/milo/opcua/binaryschema/GenericEnumCodec.java:[25,19] cannot find symbol ... ```<issue_comment>username_1: Have you fetched/updated recently? There were some issues with version numbers that broke the build recently: <https://github.com/eclipse/milo/issues/230> They have been fixed on HEAD Upvotes: 0 <issue_comment>username_2: The org.opcfoundation.\* sources are generated during the 'generate-sources' phase and placed in ../target/generated-sources. In Eclipse, you have to add this folder to the build-path. Open the properties dialog for bsd-parser-core, open the build path folder and add the source folder. [![build-path dialog](https://i.stack.imgur.com/xWtQe.png)](https://i.stack.imgur.com/xWtQe.png) Upvotes: 2 [selected_answer]
2018/03/16
2,527
6,867
<issue_start>username_0: I'm trying to replicate the output that jupyter uses for a pandas dataframe in their notebooks to html/css/js so that it's returnable by Flask `jsonify` as html that I later use in an AJAX call. I found [this](https://stackoverflow.com/questions/38511373/change-the-color-of-text-within-a-pandas-dataframe-html-table-python-using-style), and [this](https://stackoverflow.com/questions/36897366/pandas-to-html-using-the-style-options-or-custom-css), which suggested using the pandas builtin style functionality rather than CSS hacks but i'm struggling to get the desired functionality: ``` def hover(hover_color="#add8e6"): return dict(selector="tr:hover", props=[("background-color", "%s" % hover_color)]) styles = [ hover(), dict(selector="th", props=[("font-size", "125%"), ("text-align", "center"), ("padding", "5px 5px")]), dict(selector="tr", props=[("text-align", "center")]), dict(selector="caption", props=[("caption-side", "bottom")]) ] # creating some dummy data index = pd.MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']], labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]], names=['first', 'second']) df = pd.DataFrame(data=np.random.randn(8), index=index) # you'll see the html rendered bellow df.style.set_table_styles(styles).set_caption("test").render() ``` Compared to jupyter notebooks, this is missing some default background color stripping, and the header shouldn't apply the hover class. The only way I can think to apply something on select elements would be to add `class=` or `id=` but the style functionality hides all that. ```html #T\_479b61ba\_292a\_11e8\_86bf\_0ee09a5428a2 tr:hover { background-color: #add8e6; } #T\_479b61ba\_292a\_11e8\_86bf\_0ee09a5428a2 th { font-size: 150%; text-align: center; } #T\_479b61ba\_292a\_11e8\_86bf\_0ee09a5428a2 caption { caption-side: bottom; } Hover to highlight.| | | 0 | | --- | --- | --- | | first | second | | | bar | one | -0.0690895 | | two | -0.518092 | | baz | one | -0.163842 | | two | -0.144757 | | foo | one | 1.22865 | | two | 1.83947 | | qux | one | 0.793328 | | two | -0.723836 | ```<issue_comment>username_1: I've made a few changes to your code to get the functionality you want: * Pandas dataframes are styled with two special HTML tags for tables, namely `thead` for the header and `tbody` for the body. We can use this to specify the highlighting behavior as body-only * CSS has "even" and "odd" properties which you can use to add shading effects to tables. * In order for hover to work with the background shading specified, it must be called last not first **In Jupyter Notebook:** ``` import pandas as pd import numpy as np from IPython.display import HTML def hover(hover_color="#add8e6"): return dict(selector="tbody tr:hover", props=[("background-color", "%s" % hover_color)]) styles = [ #table properties dict(selector=" ", props=[("margin","0"), ("font-family",'"Helvetica", "Arial", sans-serif'), ("border-collapse", "collapse"), ("border","none"), ("border", "2px solid #ccf") ]), #header color - optional dict(selector="thead", props=[("background-color","#cc8484") ]), #background shading dict(selector="tbody tr:nth-child(even)", props=[("background-color", "#fff")]), dict(selector="tbody tr:nth-child(odd)", props=[("background-color", "#eee")]), #cell spacing dict(selector="td", props=[("padding", ".5em")]), #header cell properties dict(selector="th", props=[("font-size", "125%"), ("text-align", "center")]), #caption placement dict(selector="caption", props=[("caption-side", "bottom")]), #render hover last to override background-color hover() ] html = (df.style.set_table_styles(styles) .set_caption("Hover to highlight.")) html ``` [![Jupyter output](https://i.stack.imgur.com/HT1ZV.png)](https://i.stack.imgur.com/HT1ZV.png) **...but is it still beautiful when we output the HTML file??** Yes. You can do some more CSS styling to get it just right (font-size, font-family, text-decoration, margin/padding, etc) but this gives you a start. See below: ``` print(html.render()) ``` ```html #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc { margin: 0; font-family: "Helvetica", "Arial", sans-serif; border-collapse: collapse; border: none; border: 2px solid #ccf; } #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc thead { background-color: #cc8484; } #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc tbody tr:nth-child(even) { background-color: #fff; } #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc tbody tr:nth-child(odd) { background-color: #eee; } #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc td { padding: .5em; } #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc th { font-size: 125%; text-align: center; } #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc caption { caption-side: bottom; } #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc tbody tr:hover { background-color: #add8e6; } Hover to highlight.| | | 0 | | --- | --- | --- | | first | second | | | bar | one | -0.130634 | | two | 1.17685 | | baz | one | 0.500367 | | two | 0.555932 | | foo | one | -0.744553 | | two | -1.41269 | | qux | one | 0.726728 | | two | -0.683555 | ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: Definitely took me a while to look for where the template is, but here it is, [link](https://github.com/jupyter/notebook/blob/9de5042e1058dc8aef7632f313e3e86c33390d31/notebook/static/notebook/less/renderedhtml.less#L77-L109). I believe this includes all the CSS for notebook cell outputs, so you just need the table related parts (table, thead, tbody, th, etc) and tweak them to your liking. You still need to turn it in python, but to illustrate it works, here's the raw HTML ```html table { border: none; border-collapse: collapse; border-spacing: 0; color: black; font-size: 12px; table-layout: fixed; } thead { border-bottom: 1px solid black; vertical-align: bottom; } tr, th, td { text-align: right; vertical-align: middle; padding: 0.5em 0.5em; line-height: normal; white-space: normal; max-width: none; border: none; } th { font-weight: bold; } tbody tr:nth-child(odd) { background: #f5f5f5; } tbody tr:hover { background: rgba(66, 165, 245, 0.2); } | | | 0 | | --- | --- | --- | | first | second | | | bar | one | -0.466253 | | two | -0.579658 | | baz | one | 1.868159 | | two | 0.392282 | | foo | one | -2.427858 | | two | -0.813941 | | qux | one | 0.110564 | | two | 0.834701 | ``` Upvotes: 3
2018/03/16
1,959
5,881
<issue_start>username_0: I am using Ampps on Mac and trying to send an email using php from a contact form however I do not receive the mail and when the form is submitted it redirects me to the file page resulting in a blank display my form : ``` Your name Your email Your subject ``` my File : ``` $email = $_POST['Email']; $name = $_POST['Name']; $to = "<EMAIL>"; $subject = $_POST['Subject']; $userMessage =$_POST['Message']; $headers = "From: $email\n"; $message = "$name has sent you the following message.\n Message: $userMessage"; $user = "$email"; $usersubject = "Thank You"; $userheaders = "From: <EMAIL>\n"; $usermessage = "Thank you for your enquiry we will be in touch."; mail($to,$subject,$message,$headers); mail($user,$usersubject,$usermessage,$userheaders); ```<issue_comment>username_1: I've made a few changes to your code to get the functionality you want: * Pandas dataframes are styled with two special HTML tags for tables, namely `thead` for the header and `tbody` for the body. We can use this to specify the highlighting behavior as body-only * CSS has "even" and "odd" properties which you can use to add shading effects to tables. * In order for hover to work with the background shading specified, it must be called last not first **In Jupyter Notebook:** ``` import pandas as pd import numpy as np from IPython.display import HTML def hover(hover_color="#add8e6"): return dict(selector="tbody tr:hover", props=[("background-color", "%s" % hover_color)]) styles = [ #table properties dict(selector=" ", props=[("margin","0"), ("font-family",'"Helvetica", "Arial", sans-serif'), ("border-collapse", "collapse"), ("border","none"), ("border", "2px solid #ccf") ]), #header color - optional dict(selector="thead", props=[("background-color","#cc8484") ]), #background shading dict(selector="tbody tr:nth-child(even)", props=[("background-color", "#fff")]), dict(selector="tbody tr:nth-child(odd)", props=[("background-color", "#eee")]), #cell spacing dict(selector="td", props=[("padding", ".5em")]), #header cell properties dict(selector="th", props=[("font-size", "125%"), ("text-align", "center")]), #caption placement dict(selector="caption", props=[("caption-side", "bottom")]), #render hover last to override background-color hover() ] html = (df.style.set_table_styles(styles) .set_caption("Hover to highlight.")) html ``` [![Jupyter output](https://i.stack.imgur.com/HT1ZV.png)](https://i.stack.imgur.com/HT1ZV.png) **...but is it still beautiful when we output the HTML file??** Yes. You can do some more CSS styling to get it just right (font-size, font-family, text-decoration, margin/padding, etc) but this gives you a start. See below: ``` print(html.render()) ``` ```html #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc { margin: 0; font-family: "Helvetica", "Arial", sans-serif; border-collapse: collapse; border: none; border: 2px solid #ccf; } #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc thead { background-color: #cc8484; } #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc tbody tr:nth-child(even) { background-color: #fff; } #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc tbody tr:nth-child(odd) { background-color: #eee; } #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc td { padding: .5em; } #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc th { font-size: 125%; text-align: center; } #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc caption { caption-side: bottom; } #T\_3e73cfd2\_396c\_11e8\_9d70\_240a645b34fc tbody tr:hover { background-color: #add8e6; } Hover to highlight.| | | 0 | | --- | --- | --- | | first | second | | | bar | one | -0.130634 | | two | 1.17685 | | baz | one | 0.500367 | | two | 0.555932 | | foo | one | -0.744553 | | two | -1.41269 | | qux | one | 0.726728 | | two | -0.683555 | ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: Definitely took me a while to look for where the template is, but here it is, [link](https://github.com/jupyter/notebook/blob/9de5042e1058dc8aef7632f313e3e86c33390d31/notebook/static/notebook/less/renderedhtml.less#L77-L109). I believe this includes all the CSS for notebook cell outputs, so you just need the table related parts (table, thead, tbody, th, etc) and tweak them to your liking. You still need to turn it in python, but to illustrate it works, here's the raw HTML ```html table { border: none; border-collapse: collapse; border-spacing: 0; color: black; font-size: 12px; table-layout: fixed; } thead { border-bottom: 1px solid black; vertical-align: bottom; } tr, th, td { text-align: right; vertical-align: middle; padding: 0.5em 0.5em; line-height: normal; white-space: normal; max-width: none; border: none; } th { font-weight: bold; } tbody tr:nth-child(odd) { background: #f5f5f5; } tbody tr:hover { background: rgba(66, 165, 245, 0.2); } | | | 0 | | --- | --- | --- | | first | second | | | bar | one | -0.466253 | | two | -0.579658 | | baz | one | 1.868159 | | two | 0.392282 | | foo | one | -2.427858 | | two | -0.813941 | | qux | one | 0.110564 | | two | 0.834701 | ``` Upvotes: 3
2018/03/16
3,234
8,685
<issue_start>username_0: I'm trying to to parse some text from a website using jsoup, but unfortunately the has no classname. I' just learning jsoup and I don't know which function of jsoup will help me parse text from such a . Example: `.... ... .....` Right now I'm only able to fetch text from with classname Code: ``` document= Jsoup.connect(url).get(); Elements element = document.select("div[class=pandora]"); openBox = element.text(); ``` HTML from `jsoup.org`: ```html <NAME> Lyrics - Nuh Ready Nuh Ready ArtistName = "<NAME>"; SongName = "Nuh Ready Nuh Ready"; function submitCorrections(){ document.getElementById('corlyr').submit(); return false; } var \_comscore = \_comscore || []; \_comscore.push({ c1: "2", c2: "6772046" }); (function() { var s = document.createElement("script"), el = document.getElementsByTagName("script")[0]; s.async = true; s.src = (document.location.protocol == "https:" ? "https://sb" : "http://b") + ".scorecardresearch.com/beacon.js"; el.parentNode.insertBefore(s, el); })(); ![](https://sb.scorecardresearch.com/p?c1=2&c2=6772046&cv=2.0&cj=1) (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en\_US/sdk.js#xfbml=1&version=v2.3"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); [![AZLyrics.com](//www.azlyrics.com/az_logo_tr.png)](//www.azlyrics.com) * [A](//www.azlyrics.com/a.html) [B](//www.azlyrics.com/b.html) [C](//www.azlyrics.com/c.html) [D](//www.azlyrics.com/d.html) [E](//www.azlyrics.com/e.html) [F](//www.azlyrics.com/f.html) [G](//www.azlyrics.com/g.html) [H](//www.azlyrics.com/h.html) [I](//www.azlyrics.com/i.html) [J](//www.azlyrics.com/j.html) [K](//www.azlyrics.com/k.html) [L](//www.azlyrics.com/l.html) [M](//www.azlyrics.com/m.html) [N](//www.azlyrics.com/n.html) [O](//www.azlyrics.com/o.html) [P](//www.azlyrics.com/p.html) [Q](//www.azlyrics.com/q.html) [R](//www.azlyrics.com/r.html) [S](//www.azlyrics.com/s.html) [T](//www.azlyrics.com/t.html) [U](//www.azlyrics.com/u.html) [V](//www.azlyrics.com/v.html) [W](//www.azlyrics.com/w.html) [X](//www.azlyrics.com/x.html) [Y](//www.azlyrics.com/y.html) [Z](//www.azlyrics.com/z.html) [#](//www.azlyrics.com/19.html) Search ![Email](//www.azlyrics.com/images/email.svg) ![Print](//www.azlyrics.com/images/print.svg) "Nuh Ready Nuh Ready" lyrics ============================ **<NAME> Lyrics** ------------------------ **"Nuh Ready Nuh Ready"** (feat. PARTYNEXTDOOR) Mi and di mandem We haffi run from half of di gyal dem So sweet, so sweet Don't want mi children and ting' Mi nuh ready fi all dem tings So sweet, you're so sweet, yeah Yeah, mi nuh ready fi all dem things yet So sweet, so sweet, yeah Yeah, I'm not ready fi all dem tings yet I'm not ready fi all dem tings yet She call me kid, kid, kid My mama kiss her kid She say mi tooth-tooth sweet She say mi tooth-tooth sweet Don't make me feel like I love you Just 'cause I thought you was special Won't make me feel like I love you Baby, girl, I won't settle I had dreams of fuckin' the baddest bitch Last night I awoke up and I fucked the baddest bitch I thought I would be ready when I seen her When I was in the disco I gotta keep it honest Keep it real with you Mi and di mandem We haffi run from half of di gyal dem So sweet, so sweet Don't want mi children and tings Mi nuh ready fi all dem tings So sweet, you're so sweet Mi nuh ready fi all dem tings yet So sweet, so sweet Mi and di mandem We haffi run from half of di gyal dem So sweet, you're so sweet Don't want mi children and tings Mi nuh ready fi all dem tings So sweet, you're so sweet Mi nuh ready fi all dem tings So sweet, so sweet I strapped up 'cause they mapped up 'Cause I need to know where you are Can't keep following these signs 'Cause you're lookin' for a sign, and I can't give you one Start to feel like it's mad love That's givin' your attraction, to me Yeah, I just want you, nobody else, baby I don't wanna get too far It's just you that I want When it's mi and di mandem We haffi run from half of di gyal dem So sweet, so sweet Don't want mi children and tings Mi nuh ready fi all dem tings So sweet, you're so sweet Mi nuh ready fi all dem tings yet So sweet, so sweet Mi and di mandem We haffi run from half of di gyal dem So sweet, so sweet Don't want mi children and tings Mi nuh ready fi all dem tings So sweet, you're so sweet Mi nuh ready fi all dem tings if ( /Android|webOS|iPhone|iPod|iPad|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) { document.write('<div style="margin-left: auto; margin-right: auto;">'+ '<iframe scrolling="no" style="border: 0px none; overflow:hidden;" src="//adv.mxmcdn.net/br/t1.0/m\_js/e\_0/sn\_0/l\_17494554/su\_0/tr\_3vUCAOZlq\_zEKGGqiwqgUipktnY4AJ8vdMlDERwd-IQW1fCzlbIik50-scymuRv\_pi3wUAIxUI2AiwodRggYSWyWKe5520YE8tdDBkiBtPeafB1eU4jsrx-cHUKKrQnbpH1kEJ6cxCXNRK21S-URGe9hKl3IVQsjUfAjAGzo670kV-\_NZoBHp8gEZ5eOQESUhj\_qd\_IMSEvXm2euf-p8Ih6vduevXpBlMcIEAKI3kCxKguw10zJEFpaF8y<KEY> width="290px" height="50px"></iframe>'+ '</div>'); } [Submit Corrections](#) 1. [AZLyrics](//www.azlyrics.com) 2. [C](//www.azlyrics.com/c.html) 3. [Calvin Harris Lyrics](//www.azlyrics.com/c/calvinharris.html) Search * [Submit Lyrics](//www.azlyrics.com/add.php) * [Soundtracks](//www.stlyrics.com) * [Facebook](//www.facebook.com/pages/AZLyricscom/154139197951223) * [Contact Us](//www.azlyrics.com/contact.html) * [Advertise Here](//www.azlyrics.com/adv.html) * [Privacy Policy](//www.azlyrics.com/privacy.html) * [DMCA Policy](//www.azlyrics.com/copyright.html) Powered by ![MusixMatch](//www.azlyrics.com/images/mxm.png) Calvin Harris lyrics are property and copyright of their owners. "Nuh Ready Nuh Ready" lyrics provided for educational purposes and personal use only. curdate=new Date(); document.write("<strong>Copyright &copy; 2000-"+curdate.getFullYear()+" AZLyrics.com<\/strong>"); cf\_page\_artist = ArtistName; cf\_page\_song = SongName; cf\_page\_genre = "pop"; var \_gaq = \_gaq || []; \_gaq.push(['\_setAccount', 'UA-4309237-1']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); window.jQuery || document.write('<script src="//www.azlyrics.com/local/jquery.min.js"><\/script>') $(function () { if ($('#CssFailCheck').is(':visible') === true) { $('<link rel="stylesheet" type="text/css" href="//www.azlyrics.com/bs/css/bootstrap.min.css"><link rel="stylesheet" href="//www.azlyrics.com/bsaz.css">').appendTo('head'); } }); ``` What changes should I do to achieve the above? Thanks<issue_comment>username_1: Try this ``` Elements main = doc.select("div[class=container main-page]"); Elements row = main.select("div[class=row]"); Elements col = row.select("div[class=col-xs-12 col-lg-8 text-center]"); songMetaDataTextView.setText(Html.fromHtml(col.select("div").get(7).toString()); ``` You have nested tags ``` ![Email](//www.azlyrics.com/images/email.svg) ![Print](//www.azlyrics.com/images/print.svg) "Nuh Ready Nuh Ready" lyrics ============================ **Calvin Harris Lyrics** ------------------------ **"Nuh Ready Nuh Ready"** (feat. PARTYNEXTDOOR) ``` So first you get container main-page then row and then col-xs-12 col-lg-8 text-center and then finally get the text using index 7 Upvotes: 1 [selected_answer]<issue_comment>username_2: The following code should get you the lyrics formatted how you want: ``` // Get the lyrics div element Element lyricsDiv = document.select("div.main-page > div.row > div.col-xs-12").select("div").get(7); // Get the html of the element and replace and comments String lyrics = lyricsDiv.html().replaceAll(" ", "").replaceAll("", ""); ``` Upvotes: 1
2018/03/16
307
992
<issue_start>username_0: Consider this variable ``` X = "1_2_3_4", ``` How to I get X into a binary string format? So like this ``` <<"1_2_3_4">> ``` I'm getting all manner of errors trying to figure it out. Thanks in advance, Snelly.<issue_comment>username_1: Use the built in conversion function. list\_to\_binary(X). Upvotes: 3 [selected_answer]<issue_comment>username_2: > > Thanks Dave! I had a quite a complex function concatinating variables > and strings/integers/atoms etc. > > > In case you are interested: ``` convert(L) -> convert(L, <<>>). convert([], Bin) -> Bin; convert([H|T], Bin) -> convert(T, <>). ``` > > (what I was thinking of as Strings) as lists! Confusing > > > I think the reason that it's confusing is because sometimes the shell prints out a list as a string and sometimes it doesn't. In my opinion, things would be much clearer if the shell always output a list as a list unless you specifically requested a string. Upvotes: 0
2018/03/16
838
3,476
<issue_start>username_0: On the subject of Anonymous classes, the Oracle documentation states that... > > They are like local classes except that they do not have a name. Use them if you need to use a local class only once > > > Now, given that local classes are (to my knowledge) classes defined within a method (or some other local construct) like the following...(where 'MyInterface' is an interface with an abstract 'test' method) ``` public void localTest(){ MyInterface mi = new MyInterface(){ @Override public void test(){System.out.println("test");}; }; } ``` The above is OK and falls within the definition above, however, I can also define the following... ``` class MyClass{ MyInterface mi = new MyInterface(){ @Override public void test(){System.out.println("test");}; }; } ``` This isn't within a method so isn't a 'Local' class and therefore doesn't fall within the above definition. Is there anywhere I can read about these types of anonymous classes (anonymous member classes if you will). What exactly are they if not anonymous classes as defined?<issue_comment>username_1: Local classes are defined [here](https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html) as being defined in a *block*, rather than in a method. Your example is still an anonymous class. If you're in the process of learning, a note here is that you can actually replace the declaration with a lambda expression like so: ``` MyInterface mi = () -> System.out.println("test"); ``` Also, anonymous classes are only described as being *like* local classes, meaning that the former is not necessarily a subset of the latter. Upvotes: 0 <issue_comment>username_2: Both examples you show are anonymous classes. A true local class is a class definition in a method (or other code block), with an actual name (so, not anonymous). Given your example, an equivalent local class would be: ``` public void localTest(){ class LocalClass implements MyInterface { @Override public void test(){ System.out.println("test"); } } MyInterface mi = new LocalClass(); } ``` In my opinion you should hardly ever need a local class. I think I have only tried to use it once, to only quickly refactor it when I got a grip on what I actually needed. The most important difference between local classes and anonymous classes is that you can reuse a local class within the same method (that is create multiple instances in the same method; without resorting to loops or lambdas). Furthermore, as you actually have class definition, you can also define and call methods that aren't defined in the interface or super-class. Prior to Java 10 and the introduction of `var`, this was not possible with anonymous classes. Other minor differences are that local classes can be abstract or final, and local classes can extend (and be extended by) other local classes, while an anonymous class is not final and cannot be abstract, but anonymous classes cannot be extended by other classes. For more information regarding the difference between local classes and anonymous classes, see the Java Language Specification, specifically [14.3. Local Class Declarations](https://docs.oracle.com/javase/specs/jls/se9/html/jls-14.html#jls-14.3) and [15.9.5. Anonymous Class Declarations](https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.9.5) and related sections. Upvotes: 1
2018/03/16
667
2,352
<issue_start>username_0: I need to test that a series of asynchronous functions are called in a particular order. Is there an easy way to do this? An example of what I want to achieve below: ``` describe("Test ASYNC order", () => { it("Calls in a particular order", () => { const p1 = new Promise(resolve => setTimeout(resolve, 500)); const p2 = new Promise(resolve => setTimeout(resolve, 600)); const p3 = new Promise(resolve => setTimeout(resolve, 200)); /* How would I test that the order of the promises resolving is p3 then p1 then p2 ????? */ }) }) ```<issue_comment>username_1: One way to do that is the following: ``` test('Calls in a particular order', async () => { const res = []; const storeRes = index => res.push(index); const p1 = new Promise(resolve => setTimeout(resolve, 500)).then(() => storeRes(1)); const p2 = new Promise(resolve => setTimeout(resolve, 600)).then(() => storeRes(2)); const p3 = new Promise(resolve => setTimeout(resolve, 200)).then(() => storeRes(3)); await Promise.all([p1, p2, p3]); expect(res).toEqual([3, 1, 2]); }); ``` It pushes values to an array after each promise, and once all of them have resolved, tests the order of the values in the `result` array against the expected order. Upvotes: 4 [selected_answer]<issue_comment>username_2: You can create and use a Deferred object, as described in [Testing Promise Side Effects with Async/Await](https://rescale.com/testing-promise-side-effects-with-asyncawait/). I would recommend this over using setTimeout, as unless you are controlling clocks with `jest.useFakeTimers`, setTimeout will increase the time it takes to execute your test. ```js class Deferred { constructor() { this.promise = new Promise((resolve, reject) => { this.resolve = resolve; this.reject = reject; }); } } test('Calls in a particular order', async () => { const res = []; const storeRes = index => res.push(index); const d1 = new Deferred(); d1.promise.then(() => storeRes(1)); const d2 = new Deferred(); d2.promise.then(() => storeRes(2)); const d3 = new Deferred(); d3.promise.then(() => storeRes(3)); d3.resolve(); d1.resolve(); d2.resolve(); await Promise.all([d1.promise, d2.promise, d3.promise]); expect(res).toEqual([3, 1, 2]); }); ``` Upvotes: 0
2018/03/16
1,695
5,685
<issue_start>username_0: I have 20 csv files. Each are unrelated. How do I combine them together into one xlsx file with 20 sheets, each named after the csv files. ``` $root = "C:\Users\abc\Desktop\testcsv" $CSVfiles = Get-ChildItem -Path $root -Filter *.csv $xlsx = "C:\Users\abc\Desktop\testxl.xlsx" #output location $delimiter = "," #delimiter #Create a excel $xl=New-Object -ComObject Excel.Application $xl.Visible=$true #add a workbook $wb=$xl.WorkBooks.add(1) ForEach ($csv in $CSVfiles){ #name the worksheet $ws=$wb.WorkSheets.item(1) $ws.Name = [io.path]::GetFileNameWithoutExtension($csv) $TxtConnector = ("TEXT;" + $csv) $Connector = $ws.QueryTables.add($TxtConnector,$ws.Range("A1")) $query = $ws.QueryTables.item($Connector.name) $query.TextFileOtherDelimiter = $delimiter $query.TextFileParseType = 1 $query.TextFileColumnDataTypes = ,1 * $ws.Cells.Columns.Count $query.AdjustColumnWidth = 1 # Execute & delete the import query $query.Refresh() $query.Delete() $wb.SaveAs($xlsx,51) } # Save & close the Workbook as XLSX. $xl.Quit() ```<issue_comment>username_1: See below for a solution with uses the [`OpenText`](https://msdn.microsoft.com/en-us/vba/excel-vba/articles/workbooks-opentext-method-excel) method. At least two things to note: * I'm assuming your workbook creates a single sheet by default. if creates more than that, you will need to modify the script so that these additional sheets are deleted from the end result. * The way you specify `TextFileColumnDataTypes` is quite clever. You will need to modify it and feed the array to the `FieldInfo` argument below. See the documentation linked above for the kind of array it is expecting. --- ``` $CSVfiles = Get-ChildItem -Path $root -Filter *.csv $xlsx = "C:\Users\abc\Desktop\testxl.xlsx" #output location #Create a excel $xl = New-Object -ComObject Excel.Application $xl.Visible=$true #add a workbook $wb = $xl.WorkBooks.add(1) # how many worksheets do you have in your original workbook? Assuming one: $ws = $wb.Worksheets.Item(1) ForEach ($csv in $CSVfiles){ # OpenText method does not work well with csv files Copy-Item -Path $csv.FullName -Destination ($csv.FullName).Replace(".csv",".txt") -Force # Use OpenText method. FieldInfo will need to be amended to suit your needs $xl.WorkBooks.OpenText(` ($file.FullName).Replace(".csv",".txt"), # Filename 2, # Origin 1, # StartRow 1, # DataType 1, # TextQualifier $false, # ConsecutiveDelimiter $false, # Tab $false, # Semicolon $true, # Comma $false, # Space $false, # Other $false, # OtherChar @() # FieldInfo ) $tempBook = $xl.ActiveWorkbook $tempBook.worksheets.Item(1).Range("A1").Select() | Out-Null $tempBook.worksheets.Item(1).Move($wb.Worksheets.Item(1)) | Out-Null # name the worksheet $xl.ActiveSheet.Name = $csv.BaseName Remove-Item -Path ($csv.FullName).Replace(".csv",".txt") -Force } $ws.Delete() # Save & close the Workbook as XLSX. $wb.SaveAs($xlsx,51) $wb.Close() $xl.Quit() ``` Upvotes: 0 <issue_comment>username_2: [This way](https://code.adonline.id.au/multiple-csvs-into-xlsx/), change the first line to the folder where you store those 20 CSV files and then ``` $path="c:\path\to\folder" #target folder cd $path; $csvs = Get-ChildItem .\* -Include *.csv $y=$csvs.Count Write-Host "Detected the following CSV files: ($y)" foreach ($csv in $csvs) { Write-Host " "$csv.Name } $outputfilename = $(get-date -f yyyyMMdd) + "_" + $env:USERNAME + "_combined-data.xlsx" #creates file name with date/username Write-Host Creating: $outputfilename $excelapp = new-object -comobject Excel.Application $excelapp.sheetsInNewWorkbook = $csvs.Count $xlsx = $excelapp.Workbooks.Add() $sheet=1 foreach ($csv in $csvs) { $row=1 $column=1 $worksheet = $xlsx.Worksheets.Item($sheet) $worksheet.Name = $csv.Name $file = (Get-Content $csv) foreach($line in $file) { $linecontents=$line -split ',(?!\s*\w+")' foreach($cell in $linecontents) { $worksheet.Cells.Item($row,$column) = $cell $column++ } $column=1 $row++ } $sheet++ } $output = $path + "\" + $outputfilename $xlsx.SaveAs($output) $excelapp.quit() cd \ #returns to drive root ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: <https://stackoverflow.com/a/51094040/5995160> answer is too slow when dealing with csv's with a ton of data, I modified this solution to use <https://github.com/dfinke/ImportExcel>. This has greatly improved the performance of this task, at least for me. ``` Install-Module ImportExcel -scope CurrentUser $csvs = Get-ChildItem .\* -Include *.csv $csvCount = $csvs.Count Write-Host "Detected the following CSV files: ($csvCount)" foreach ($csv in $csvs) { Write-Host " -"$csv.Name } $excelFileName = $(get-date -f yyyyMMdd) + "_" + $env:USERNAME + "_combined-data.xlsx" Write-Host "Creating: $excelFileName" foreach ($csv in $csvs) { $csvPath = ".\" + $csv.Name $worksheetName = $csv.Name.Replace(".csv","") Write-Host " - Adding $worksheetName to $excelFileName" Import-Csv -Path $csvPath | Export-Excel -Path $excelFileName -WorkSheetname $worksheetName } ``` This solution assumes that the user has already changed directories to where all the csv's live. Upvotes: 2
2018/03/16
546
1,922
<issue_start>username_0: I'm using lodash map in this way ``` const newCollection = _.map( responseJson.OldCollection, AddDetailsToSingleItems ); ``` having ``` function AddDetailsToSingleItems (item ) { ... } ``` I ask you, please, what's the right syntax to pass a parameter to this function. I'd like to have ``` function AddDetailsToSingleItems (item, myNewParam ) { ... } ``` (note the `myNewParam`). I don't kow how to tell to loadsh map to pass every single item to my function *and* to pass one more param when calling `AddDetailsToSingleItems`<issue_comment>username_1: You haven't explained where `myNewParam` is coming from, but I assume you have that data somewhere. Lodash [map](https://lodash.com/docs/4.17.5#map) (just like normal JavaScript [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)) accepts a function as its second argument to be run on all elements of the supplied list. You can just pass an anonymous function: ``` _.map( responseJson.OldCollection, item => AddDetailsToSingleItems(item, myNewParam) ); ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: You can create a function that knows the value of `myNewParam`, but only accepts the `item` parameter like this: ``` var myNewParam = 'param_value'; var AddDetailsFn = function(m) { return function(item) { return AddDetailsToSingleItems(item, m); }; }; const newCollection = _.map( responseJson.OldCollection, AddDetailsFn(myNewParam) ); ``` This way, `_.map` only sees a function that takes a single parameter. The `AddDetailsFn` returns a function that takes a single parameter, but already has the value of `myNewParam` captured. You can also be more succinct with: ``` const newCollection = _.map( responseJson.OldCollection, function(item) { return AddDetailsToSingleItems(item, myNewParam); } ); ``` Upvotes: 2
2018/03/16
626
2,182
<issue_start>username_0: For example, I have JSON in response: ``` [{"id":1,"name":"text"},{"id":2,"name":"text"}]} ``` I want to verify if a response contains a custom object. For example: ``` Person(id=1, name=text) ``` I found solution: ``` Person[] persons = response.as(Person[].class); assertThat(person, IsArrayContaining.hasItemInArray(expectedPerson)); ``` I want to have something like this: ``` response.then().assertThat().body(IsArrayContaining.hasItemInArray(object)); ``` Is there any solution for this? Thanks in advance for your help!<issue_comment>username_1: The `body()` method accepts a path and a Hamcrest matcher (see the [javadocs](https://static.javadoc.io/io.rest-assured/rest-assured/3.0.6/io/restassured/response/ValidatableResponseOptions.html#body-java.lang.String-org.hamcrest.Matcher-java.lang.Object...-)). So, you could do this: ``` response.then().assertThat().body("$", customMatcher); ``` For example: ``` // 'expected' is the serialised form of your Person // this is a crude way of creating that serialised form // you'll probably use whatever JSON de/serialisaiotn library is in use in your project Map expected = new HashMap(); expected.put("id", 1); expected.put("name", "text"); response.then().assertThat().body("$", Matchers.hasItem(expected)); ``` Upvotes: 4 <issue_comment>username_2: In this case, you can also use json schema validation. By using this we don't need to set individual rules for JSON elements. Have a look at [Rest assured schema validation](https://github.com/rest-assured/rest-assured/wiki/Usage#json-schema-validation) ``` get("/products").then().assertThat().body(matchesJsonSchemaInClasspath("products-schema.json")); ``` Upvotes: 0 <issue_comment>username_3: This works for me: ``` body("path.to.array", hasItem( allOf( hasEntry("firstName", "test"), hasEntry("lastName", "test") ) ) ) ``` Upvotes: 4 <issue_comment>username_4: Could validate in single line by extracting using jsonpath() ``` assertTrue( response.then().extract().jsonPath() .getList("$", Person.class) .contains(person)); ``` Upvotes: 0