date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/21
395
1,366
<issue_start>username_0: I have a data set being returned from a Firebase database, inside the data set is team information that contains number of games played, points, fouls conceded, etc... Team - Points Chelsa 10 Manchester 6 Liverpool 18 Madrid 22 etc... I need to order these top to bottom by the number of points, so using the above example, Madrid would be first, then Liverpool, then Chelsea and lastly Manchester. My question is; does Firebase allow me to do this? I have tried using; ``` OrderByChild("points"); ``` But this does not order by points (asc or desc) Or should I order the Java arrayList using sort?<issue_comment>username_1: There is no descending order in Firebase, according to this from the docs: > > `orderByChild()` > > > Children with a numeric value come next, sorted in ascending order. If multiple children have the same numerical value for the specified child node, they are sorted by key. > > > then you can do: ``` orderByChild("points").limitToFirst(20); ``` which will give you the first 20, or you can use `limitToLast(20);` more info here: <https://firebase.google.com/docs/database/android/lists-of-data> Upvotes: 1 <issue_comment>username_2: Firebase database provide only ascending order sort. So you have to get this data and reverse the data. ``` Collection.reverse(datalist); ``` Upvotes: 0
2018/03/21
810
2,632
<issue_start>username_0: The Dockerfile: ``` FROM scratch COPY hello /app/hello ENTRYPOINT ["/app/hello","-g","OMGITWORKS!"] ``` where `hello` is a copy of `/usr/bin/hello`. The commands: ``` docker build -t hello . docker run hello ``` Using `FROM scratch` or `FROM alpine` I get: ``` standard_init_linux.go:185: exec user process caused "no such file or directory" ``` `docker inspect` seems to imply that the container runs the binary without a shell: ``` "Path": "/app/hello", "Args": [ "-g", "OMGITWORKS!" ], ``` and ``` "Entrypoint": [ "/app/hello", "-g", "OMGITWORKS!" ], ``` But, surprise, with `FROM python:3.4`: ``` OMGITWORKS! ``` Probing the innards of the alpine-based container shows: ``` / # ls -al /app/hello -rwxr-xr-x 1 root root 23112 Mar 21 15:25 /app/hello ``` So, I don't really understand what is going on. What is the magic in the python:3.4 image?<issue_comment>username_1: > > exec user process caused "no such file or directory" > > > This is often cause for confusion as it's a bit misleading if, like in your case, the binary actually exists. Usually this indicates a non-static binary that can't find it's libraries it is linked against, most likely glibc, but depends on the app obviously. Running `ldd /app/hello` should give you a list of linked libraries. > > What is the magic in the python:3.4 image? > > > The "magic" is that `python:3.4` is based on [glibc](https://www.gnu.org/software/libc/), while `alpine` is based on [musl](https://www.musl-libc.org/). Binaries linked against either are not compatible with the other. You have a few options: 1. For a quick test use `FROM alpine-glibc`, if it works you know for sure it is the missing glibc, else there might be more missing -> `ldd` and install any missing libraries in your `Dockerfile` 2. Build your binary in a musl container so it's linked against the correct standard lib if you want to use `FROM alpine` 3. Build a completely static binary and use any image, even `scratch` The recently added Docker [multistage](https://docs.docker.com/develop/develop-images/multistage-build/) feature comes in handy for the last two options. Upvotes: 2 [selected_answer]<issue_comment>username_2: Adding to @ErikDannenberg's answer: [This blog post](http://blog.oddbit.com/2015/02/05/creating-minimal-docker-images/) describes in detail how one can use `ldd` and `objdump` to figure out all the dependencies and how to add them to the docker image. And it also points to the [`dockerize` tool](https://github.com/larsks/dockerize) which does that automatically. Upvotes: 0
2018/03/21
706
2,058
<issue_start>username_0: I need a JS expression to match a combination of /\* characters I have this now ``` /(\b\/*\b)g ``` but it does not work. ETA: any string that has /\* should match so... * Hello NO MATCH * 123 NO MATCH * /\* HELLo MATCH * /\*4534534 MATCH<issue_comment>username_1: You might use a positive lookahead and test if the string contains `/*`? If so, match any character one or more times `.+` from the beginning of the string `^` until the end of the string `$` [`^(?=.*\/\*).+$`](https://regex101.com/r/GY1p8J/1) **Explanation** * `^` Begin of the string * `(?=` Positive lookahead that asserts what is on the right + `.*\/\*` Match any character zero or more time and then `/*` * `)` Close positive lookahead * `.+` Match any character one or more times * `$` End of the string ```js const strings = [ "Hello NO MATCH", "123 NO MATCH", "/* HELLo MATCH", "/*4534534 MATCH", "test(((*/*" ]; let pattern = /^(?=.*\/\*).+$/; strings.forEach((s) => { console.log(s + " ==> " + pattern.test(s)); }); ``` I think you could also use [indexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) to get the index of the first occurence of `/*`. It will return -1 if the value is not found. ```js const strings = [ "Hello NO MATCH", "123 NO MATCH", "/* HELLo MATCH", "/*4534534 MATCH", "test(((*/*test", "test /", "test *", "test /*", "/*" ]; let pattern = /^(?=.*\/\*).+$/; strings.forEach((s) => { console.log(s + " ==> " + pattern.test(s)); console.log(s + " ==> " + (s.indexOf("/*") !== -1)); }); ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: Since you only want to detect if it contains something you don't have to use regex and can just use `.includes("/*")`: ```js function fits(str) { return str.includes("/*"); } var test = [ "Hello NO MATCH", "123 NO MATCH", "/* HELLo MATCH", "/*4534534 MATCH" ]; var result = test.map(str => fits(str)); console.log(result); ``` Upvotes: 1
2018/03/21
309
1,070
<issue_start>username_0: I'm using a function that returns an `std::pair`: ``` std::pair myFunction() { //Do something... if (success) { return {true, someValue}; } else { return {false, someOtherValue}; } } ``` On success, the pair's first value will be `true`, otherwise `false`. Some functions that call `myFunction()` use the returned pair's second value, others don't. For those, I'm calling `myFunction()` like this: ``` bool myOtherFunction() { //Do something... bool success; std::tie(success, std::ignore) = myFunction(); //I don't care about the pair's second value return success; } ``` Is there a way to avoid declaring `bool success` and returning `myFunction()`'s return value's first element directly?<issue_comment>username_1: a `std::pair` is just a struct with 2 values; so just return the "first" item in the struct. ``` return myFunction().first; ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Perhaps ``` return std::get<0>(myFunction()); ``` or ``` return std::get(myFunction()); ``` Upvotes: 3
2018/03/21
675
2,249
<issue_start>username_0: I have the following linux cmd: ``` grep -o file.txt "\"uri\":\".{1,}\"" ``` The text i have is the following: ``` "some characters here","uri":"some_URI*Here.^%$#!", "again a set of irrelevant characters" ``` Of course the output i want to have is: ``` "uri":"some_URI*Here.^%$#!" ``` Why dont i have the correct output? Because of the " required by the grep which mix with " in my text? How to fix it?<issue_comment>username_1: You could use the following regex: ``` grep -oE '"uri":".[^"]+"' inputFile ``` Original poster provided a regex that is almost correct but have some flaws, below is his/her version and a corrected one: ``` grep -o inputFile "\"uri\":".{1,}\"" # wrong grep -oE '"uri":"[^"]{1,}"' inputFile # correct ``` The problems with the first use of grep are: * inputFile should come after the regex, not before * Needs `-E` flag for `{1,}` to work * Better use single quotes outside so that double quotes need no be escaped * Need to use `[^"]` character class instead of `.` Upvotes: 3 [selected_answer]<issue_comment>username_2: Either ``` grep -oE "\"uri\":\"[^\"]{1,}\"" file.txt ``` or ``` grep -o "\"uri\":\"[^\"]\\{1,\\}\"" file.txt ``` will leave out the trailing irrelevant characters. Explanation: * Your `grep` command was listing `file.txt` before the pattern, but `grep` requires pattern first, then files. * Instead of `.`, you need `[^\"]` to match the characters between the quotes. That is because `.` will match a `"` itself, so `.{1,}` matches right through the intervening double quotes ("greedy matching"). The two options are: * with `-E`, `grep` uses extended regular expressions, in which `{}` are automatically range operators. * without `-E`, you need to use backslashes to mark the `{}` as range operators instead of literal characters. `\{1,\}` is the regex syntax. Since you are in a shell double-quoted string, you need to escape the backslashes, whence `\\{1,\\}`. To test shell quoting, an easy way is to use `echo`. For example, in bash: ``` $ echo grep -o "\"uri\":\"[^\"]\\{1,\\}\"" file.txt grep -o "uri":"[^"]\{1,\}" file.txt ``` That shows, for example, that the `\\` in the pattern have been collapsed to a single `\`. Upvotes: 1
2018/03/21
968
3,499
<issue_start>username_0: I am Following both the Enzyme examples for [.find()](http://airbnb.io/enzyme/docs/api/ShallowWrapper/find.html) and this GitHub [enzyme-example-jest](https://github.com/vjwilson/enzyme-example-jest) example to get a basic component to test and verify the outer-most element `className` exists, I do not understand why this does not pass: // REACT COMPONENT ``` class VisitorShortcut extends Component { //all the props & lifecycle hooks here render() { return ( // <-- this className is being tested e.stopPropagation()} className="dropdown open" > {results} ); } } ``` // TEST FILE ``` import React from "react"; import { shallow, mount } from "enzyme"; import VisitorShortcut from "../VisitorShortcut"; describe("Shortcuts", () => { test("The main Class exists", () => { expect( ().find(".visitor-shortcuts").length ).toBe(1); }); }); ``` // OUTPUT ``` Expected value to be (using ===): 1 Received: 0 ``` if I switch to `expect(wrapper.find('div.some-class')).to.have.length(3);` as per Enzyme docs, the output is `TypeError: Cannot read property 'have' of undefined` I am fairly sure I do not need to use the `mount` API instead of `shallow` Thanks for helping to clarify this. It seems so basic...<issue_comment>username_1: The below code worked for me ``` import React from "react"; import { shallow, mount } from "enzyme"; import { assert } from 'chai'; import VisitorShortcut from "../VisitorShortcut"; describe("Shortcuts", () => { test("The main Class exists", () => { const wrapper = shallow(); const visitorShortcutsWrapper = wrapper.find('.visitor-shortcuts'); assert.equal(visitorShortcutsWrapper.length, 1); }); }); ``` By the ways, I am using `assert` from `chai` package. Upvotes: 3 <issue_comment>username_2: I use [`chai`](http://www.chaijs.com/), it works. ``` import React from 'react'; import { shallow } from 'enzyme'; import { expect } from 'chai'; import App from './App'; describe('', () => { const wrapper = shallow(); it('should have an App class', () => { expect(wrapper.find('.App')).to.have.length(1); }); }); ``` Upvotes: 2 <issue_comment>username_3: This works for checking whether there are two sub-elements of an element in Jest ``` expect(wrapper.find('.parent-class').getElements().length).toEqual(2) ``` Upvotes: 2 <issue_comment>username_4: as per Enzyme doc you can do as below: ``` const wrapper = shallow(); expect(wrapper.find("div.visitor-shortcuts").length).toBe(1) ``` Upvotes: 3 <issue_comment>username_5: For a more "complex" scenario, where your component is using multiple instances of another component (internally) and you want to check if those exist - The below test checks there are only 2 instances of `Foo` component with the class name `foo`: Component (to test) ------------------- ```js export const Foo = ({className}) => ; export const Comp = () => ( <> ) ``` Test file --------- ```js import {mount} from "enzyme" import {Comp, Foo} from "../Comp"; describe("Comp", () => { it("Should have 2 Foo components with `.foo` class", () => { const wrapper = mount(); expect(wrapper.find(Foo).filter('.foo')).toHaveLength(2); }) }) ``` The combination of `find` & `filter` allows to use the real component reference `find(Foo)` and not assumed *displayName* `"Foo"`, which is prone to changes. This approach less coupled and I believe to be less error-prone. Upvotes: 0
2018/03/21
254
997
<issue_start>username_0: I'm having an issue getting bootstrap to load in rails 5. I made the mistake of using a product called rapid rails themes (dresssed ives), which is a total piece of garbage, and made a mess of my application. I've removed this theme and am now having an issue with getting bootstrap to load. Any advice would be greatly helpful. I noticed I'm unable to get font-awesome to work as well. Seems like an issue with the assets pipeline.<issue_comment>username_1: Have you tried using a gem to install it? I found this gem that adds it to the project which seems pretty straight forward: <https://github.com/twbs/bootstrap-rubygem> Upvotes: 0 <issue_comment>username_2: Ok, I was able to do it by installing bootstrap manually and adding the following to my config/application.rb ``` <%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => "reload" %> <%= javascript_include_tag "application", "data-turbolinks-track" => "reload" %> ``` Upvotes: 1
2018/03/21
731
2,656
<issue_start>username_0: i want to write a program to convert English to Piglantin using Java,but unlike the traditional way i want to store the vowels in an array...but apparently that doesn't work,i have my boards tomorrow and it would be quite helpful if you could point out my mistake....here's the program snippet ``` class Piglatin_2 { public static void main(String s) { s = s.toUpperCase(); char c[] = {'A', 'E', 'I', 'O', 'U'}; String a = ""; for(int i = 0; i < s.length(); i++) { for(int j = 0; j < 5; j++) { if(s.charAt(i) == c[j]) { a = s.substring(i) + s.substring(0, i) + "AY"; break; } } } System.out.println("Piglatin:"+a); } } ``` I am using the string "London" as an input. The supposed output should be "ONDONLAY" But i am getting "ONLONDAY"<issue_comment>username_1: Firstly, your main method has to take an array of strings, like Michael's comment says. This will work in your favor as well if you are trying to translate each word. If you run your program with a sentence as arguments, the your args[] array will contain each word that is split by white space. For instance, if your sentence is "Hello World" and you run it with ``` $ java -jar myapplication.jar hello world ``` then your args array will look like ``` args[0] = hello args[1] = world ``` from there you should be able to iterate though the array and translate each word to pig latin. [OPINION] If you're just wanting to have a script to pass a sentence to and return pig latin, using Java is kind of line landing a 747 on the freeway. You may want to use something like python or even a shell script if you're using unix. Otherwise, you may consider having a loop that keeps the program running and taking input with a BufferedReader and that way you can keep translating sentences until you end the program. Upvotes: 0 <issue_comment>username_2: I think when you `break`, you have to break out of both loops. Right now your `break` statement only breaks out of the inner loop. Try this: ``` public static void main_other(String s) { s = s.toUpperCase(); char c[] = {'A', 'E', 'I', 'O', 'U'}; String a = ""; outerloop: for(int i = 0; i < s.length(); i++) { for(int j = 0; j < 5; j++) { if(s.charAt(i) == c[j]) { a = s.substring(i) + s.substring(0, i) + "AY"; break outerloop; } } } System.out.println("Piglatin:"+a); } ``` Upvotes: 2 [selected_answer]
2018/03/21
583
1,612
<issue_start>username_0: I need to add Qty and Dayssupply from RXBatch (Test1) to another Rxbatch (Test2) by prescription, where the patid, facid, and ndc matches. Once the qty and dayssuply is added to from test1 to test2, I need test1 qty and dayssuply to be zero. [tables](https://i.stack.imgur.com/M4ost.png) Below is what I’ve been working on, but my script only adds qty to both batches and doesn’t zero out qty once its added. ``` UPDATE RXS SET QTY=RXS_Totals.Qty_Total FROM FWDB.RX.RXS RXS INNER JOIN ( SELECT FacID, PatID, NDC, SUM(Qty) AS Qty_Total FROM FWDB.RX.RXS WHERE RxBatch='test1' OR RxBatch='test2' GROUP BY FacID, PatID, NDC HAVING MIN(RxBatch) <> MAX(RxBatch) ) AS RXS_Totals ON RXS_Totals.FacID = RXS.FacID AND RXS_Totals.PatID = RXS.PatID AND RXS_Totals.NDC = RXS.NDC ```<issue_comment>username_1: I think you just need: ``` UPDATE RXS SET QTY = (CASE WHEN RxBatch = 'test2' THEN RXS_Totals.Qty_Total ELSE 0 END) FROM . . . WHERE RxBatch IN ('test1', 'test2'); ``` Upvotes: 0 <issue_comment>username_2: I think you're doing a self-join, if so, you could do something like this : ``` UPDATE rx SET Qty = (CASE WHEN rx.RxBatch = rx1.RxBatch THEN 0 ELSE rx1.Qty + rx2.Qty END), DaysSupply = (CASE WHEN rx.RxBatch = rx1.RxBatch THEN 0 ELSE rx1.DaysSupply + rx2.DaysSupply END) FROM RXS rx LEFT JOIN RXS rx1 ON rx1.RxNo = rx.RxNo AND rx1.RxBatch = 'TEST1' LEFT JOIN RXS rx2 ON rx2.RxNo = rx.RxNo AND rx2.RxBatch = 'TEST2' WHERE rx1.PatID = rx2.PatID AND rx1.FacID = rx2.FacID AND rx1.NDC = rx2.NDC ``` Upvotes: 2 [selected_answer]
2018/03/21
638
2,322
<issue_start>username_0: How to make it deserialize to original type? WebJobs SDK allows to specify the type of a POCO object and add `QueueTriggerAttribute` near it to make it function ([the doc](https://github.com/Azure/azure-webjobs-sdk/wiki/Queues#poco-plain-old-clr-object-queue-messages)). Now it deserializes not to an original type but some other (from run to run it varies). Here is the code: ```cs public class PocoCommandA { public string Prop { get; set; } } public class PocoCommandB { public string Prop { get; set; } } public static void Func1([QueueTrigger("myqueue")] PocoCommandA aCommand) {... } public static void Func2([QueueTrigger("myqueue")] PocoCommandB bCommand) { ... } ``` And it calls `Fun2` (or some other) when ```cs var a = new PocoCommandA(); var cloudQueueMessage = new CloudQueueMessage(JsonConvert.SerializeObject(a)); await queue.AddMessageAsync(cloudQueueMessage); ```<issue_comment>username_1: If PocoCommandA and PocoCommandB 2 classes has the same properties that it can't know which message belong to specific object. As it could be any of the 2 Objects. Generally, we don't recommond that 2 classes have the same properties. If PocoCommandA and PocoCommandB 2 classes have the different properties, then if we send the Poco message to queue, then corresponding function will be triggered. And we no need to deserialize it. We could use the aCommand or bCommand directly. Upvotes: 1 <issue_comment>username_2: Fixed by manually handling serialization / deserialization. This entails that handling of the messages are done using `switch` (could be Reflection of course). Deserialize: ```cs var message = (IMessage) JsonConvert.DeserializeObject(msg, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects, DateParseHandling = DateParseHandling.DateTimeOffset } ); ``` Serialize: ```cs new CloudQueueMessage(JsonConvert.SerializeObject(msg, /* the same */)); ``` WebJobs SDK place where it is handled is [here](https://github.com/Azure/azure-webjobs-sdk/blob/663a508e8a851629c26a51e7de3af36629dfd120/src/Microsoft.Azure.WebJobs.Protocols/JsonSerialization.cs). But it is not configurable. [Issue](https://github.com/Azure/azure-webjobs-sdk/issues/1639) created there. Upvotes: 0
2018/03/21
3,039
10,312
<issue_start>username_0: I am trying to use JavaScript to convert a JSON File to a csv that can be opened in excel. **What I have:** ``` function exportToCsv(filename, rows) { var processRow = function (row) { var finalVal = ''; for (var j = 0; j < row.length; j++) { var innerValue = row[j] === null ? '' : row[j].toString(); if (row[j] instanceof Date) { innerValue = row[j].toLocaleString(); }; var result = innerValue.replace(/"/g, '""'); if (result.search(/("|,|\n)/g) >= 0) result = '"' + result + '"'; if (j > 0) finalVal += ','; finalVal += result; } return finalVal + '\n'; }; var csvFile = ''; for (var i = 0; i < rows.length; i++) { csvFile += processRow(rows[i]); } var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' }); if (navigator.msSaveBlob) { // IE 10+ navigator.msSaveBlob(blob, filename); } else { var link = document.createElement("a"); if (link.download !== undefined) { // feature detection // Browsers that support HTML5 download attribute var url = URL.createObjectURL(blob); link.setAttribute("href", url); link.setAttribute("download", filename); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } } exportToCsv('export.csv', 'FILENAME.JSON') ``` **FILENAME.JSON (very detailed- nested example)** ``` [{ "countyCode": 18, "excludedFlag": null, "fees": { "annualTotalFees": 35.6, "annualTotalFeesMail": 36.35, "annualTotalFeesOnline": 38.35, "biennialTotalFees": 71.2, "biennialTotalFeesMail": 71.95, "biennialTotalFeesOnline": 73.95, "branchFeeFlag": false, "delinquentFeeAmount": 5, "mhBackTax": 0, "mhBackTaxMonths": 0 }, "fileId": 876, "id": "2398743-32403274-2398", "messages": [ { "messageCode": "RN2", "messageText": "Plate must be replaced if a 2 year renewal is desired.", "messageType": "I" }, { "messageCode": "RN40", "messageText": "You must complete the affidavit on the reverse side or provide a copy of your Florida insurance identification card.", "messageType": "I" }, { "messageCode": "RN41", "messageText": "Insurance is on file.", "messageType": "II" } ], "registrationDetail": { "annualPlateReplacementFlag": false, "arfCredit": 25.6, "biennialPlateReplacementFlag": true, "customerStopFlag": null, "delinquentDate": "2018-02-11T00:00:00", "expirationDate": "2018-01-09T00:00:00", "foreignAddressFlag": false, "honorayConsulPlateFlag": null, "hovDecalNumber": null, "hovDecalYear": null, "hovExpirationDate": null, "inventorySubtype": "RP", "lastActivityCounty": 15, "legislativePlateDueForReplacementFlag": false, "licensePlateCode": "RPR", "licensePlateNumber": "Plate", "mailToAddressFlag": false, "mailToCustomerNumber": null, "mhLocationCode": null, "militaryOwnerFlag": false, "numberOfRegistrants": 1, "onlineRenewalEligibilityFlag": true, "pinNumber": 329874938, "plateExpirationDate": "2018-03-18T00:00:00", "plateIssueDate": "2008-09-18T00:00:00", "possibleNgExemptionFlag": false, "registrationNumber": 3945874398, "registrationOnlyFlag": null, "registrationType": "R", "registrationUse": "PR", "renewalCountyCode": 16, "rentalParkFlag": null, "seminoleMiccosukeeIndianFlag": false, "taxCollectorRenewalEligibilityFlag": true, "vehicleClassCode": 1 }, "registrationOwners": [ { "customer": { "addresses": [ { "addressType": "R", "city": "BRADENTON", "countryCode": "US", "countyCode": 16, "foreignPostalCode": null, "state": "FL", "streetAddress": "24545 6th ave w", "zipCode": 34205, "zipPlus": null }, { "addressType": "M", "city": "BRADENTON", "countryCode": "US", "countyCode": 16, "foreignPostalCode": null, "state": "FL", "streetAddress": "24545 6th ave w", "zipCode": 34205, "zipPlus": 8344 } ], "companyName": null, "customerNumber": 3490436, "customerStopFlag": false, "customerType": "I", "dateOfBirth": "1971-01-09T00:00:00", "dlExpirationDate": "2025-01-09T00:00:00", "dlRenewalEligibilityFlag": true, "driverLicenseNumber": "N0932433902", "emailAddress": null, "feidNumber": null, "firstName": "Test", "lastName": "Name", "middleName": "Name", "militaryExemptionFlag": false, "nameSuffix": null, "sex": "F" }, "registrationOwnershipNumber": 1 } ], "shippingAddress": { "address": { "addressType": "S", "city": "BRADENTON", "countryCode": "US", "countyCode": 15, "foreignPostalCode": null, "state": "FL", "streetAddress": "24545 6th ave w", "zipCode": 34205, "zipPlus": 8344 }, "shippingCompanyName": null, "shippingName1": "<NAME>", "shippingName2": null }, "stops": null, "vehicle": { "address": null, "bodyCode": "4D", "brakeHorsePower": null, "cubicCentimeters": null, "grossWeight": null, "insuranceAffidavitCode": null, "leaseOwnerFlag": false, "lengthFeet": null, "lengthInches": null, "majorColorCode": "GLD", "makeCode": "CHEV", "minorColorCode": null, "netWeight": 3200, "numberOfAxles": null, "ownerUnitNumber": null, "titleNumber": 32434324, "vehicleIdentificationNumber": "1F5ZD5EU5BF32434234", "vehicleNumber": 324334, "vehicleType": "AU", "vesselCode": null, "vesselManufacturerDesc": null, "vesselResidentStatus": "Y", "vesselWaterType": null, "widthFeet": null, "widthInches": null, "yearMake": 2011 } } ] ``` I am trying to figure out how I can drop a json file into the bottom where it says FILENAME.JSON. My end goal is to allow a user to select a file to convert a "large" json file to a csv file. Every month will have a new json file so I am trying to make it easy on the user to allow them to select the file that will be converted. Is there an easy way to tie this JavaScript to allow user to select a file? Any help with this would be greatly appreciated. **EDIT (What Im trying below that has not worked yet. It spins as if it is doing something but never downloads the file or creates it.)** ``` json2csv fetch('http://path/to/json/file') .then(function(response) { function flatObjectToString(obj){ var s = "" Object.keys(obj).map(key=>{ if(obj[key] === null){ s+= key +":" }else if(obj[key].toLocaleDateString){ s+=key+": " +obj[key].toLocaleDateString() +"\n" }else if(obj[key] instanceof Array){ s+= key+":\n" +listToFlatString(obj[key]) }else if(typeof obj[key] == "object"){ s+= key+":\n" +flatObjectToString(obj[key]) }else{ s+= key+":" +obj[key] } s+= "\n" }) return s } function listToFlatString(list) { var s = ""; list.map(item => { Object.keys(item).map(key => { s+="\n" if (item[key] instanceof Array) { s += key + "\n" + listToFlatString(item[key]) }else if(typeof item[key] == "object" && item[key] !== null){ s+= key+": " + flatObjectToString(item[key]) } else { s += key + ": " + (item[key] === null ? "" : item[key].toLocaleDateString ? item[key].toLocaleDateString : item[key].toString()) } }) }) return s; } function flatten(object, addToList, prefix) { Object.keys(object).map(key => { if (object[key] === null) { addToList[prefix + key] = "" } else if (object[key] instanceof Array) { addToList[prefix + key] = listToFlatString(object[key]) } else if (typeof object[key] == 'object' && !object[key].toLocaleDateString) { flatten(object[key], addToList, prefix + key + '.') }else{ addToList[prefix + key] = object[key] } }) return addToList } exportToCsv("download.csv", data.map(record=>flatten(record, {}, ''))) }) ```<issue_comment>username_1: If PocoCommandA and PocoCommandB 2 classes has the same properties that it can't know which message belong to specific object. As it could be any of the 2 Objects. Generally, we don't recommond that 2 classes have the same properties. If PocoCommandA and PocoCommandB 2 classes have the different properties, then if we send the Poco message to queue, then corresponding function will be triggered. And we no need to deserialize it. We could use the aCommand or bCommand directly. Upvotes: 1 <issue_comment>username_2: Fixed by manually handling serialization / deserialization. This entails that handling of the messages are done using `switch` (could be Reflection of course). Deserialize: ```cs var message = (IMessage) JsonConvert.DeserializeObject(msg, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects, DateParseHandling = DateParseHandling.DateTimeOffset } ); ``` Serialize: ```cs new CloudQueueMessage(JsonConvert.SerializeObject(msg, /* the same */)); ``` WebJobs SDK place where it is handled is [here](https://github.com/Azure/azure-webjobs-sdk/blob/663a508e8a851629c26a51e7de3af36629dfd120/src/Microsoft.Azure.WebJobs.Protocols/JsonSerialization.cs). But it is not configurable. [Issue](https://github.com/Azure/azure-webjobs-sdk/issues/1639) created there. Upvotes: 0
2018/03/21
620
2,128
<issue_start>username_0: I have SQL tables with "score" columns. Sometimes that table will have hundreds of rows and sometimes it will have less than 10 rows. I need a SQL query that outputs the top 3 scores if there are less than 10 rows, or the top 10 scores if there are more than 10 scores in the table. I'm not sure how to do this in SQL, but something like this: ```sql SELECT CASE WHEN COUNT(*) < 10 THEN ( SELECT score FROM scores_table ORDER BY score DESC LIMIT 3 ) WHEN COUNT(*) > 10 THEN ( SELECT score FROM scores_table ORDER BY score DESC LIMIT 10 ) END ``` The above doesn't work but hopefully it conveys what I'm trying to get.<issue_comment>username_1: I think this does what you want: ``` ( SELECT `score` FROM `scores_table` ORDER BY `score` DESC LIMIT 3 ) UNION ALL ( SELECT `score` FROM `scores_table` WHERE (SELECT COUNT(*) FROM `scores_table`) >= 10 ORDER BY `score` DESC LIMIT 2, 7 ) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Try this query ! ``` SELECT `score` FROM `scores_table` WHERE COUNT(*) <= 10 ORDER BY `score` DESC TOP 3 UNION SELECT `score` FROM `scores_table` WHERE COUNT(*) < 10 ORDER BY `score` DESC TOP 10 ``` Upvotes: 1 <issue_comment>username_3: The question is interesting. As you selected the tag "MySQL", you may not be directly interested by the answer I propose, however someone may find it useful some day. The problem I see with the other two answers already posted is that they make use of "LIMIT" or "TOP", which are not SQL. The following query uses only standard SQL. The idea is to first fetch the third and tenth scores, then to fetch each row of the score table with a score higher than one of these. ```sql WITH RN(score, rn) AS ( SELECT score, row_number() OVER (ORDER BY score DESC) FROM score ), BOUND(bound) AS ( SELECT min(score) FROM RN WHERE rn IN (3, 10) ) SELECT score.* FROM score INNER JOIN BOUND ON score >= bound ORDER BY score DESC; ``` SQL fiddle: <http://sqlfiddle.com/#!17/b44b8/2/0> Upvotes: 1
2018/03/21
809
2,663
<issue_start>username_0: This is related to question : [String array to C++ function](https://stackoverflow.com/questions/49410992/string-array-to-c-function) Although everything is working fine now, the only thing I am not able to accomplish is to **tolower** the user input as I am getting an error : ### Function ``` bool lookupTerm(const std::string& term, const std::vector& possible\_names) { transform(term.begin(), term.end(), term.begin(), ::tolower); for (const std::string &possible\_name : possible\_names) { if (possible\_name.compare(term) == 0) return true; } return false; } ``` ### Parameters ``` const std::vector possible\_asterisk = { "star" , "asterisk" , "tilde"}; string term = "SoMeWorD"; ``` ### Error ``` In file included from /usr/include/c++/7.2.0/algorithm:62:0, from jdoodle.cpp:5: /usr/include/c++/7.2.0/bits/stl_algo.h: In instantiation of '_OIter std::transform(_IIter, _IIter, _OIter, _UnaryOperation) [with _IIter = __gnu_cxx::__normal_iterator >; \_OIter = \_\_gnu\_cxx::\_\_normal\_iterator >; \_UnaryOperation = int (\*)(int) throw ()]': jdoodle.cpp:40:64: required from here /usr/include/c++/7.2.0/bits/stl\_algo.h:4306:12: error: assignment of read-only location '\_\_result.\_\_gnu\_cxx::\_\_normal\_iterator >::operator\*()' \*\_\_result = \_\_unary\_op(\*\_\_first); ``` I know that transform should be receiving a string. How can I momentarily cast the **std::vector** to simply **string** so I can get that word to lowercase?<issue_comment>username_1: This is because `term` is `const` reference. Make a copy before converting it to lowercase: ``` bool lookupTerm(const std::string& term, const std::vector& possible\_names) { std::string lower(term); transform(lower.begin(), lower.end(), lower.begin(), ::tolower); for (const std::string &possible\_name : possible\_names) { if (possible\_name.compare(lower) == 0) return true; } return false; } ``` You could also achieve the same effect by removing `const`, and taking the parameter by value: ``` bool lookupTerm(std::string term, const std::vector& possible\_names) { ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: `std::transform` needs to be able to change the contents of whatever the third argument dereferences to. That does not work in your case since `term` is a `const` object. You can create function local object to store the transformed string. ``` std::string lowercaseTerm(term); transform(term.begin(), term.end(), lowercaseTerm.begin(), ::tolower); ``` and then use `lowercaseTerm` in the following line. ``` if (possible_name.compare(lowercaseTerm) == 0) ``` Upvotes: 1
2018/03/21
583
2,272
<issue_start>username_0: Say I have scope `S1` which has the module with the binding: ``` bind(Repository.class).to(RepositoryImpl.class).singletonInScope() ``` Then `S2` scope gets opened with `S1` as a parent (`S1 -> S2`) and `S2` defines the same binding (because it's independent and knows nothing of `S1`): ``` bind(Repository.class).to(RepositoryImpl.class).singletonInScope() ``` By default Toothpick overrides parent scope dependencies, so `S2` will have a new `RepositoryImpl` created. **Question**: Is there a way to reuse the one created in `S1` and ignore an `S2` binding? This requirement comes from the fact that sometimes there are *independent* application components which reside in different scopes and which share that `Repository` dependency. They know nothing of each other. These components can also be created in different order, depending on the scenario and use case. So the only rule which I want to impose is this: some component (it is unknown exactly which one) creates `Repository`, all which are created later in current *and* child scopes - reuse it.<issue_comment>username_1: To get early opened scope anywhere in your code you can just use ``` Scope s1Scope = Toothpick.openScope('s1-scope-name'); ``` In case S1 is parent scope of S2 you can do the same by using getParentScope() method ``` Scope s1Scope = s2Scope.getParentScope(); ``` And then just load required singleton from S1 scope ``` Repository s1Repository = s1Scope.getInstance(Repository.class); ``` If you want to do it in the S2 module you can simply do ``` bind(Repository.class).toProviderInstance(() -> Toothpick.openScope('s1-scope-name').getInstance(Repository.class)); ``` Upvotes: 2 <issue_comment>username_2: When you develop an app built from multi independant components with Toothpick, you may go to this direction : Every independant component, should own 2 toothpick modules. * one module that deals with internals dependencies (provided by the module itself) * one module that deals with externals dependencies (provided at integration level) In the second one, you will define the in and out dependencies, that will be connected to the others independant components, to build at the end an integrated system of componenet. Upvotes: 0
2018/03/21
521
2,014
<issue_start>username_0: I created two virtual networks in azure using the routeable private adress configurations vnet1: 172.16.10.0/24(vsubnet1) vnet2: 172.16.20.0/24(vsubnet2) I Created two virtual machines by connecting to the above vsubnets through NIC. Network security Group has been defined to allow all the traffic and no additional routes are created. How can I approach this connectivity between these two virtual machines without creating VPN/Express route as given in Azure [documentation](https://azure.microsoft.com/en-in/blog/vnet-to-vnet-connecting-virtual-networks-in-azure-across-different-regions/) In Openstack we have the option of creating the interfaces that connect to ports of multiple virtual networks where as in azure, the NIC configuration is limited only to one virtual network which vm connects to.<issue_comment>username_1: To get early opened scope anywhere in your code you can just use ``` Scope s1Scope = Toothpick.openScope('s1-scope-name'); ``` In case S1 is parent scope of S2 you can do the same by using getParentScope() method ``` Scope s1Scope = s2Scope.getParentScope(); ``` And then just load required singleton from S1 scope ``` Repository s1Repository = s1Scope.getInstance(Repository.class); ``` If you want to do it in the S2 module you can simply do ``` bind(Repository.class).toProviderInstance(() -> Toothpick.openScope('s1-scope-name').getInstance(Repository.class)); ``` Upvotes: 2 <issue_comment>username_2: When you develop an app built from multi independant components with Toothpick, you may go to this direction : Every independant component, should own 2 toothpick modules. * one module that deals with internals dependencies (provided by the module itself) * one module that deals with externals dependencies (provided at integration level) In the second one, you will define the in and out dependencies, that will be connected to the others independant components, to build at the end an integrated system of componenet. Upvotes: 0
2018/03/21
670
2,989
<issue_start>username_0: I know this must be the most simple question ever, but as someone completely new to AOP i cant get my head around it. 1. What is the difference between an Aspect and a Method? within the documentation its mentioned: > > Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects. > > > "the modularizations of concerns" sounds to me like just making more methods for more specific procedures, 2. is it? if not how any why is it different? "that cut across multiple types and objects" sounds to me like these methods are global and able to be accessed from other classes, I'm near certain that this isn't correct. However the mention of Types and objects separately also has me a little confused here too. 3. When objects are mentioned are these just POJO's? 4. what is meant by Types if these aren't just objects? Thanks in advance<issue_comment>username_1: Aspect is adding a behavior to a method (or all the classes of a method) through configuration instead of programmatically. The configuration can be done in XML, or anything else but the best example is with annotations, like for example you can have a method : ``` @Audit public Integer doSomething(String parameter) { //Something is happening here } ``` Simply adding the `@Audit` annotation will add the behavior of logging the input parameters, output value and the time of execution. And you do that by creating an interceptor and having your interceptor applied to the methods that have the annotation. This is just an example, you can implement transactions, caching, circuit breaker and a lot of other things with that. In your interceptor you have a normal method that take as parameter a ProceedingJoinPoint (assuming you are using AspectJ) which contains information about the method and on which you can call proceed() to actually call the method, this allow you to stuff before and after the method call, potentially changing arguments or return value and even potentially not calling the method at all (in the case of caching for example). The big benefit of aspects is that you write your interceptor once, and then it's very easy to add the behavior to any method you want through configuration. P.S. : When they say types and objects, I think you should understand it as interfaces and implementations, like you could add the behavior to all implementations of List or just to ArrayList. Upvotes: 2 [selected_answer]<issue_comment>username_2: An **Aspect** is the association of a **Concern**, a **Pointcut** and a **Joinpoint**. * The implementation of a cross-cutting concern is called the **Concern** * The well defined location within a class where a concern is going to be attached is the **Joinpoint** * The place where the joinpoint(s) are specified, either through configuration or code, is the **Pointcut** A **Method** is a **Joinpoint**. **Objects** are instances of **Types**. Upvotes: 2
2018/03/21
755
2,961
<issue_start>username_0: This is my code: ``` declare @maxsnap table (sita varchar(10), date date, SNAPSHOT_DATE date) insert into @maxsnap select sita, date, max(SNAPSHOT_DATE) snapshot from [UKRMC].[dbo].[Roll_forecast] where date between '2018-03-21' and '2018-05-31' group by sita, date select roll.DATE, roll.SITA, contacts.rooms, roll.SEGMENT, roll.RNS from [UKRMC].[dbo].[Roll_forecast] roll join [UKRMC].[dbo].[Contacts] contacts on contacts.SITA = roll.SITA join @maxsnap snap on roll.DATE = snap.date and roll.SITA = snap.sita and roll.SNAPSHOT_DATE = snap.snapshot where roll.date between '2018-03-21' and '2018-05-31' ``` The error I am getting is > > Invalid column name 'snapshot' > > > when I join the `@maxnsap` table variable. But that column does exist!<issue_comment>username_1: Aspect is adding a behavior to a method (or all the classes of a method) through configuration instead of programmatically. The configuration can be done in XML, or anything else but the best example is with annotations, like for example you can have a method : ``` @Audit public Integer doSomething(String parameter) { //Something is happening here } ``` Simply adding the `@Audit` annotation will add the behavior of logging the input parameters, output value and the time of execution. And you do that by creating an interceptor and having your interceptor applied to the methods that have the annotation. This is just an example, you can implement transactions, caching, circuit breaker and a lot of other things with that. In your interceptor you have a normal method that take as parameter a ProceedingJoinPoint (assuming you are using AspectJ) which contains information about the method and on which you can call proceed() to actually call the method, this allow you to stuff before and after the method call, potentially changing arguments or return value and even potentially not calling the method at all (in the case of caching for example). The big benefit of aspects is that you write your interceptor once, and then it's very easy to add the behavior to any method you want through configuration. P.S. : When they say types and objects, I think you should understand it as interfaces and implementations, like you could add the behavior to all implementations of List or just to ArrayList. Upvotes: 2 [selected_answer]<issue_comment>username_2: An **Aspect** is the association of a **Concern**, a **Pointcut** and a **Joinpoint**. * The implementation of a cross-cutting concern is called the **Concern** * The well defined location within a class where a concern is going to be attached is the **Joinpoint** * The place where the joinpoint(s) are specified, either through configuration or code, is the **Pointcut** A **Method** is a **Joinpoint**. **Objects** are instances of **Types**. Upvotes: 2
2018/03/21
826
3,370
<issue_start>username_0: I am trying to ensure that my error trapping is working correctly but not sure I understand the proper procedure for handling an error that was found in another module. If I had in module1 ``` Sub test() . . . . 'macro code Part1 SAtext = SAdata(SApage, "A") . . . . . 'macro code part2 my5Error: ASSoffice = Empty prv1 = Empty TNT = Empty End sub ``` I would want the macro code part1 to run and call the SAdata function. When the function runs, I want it to run the function code part1 and then check if err.number = 5 will occur. If it doesn't then the error handling is reset, but if it does I want it to skip the 'function code part2' section and run the code at myBlank: This part seems to work okay. ``` Function SAdata(SApage, "A") . . . . Function code part1 On Error Resume Next myresponse = Mid(xmlHTTP.responseText, InStr(1, xmlHTTP.responseText, "Ref No.", vbTextCompare), Len(xmlHTTP.responseText)) If Err.Number = 5 Then GoTo myBlank On Error GoTo 0 . . . . . function code part2 myBlank: Set xmlHTTP = Nothing Set oDoc = Nothing Set objData = Nothing On Error GoTo 0 End Function ``` After the error handling is complete for the function, how would I identify that an error had occurred in the function and to skip the 'macro code part2' section?<issue_comment>username_1: Aspect is adding a behavior to a method (or all the classes of a method) through configuration instead of programmatically. The configuration can be done in XML, or anything else but the best example is with annotations, like for example you can have a method : ``` @Audit public Integer doSomething(String parameter) { //Something is happening here } ``` Simply adding the `@Audit` annotation will add the behavior of logging the input parameters, output value and the time of execution. And you do that by creating an interceptor and having your interceptor applied to the methods that have the annotation. This is just an example, you can implement transactions, caching, circuit breaker and a lot of other things with that. In your interceptor you have a normal method that take as parameter a ProceedingJoinPoint (assuming you are using AspectJ) which contains information about the method and on which you can call proceed() to actually call the method, this allow you to stuff before and after the method call, potentially changing arguments or return value and even potentially not calling the method at all (in the case of caching for example). The big benefit of aspects is that you write your interceptor once, and then it's very easy to add the behavior to any method you want through configuration. P.S. : When they say types and objects, I think you should understand it as interfaces and implementations, like you could add the behavior to all implementations of List or just to ArrayList. Upvotes: 2 [selected_answer]<issue_comment>username_2: An **Aspect** is the association of a **Concern**, a **Pointcut** and a **Joinpoint**. * The implementation of a cross-cutting concern is called the **Concern** * The well defined location within a class where a concern is going to be attached is the **Joinpoint** * The place where the joinpoint(s) are specified, either through configuration or code, is the **Pointcut** A **Method** is a **Joinpoint**. **Objects** are instances of **Types**. Upvotes: 2
2018/03/21
2,273
8,669
<issue_start>username_0: I'm doing some project and I'm stuck ... I'm doing something wrong, probably with AsyncTask and I have no idea what to fix and how .... there is code I have right now. ReviewData.class ``` public class ReviewData implements Parcelable { private String mAuthor, mContent; public ReviewData(String author, String content) { this.mAuthor = author; this.mContent = content; } private ReviewData(Parcel in) { mAuthor = in.readString(); mContent = in.readString(); } public static final Creator CREATOR = new Creator() { @Override public ReviewData createFromParcel(Parcel in) { return new ReviewData(in); } @Override public ReviewData[] newArray(int size) { return new ReviewData[size]; } }; //Getter method for review author public String getAuthor() { return mAuthor; } //Setter method for review author public void setAuthor(String author) { this.mAuthor = author; } //Getter method for review content public String getContent() { return mContent; } //Setter method for review content public void setContent(String content) { this.mContent = content; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mAuthor); dest.writeString(mContent); } ``` } ReviewAdapter.class ``` public class ReviewAdapter extends RecyclerView.Adapter { private ArrayList mReviewList; private Context mContext; public ReviewAdapter(Context context, ArrayList reviewList) { this.mContext = context; this.mReviewList = reviewList; } @Override public ReviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { mContext = parent.getContext(); View view = LayoutInflater.from(mContext).inflate(R.layout.review\_item\_list, parent, false); view.setFocusable(true); return new ReviewViewHolder(view); } @Override public void onBindViewHolder(final ReviewViewHolder holder, int position) { if(mReviewList != null) { ReviewData reviewData = mReviewList.get(position); holder.reviewAuthor.setText(reviewData.getAuthor()); holder.reviewContent.setText(reviewData.getContent()); } } @Override public long getItemId(int position) { return position; } @Override public int getItemCount() { if(mReviewList == null) { return 0; } else { return mReviewList.size(); } } public void setReviewList(ArrayList reviewList) { if(reviewList != null) { mReviewList = new ArrayList<>(reviewList); } notifyDataSetChanged(); } public class ReviewViewHolder extends RecyclerView.ViewHolder { TextView reviewAuthor; TextView reviewContent; public ReviewViewHolder(View itemView) { super(itemView); reviewAuthor = itemView.findViewById(R.id.review\_author); reviewContent = itemView.findViewById(R.id.review\_content); } } ``` } NetworkUtils.class (but only code for Review url builder, for other thing works perfectly). PS. this parse is written as API documentation said ... it should be someurl/movie/{id}/reviews ``` //URL builder for reviews public static URL buildReviewUrl(String id) { Uri builtUri = Uri.parse(BASE_MOVIE_URL + id + REVIEW).buildUpon() .appendQueryParameter(QUERY_API_KEY, API_KEY) .build(); URL url = null; try { url = new URL(builtUri.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } return url; } ``` JsonData. class (also, only for Reviews, for other works perfectly...) ``` //JSON for Review public static ArrayList getReviewFromJson(String json) throws JSONException { ArrayList listOfReviews = new ArrayList<>(); try { JSONObject reviews = new JSONObject(json); JSONArray reviewsArray = reviews.getJSONArray(QUERY\_RESULTS); for(int i = 0; i < reviewsArray.length(); i++) { JSONObject jsonReview = reviewsArray.getJSONObject(i); String author = jsonReview.optString(REVIEW\_AUTHOR); String content = jsonReview.optString(REVIEW\_CONTENT); ReviewData reviewData = new ReviewData(author, content); listOfReviews.add(reviewData); } } catch(JSONException e) { e.printStackTrace(); Log.e("ReviewJson", "JSON Review Error"); } return listOfReviews; } ``` ReviewAsyncTask.class ``` public class ReviewAsyncTask extends AsyncTask> { private ReviewData mReviewData; public interface ReviewResponse { void finished(ArrayList output); } private ReviewResponse reviewResponse = null; public ReviewAsyncTask(ReviewResponse reviewResponse) { this.reviewResponse = reviewResponse; } @Override protected ArrayList doInBackground(String... strings) { String rawData = ""; ArrayList reviewList = new ArrayList<>(); try { rawData = NetworkUtils.getResponseFromHttpRequest(NetworkUtils .buildReviewUrl(String.valueOf(mReviewData))); reviewList = JsonData.getReviewFromJson(rawData); } catch (IOException e) { e.printStackTrace(); Log.e("ReviewAsyncTask", "Error in ReviewAsyncTask"); } catch (JSONException e) { e.printStackTrace(); Log.e("JSONAsync", "JSON problem"); } return reviewList; } @Override protected void onPostExecute(ArrayList reviewData) { reviewResponse.finished(reviewData); } ``` } and MovieDetails activity (everything works fine except from the comment recycle review to next comment. ``` public class MovieDetails extends AppCompatActivity implements ReviewAsyncTask.ReviewResponse { private final static String BASE_URL = "http://image.tmdb.org/t/p/"; private final static String SIZE = "w185/"; private ArrayList mReviewList; private ReviewAdapter mReviewAdapter; @BindView(R.id.poster\_detail) ImageView mMoviePoster; @BindView(R.id.title\_detail) TextView mMovieTitle; @BindView(R.id.release\_date) TextView mReleaseDate; @BindView(R.id.average\_vote) TextView mAverageVote; @BindView(R.id.synopsis) TextView mSynopsis; @BindView(R.id.review\_recycler) RecyclerView mReviewRecycle; Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity\_movie\_details); ButterKnife.bind(this); displayMovieDetail(); //Review RecycleView mReviewList = new ArrayList<>(); mReviewAdapter = new ReviewAdapter(this, mReviewList); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); mReviewRecycle.setLayoutManager(layoutManager); mReviewRecycle.setHasFixedSize(true); mReviewRecycle.setAdapter(mReviewAdapter); } @Override public void finished(ArrayList output) { ReviewAsyncTask reviewAsyncTask = new ReviewAsyncTask(this); reviewAsyncTask.execute(); } /\* Method for displaying the info about movies in activity details \* @param mMoviePoster sets the movie poster \* @param mMovieTitle sets original title of the movie \* @param mReleaseDate sets release date of the movie \* @param mAverageVote sets average rating grade of the movie \* @param mSynopsis sets plot of the movie \*/ private void displayMovieDetail() { int idMovie = (Integer) getIntent().getExtras().get(getString(R.string.movie\_id)); List movieList; movieList = getIntent().getParcelableArrayListExtra(getString(R.string.movie\_lsit)); MovieData movieData = movieList.get(idMovie); Picasso.with(mContext).load(BASE\_URL + SIZE + movieData.getPoster()).into(mMoviePoster); mMovieTitle.setText(movieData.getTitle()); mReleaseDate.setText(movieData.getReleaseDate()); mAverageVote.setText(Double.toString(movieData.getRating())); mSynopsis.setText(movieData.getSynopsis()); } ``` } P.S. I would share github link but I should give you my personal API key. :(<issue_comment>username_1: You need to start the `AsyncTask` in `onCreate()` (like you did before) and in `finished()` you take the results and add them to the Adapter's data list. Finally, don't forget to call `notifyDatasetChanged()`. ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_details); // skipping some lines of code here... mReviewRecycle.setAdapter(mReviewAdapter); ReviewAsyncTask reviewAsyncTask = new ReviewAsyncTask(this); reviewAsyncTask.execute(); } @Override public void finished(ArrayList output) { mReviewList.addAll(output); mReviewAdapter.notifyDatasetChanged(); } ``` (Please note that I skipped null checks and error handling for brevity's sake) Upvotes: 1 <issue_comment>username_2: 1. In MovieDetails onCreate retrieve current movie ID like you do in displayMovieDetail. 2. Send that ID to ReviewAsyncTask (you'll need to modify constructor of ReviewAsyncTask) 3. Retrieve id in ReviewAsyncTask, save it as member variable, and then in doInBackground method send that id to buildReviewUrl as an argument. Upvotes: 0
2018/03/21
529
2,055
<issue_start>username_0: I'm a pretty decent wordpress coder. Maybe I'm being stupid, but I can't work out how to edit the Divi blog module layout... basically the `archive.php` for the Divi theme - it doesn't seem to have one. What I want to do is change the HTML of the blog when it added to the Divi page builder as a module... How do I go about editing the code for that? (I've searched everywhere and they all talk about CSS changes, but I want to edit the HTML that is output as well). Thanks! EDIT: To clarify my question, I'm looking for specific help with DIVI. I have a good understanding of Wordpress, and know the usual hierarchy structure. My question for Divi is more to do with the blog module that you add to the Page Builder - that's the bit I want to edit the HTML output of. All google searches (and stackoverflow!) point me to CSS changes only, but I want to edit the HTML output of that page builder (Which I'm guessing is using a shortcode)<issue_comment>username_1: There is usually a page (under pages in Wordpress) that has an "Archive" template. Check it out and edit that template. [![enter image description here](https://i.stack.imgur.com/ZdLrf.jpg)](https://i.stack.imgur.com/ZdLrf.jpg) You can check more about page templates (and maybe even creating your own, if you wish) here - <https://www.elegantthemes.com/blog/resources/an-introduction-to-wordpress-page-templates> Upvotes: 1 <issue_comment>username_2: 1. Make a copy of the index.php file from the Divi parent theme 2. Paste the file into your child theme directory 3. Change the name of the file to archive.php 4. Modify the html/php as you need That should work :) Upvotes: 2 <issue_comment>username_3: You can use Divi Builder for categories pages or custom categories pages. You simply have to go in Divi > Theme Builder. Then, go into a new model, and select the archive page you need. Finally, you can add custom content within the builder into the header, body or footer. That content will be available in the archive pages you selected. Upvotes: 0
2018/03/21
515
1,694
<issue_start>username_0: Why friend class need not forward declaration but member function need? friend class: ``` class String0{ friend class String; private: int size = 0; string s; }; class String { public: string combine(const string &s1); private: int size = 0; string s; }; ``` member friend: ``` class String { public: string combine(const string &s1); //why need this? private: int size = 0; string s; }; class String0 { friend string String::combine(const string &); }; String String::combine(const string &s1){...} ``` Classes and nonmember functions need not have been declared before they are used in a friend declaration. But why member function need?<issue_comment>username_1: A friend class/function declaration IS a declaration in itself and forward-declares the class/function. You got that right. Now if you could forward declare a member function of `class A` as a `friend` in `class B`, that means you are changing the interface of `class A`. Imagine I did ``` class foo { public: friend void std::vector::fun(); }; ``` Am I adding a function to `std::vector`? Upvotes: 3 [selected_answer]<issue_comment>username_2: Standard gives an example: > > **13.3 Friends** [class.friend] 3/ > > > > ``` > class C; > typedef C Ct; > > class X1 { > friend C; // OK: class C is a friend > }; > > class X2 { > friend Ct; // OK: class C is a friend > friend D; // error: no type-name D in scope > friend class D; // OK: elaborated-type-specifier declares new class > }; > > ``` > > `friend class D` both forward declares `class D` and a friend relationship with it. Upvotes: 1
2018/03/21
1,226
3,996
<issue_start>username_0: All, To replace one string in one particular column I have done this and it worked fine: ``` dataUS['sec_type'].str.strip().str.replace("LOCAL","CORP") ``` I would like now to replace multiple strings with one string say replace `["LOCAL", "FOREIGN", "HELLO"]` with `"CORP"` How can make it work? the code below didn't work ``` dataUS['sec_type'].str.strip().str.replace(["LOCAL", "FOREIGN", "HELLO"], "CORP") ```<issue_comment>username_1: `replace` can accept `dict` , os we just create a dict for those values need to be replaced ``` dataUS['sec_type'].str.strip().replace(dict(zip(["LOCAL", "FOREIGN", "HELLO"], ["CORP"]*3)),regex=True) ``` Info of the dict ``` dict(zip(["LOCAL", "FOREIGN", "HELLO"], ["CORP"]*3)) Out[585]: {'FOREIGN': 'CORP', 'HELLO': 'CORP', 'LOCAL': 'CORP'} ``` The reason why you receive the error , [str.replace](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html) is different from [replace](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html) Upvotes: 4 <issue_comment>username_2: Try: ``` dataUS.replace({"sec_type": { 'LOCAL' : "CORP", 'FOREIGN' : "CORP"}}) ``` Upvotes: 0 <issue_comment>username_3: You can perform this task by forming a |-separated string. This works because [`pd.Series.str.replace`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html) accepts regex: > > Replace occurrences of pattern/regex in the Series/Index with some > other string. Equivalent to str.replace() or re.sub(). > > > This avoids the need to create a dictionary. ``` import pandas as pd df = pd.DataFrame({'A': ['LOCAL TEST', 'TEST FOREIGN', 'ANOTHER HELLO', 'NOTHING']}) pattern = '|'.join(['LOCAL', 'FOREIGN', 'HELLO']) df['A'] = df['A'].str.replace(pattern, 'CORP') # A # 0 CORP TEST # 1 TEST CORP # 2 ANOTHER CORP # 3 NOTHING ``` Upvotes: 6 [selected_answer]<issue_comment>username_4: **Function to replace multiple values in pandas Series:** ``` def replace_values(series, to_replace, value): for i in to_replace: series = series.str.replace(i, value) return series ``` Hope this helps someone Upvotes: 2 <issue_comment>username_5: The answer of @username_2 is very neat but does not allow for substrings. With a small change however, it does. 1. Use a replacement dictionary because it makes it much more generic 2. Add the keyword argument `regex=True` to `Series.replace()` (not `Series.str.replace`) This does two things actually: It changes your replacement to regex replacement, which is much more powerful but you will have to escape special characters. Beware for that. Secondly it will make the replace work on substrings instead of the entire string. Which is really cool! ``` replacement = { "LOCAL": "CORP", "FOREIGN": "CORP", "HELLO": "CORP" } dataUS['sec_type'].replace(replacement, regex=True) ``` **Full code example** ``` dataUS = pd.DataFrame({'sec_type': ['LOCAL', 'Sample text LOCAL', 'Sample text LOCAL sample FOREIGN']}) replacement = { "LOCAL": "CORP", "FOREIGN": "CORP", "HELLO": "CORP" } dataUS['sec_type'].replace(replacement, regex=True) ``` **Output** ``` 0 CORP 1 CORP 2 Sample text CORP 3 Sample text CORP sample CORP Name: sec_type, dtype: object ``` Upvotes: 4 <issue_comment>username_6: @JJP answer is a good one if you have a long list. But if you have just two or three then you can simply use the '|' within the pattern. Make sure to add `regex=True` parameter. Clearly `.str.strip()` is not a requirement but is good practise. ``` import pandas as pd df = pd.DataFrame({'A': ['LOCAL TEST', 'TEST FOREIGN', 'ANOTHER HELLO', 'NOTHING']}) df['A'] = df['A'].str.strip().str.replace("LOCAL|FOREIGN|HELLO", "CORP", regex=True) ``` output ``` A 0 CORP TEST 1 TEST CORP 2 ANOTHER CORP 3 NOTHING ``` Upvotes: 2
2018/03/21
691
2,623
<issue_start>username_0: I currently use Akamai as a CDN for my app, which is served over multiple subdomains. I recently realized that Akamai is caching CORS requests the same, regardless of the origin from which they were requested. This of course causes clients that make requests with a different `Origin` than the cached response to fail (since they have a different response header for `Access-Control-Allow-Origin` than they should) Many suggest supplying the `Vary: Origin` request header to avoid this issue, but [according to Akamai's docs](https://control.akamai.com/dl/rd/propmgr/PropMgr_Left.htm#CSHID=1073|StartTopic=Content%2FRemove-Vary.htm|SkinName=Akamai_skin) and [this Akamai community post](https://community.akamai.com/thread/4936-does-akamai-cdn-support-vary-origin), this isn't supported by Akamai. How can I force Akamai to cache things uniquely by `Origin` if an `Origin` header is present in the request?<issue_comment>username_1: I did some research, and it appears this can be done by adding a new `Rule` in your Akamai config, like so: Note that if you do this - REMEMBER - this changes your cache key at Akamai, so anything that was cached before is essentially NOT CACHED anymore! Also, as noted in the yellow warning labels, this can make it harder to force reset your cache using Akamai's url purging tools. You could remove the `If` block, and just include `Origin` header as a similar `Cache ID Modification` rule too, if you were ok with changing the cache key for all your content that this rule would apply to. So in short, try this out on a small section of your site first! More details can be found [in this related post on Stack Overflow](https://stackoverflow.com/a/49262513/26510) [![enter image description here](https://i.stack.imgur.com/nHaDS.png)](https://i.stack.imgur.com/nHaDS.png) Upvotes: 3 [selected_answer]<issue_comment>username_2: We have hosted an API on Akamai. I had similar requirement, but we wanted to use the cached response on Akamai for all the touchpoints. But without CORS settings, it used to cache the response from first origin, and then keep it in cache, and the following requests from other touch points use to fail due to cached origin header. We solved the problem with using API Gateway feature provided by Akamai. You can find it under API Definition. Custom cache parameters can also be defined here. Please see the screen shot for the CORS settings. Now it cached the response from backend and serve to the requester as per the allowed origin list. [CORS Setting in API Definition](https://i.stack.imgur.com/i04Tv.png) Upvotes: 1
2018/03/21
738
2,542
<issue_start>username_0: I'm trying to learn machine learning using Octave. OS: Mac, High Sierra 10.13.3 GNU Octave version: 3.8.0 ``` t = [0: 0.01: 0.98]; y1 = sin(2*pi*4*t); y2 = sin(2*pi*4*t); plot(t, y1); hold on; plot(t, y2, 'r'); figure(1); plot(t,y1); ``` The first time I tried ran the last line I got: "Qt terminal communication error: select() error 9 Bad file descriptor" After this I got a broken pipe error, I thought I need to plot both the graphs again before trying "figure(1); plot(y,t1);". But, it didn't work. Checked whois and printed the values of y1, y2 and t; they do exist. So, my questions are: 1. Why am I not able to plot the graphs? 2. How do I solve broken pipe error? 3. How to solve the Qt terminal communication error? [![Terminal image](https://i.stack.imgur.com/Z6Tm5.jpg)](https://i.stack.imgur.com/Z6Tm5.jpg)<issue_comment>username_1: I did some research, and it appears this can be done by adding a new `Rule` in your Akamai config, like so: Note that if you do this - REMEMBER - this changes your cache key at Akamai, so anything that was cached before is essentially NOT CACHED anymore! Also, as noted in the yellow warning labels, this can make it harder to force reset your cache using Akamai's url purging tools. You could remove the `If` block, and just include `Origin` header as a similar `Cache ID Modification` rule too, if you were ok with changing the cache key for all your content that this rule would apply to. So in short, try this out on a small section of your site first! More details can be found [in this related post on Stack Overflow](https://stackoverflow.com/a/49262513/26510) [![enter image description here](https://i.stack.imgur.com/nHaDS.png)](https://i.stack.imgur.com/nHaDS.png) Upvotes: 3 [selected_answer]<issue_comment>username_2: We have hosted an API on Akamai. I had similar requirement, but we wanted to use the cached response on Akamai for all the touchpoints. But without CORS settings, it used to cache the response from first origin, and then keep it in cache, and the following requests from other touch points use to fail due to cached origin header. We solved the problem with using API Gateway feature provided by Akamai. You can find it under API Definition. Custom cache parameters can also be defined here. Please see the screen shot for the CORS settings. Now it cached the response from backend and serve to the requester as per the allowed origin list. [CORS Setting in API Definition](https://i.stack.imgur.com/i04Tv.png) Upvotes: 1
2018/03/21
2,045
6,492
<issue_start>username_0: I've made a dropdown list with checkboxes from scratch since the project on which I am working on has to be supported by older version of IE. And the result is pretty good except for one part. when I click on the drop down list every other element of the page gets lowered down. The behaviour that I'm trying to achieve is the same of an element select where it will go on top of any other element of the page. Is there a CSS property (or pure JS) that will let me do that. Here is the code: ```js var checkList = document.getElementById('list1'); var items = document.getElementById('items'); document.getElementById('anchor').onclick = function(evt) { if (items.className.indexOf("visible") !== -1) { items.className = ""; items.style.display = "none"; } else { items.className = " visible"; items.style.display = "block"; } } ``` ```css .dropdown-check-list { display: inline-block; } .dropdown-check-list .anchor { position: relative; cursor: pointer; display: inline-block; padding: 5px 50px 5px 10px; border: 1px solid #ccc; } .dropdown-check-list .anchor:after { position: absolute; content: ""; border-left: 2px solid black; border-top: 2px solid black; padding: 5px; right: 10px; top: 20%; transform: rotate(-135deg); } .dropdown-check-list .anchor:active:after { right: 8px; top: 21%; } .dropdown-check-list ul { padding: 2px; display: none; margin: 0; border: 1px solid #ccc; border-top: none; } .dropdown-check-list ul li { list-style: none; } ``` ```html Type * Choice 3 * Choice 2 * Choice 1 this shou ============ ```<issue_comment>username_1: For the div you can use z-index: 2 and the other elements z-index: 1 The highest value is in the front Upvotes: 0 <issue_comment>username_2: You can set `position: absolute` on `items` to achieve that: ``` .items { position: absolute; background: #ffffff; } ``` Upvotes: 0 <issue_comment>username_3: Use `position:absolute` for the checklist...it will remove the element from the flow of document resulting does not affect on other elements... Also use `position:relative` to the parent container `.dropdown-check-list` ```js var checkList = document.getElementById('list1'); var items = document.getElementById('items'); document.getElementById('anchor').onclick = function(evt) { if (items.className.indexOf("visible") !== -1) { items.className = ""; items.style.display = "none"; } else { items.className = " visible"; items.style.display = "block"; } } ``` ```css .dropdown-check-list { display: inline-block; position: relative; } .dropdown-check-list .anchor { position: relative; cursor: pointer; display: inline-block; padding: 5px 50px 5px 10px; border: 1px solid #ccc; } .dropdown-check-list .anchor:after { position: absolute; content: ""; border-left: 2px solid black; border-top: 2px solid black; padding: 5px; right: 10px; top: 20%; transform: rotate(-135deg); } .dropdown-check-list .anchor:active:after { right: 8px; top: 21%; } .dropdown-check-list ul { padding: 2px; display: none; margin: 0; border: 1px solid #ccc; border-top: none; position: absolute; left: 0; right: 0; background: #fff; top: 100%; } .dropdown-check-list ul li { list-style: none; } ``` ```html Type * Choice 3 * Choice 2 * Choice 1 this shou ============ ``` Upvotes: 2 [selected_answer]<issue_comment>username_4: My humble contribution : ```js var addButton = document.getElementById("add"); addButton.onclick = addDropdown; for (var i = 0; i < 8; i++) { addDropdown.call(addButton); } document.addEventListener("click", function (ev) { var el = ev.target; if (hasClass(el, "dropdown")) { let list = closestDropdownList(el); if (hasClass(el, "active")) { list.style.display = "none"; removeClass(el, "active"); } else { var t = el.offsetTop; var l = el.offsetLeft; var h = el.offsetHeight; list.style.left = l + "px"; list.style.top = t + h + "px"; list.style.display = "block"; addClass(el, "active"); } } }); document.addEventListener("blur", function (ev) { var el = ev.target; if (hasClass(el, "dropdown")) { let list = closestDropdownList(el); list.style.display = "none"; removeClass(el, "active"); } }, true); function addDropdown () { var els = []; var el = this; var parent = this.parentNode; while (!hasClass(el, "dropdown")) { el = el.previousSibling; els.push(el.cloneNode(true)); } while (els.length > 0) { parent.insertBefore(els.pop(), this); } } function hasClass (el, name) { if (!el.getAttribute) { return false; } else { var attr = el.getAttribute("class"); attr = " " + attr + " "; name = " " + name + " "; return attr.indexOf(name) >= 0; } } function removeClass (el, name) { var attr = el.getAttribute("class"); attr = " " + attr + " "; name = " " + name + " "; attr = attr.replace(name, " "); attr = attr.slice(1, -1); el.setAttribute("class", attr); } function addClass (el, name) { var attr = el.getAttribute("class"); attr += " " + name; el.setAttribute("class", attr); } function closestFollowing (el, predicate) { while ((el = el.nextSibling) && !predicate(el)); return el; } function closestDropdownList (el) { return closestFollowing(el, function (sibling) { return hasClass(sibling, "dropdown-list"); }); } ``` ```css .dropdown { margin-bottom: .5em; } .dropdown:after { content: ""; margin-left: .4em; display: inline-block; vertical-align: middle; border-top: 5px solid black; border-left: 5px solid transparent; border-right: 5px solid transparent; border-bottom: 0px; } .dropdown-list { border: 1px solid black; position: absolute; background: white; display: none; padding: .2em; margin: 0; } .dropdown-list li { list-style: none; cursor: pointer; padding: .25em; } .dropdown-list li:hover { background: #ddd; } ``` ```html Choose * Option A * Option B * Option C Add dropdown Hello World ! Hello World ! Hello World ! ``` Event delegation for "focus" and "blur" : [quirksmode.org](https://www.quirksmode.org/blog/archives/2008/04/delegating_the.html). Upvotes: 1
2018/03/21
456
1,515
<issue_start>username_0: ``` file = open(r'd:\holiday_list.txt', 'w') date = '' while(date != '0'): date = input('\nEnter Date (YYYYMMDD) : ') date = date[:4] + '-' + date[4:6] + '-' + date[5:] file.write(date) print('Job Done!') file.close() ``` This program is supposed to take dates (eg:20112016) as input and write it to a file. The problem is the program does not exit the while loop. If i enter a 0, it prompts me to enter another date.<issue_comment>username_1: You have your check in the wrong place: you manipulate the date as soon as you read it in, and the result is no longer `'0'` when you get back to the top of the loop. Try this: ``` date = input('\nEnter Date (YYYYMMDD) : ') while(date != '0'): date = date[:4] + '-' + date[4:6] + '-' + date[5:] file.write(date) date = input('\nEnter Date (YYYYMMDD) : ') ``` ANother check is the most basic of debugging: put in a `print` command to show *exactly* what you read in. Perhaps something like ``` print("date is ||", date"||") ``` The vertical bars will show any leading or trailing white space, such as the newline character. (Get rid of that with the `strip` method.) Upvotes: 2 <issue_comment>username_2: An alternative solution to username_1's is to use an `if` statement with a `break`: ``` while(True): date=input('\nEnter Date (YYYYMMDD) : ') if(date=='0'): break ...#your work here ``` This way you don't have to have an additional input outside the loop. Upvotes: 0
2018/03/21
425
1,480
<issue_start>username_0: Is it possible to convert this subquery to join? ``` SELECT `news`.`newsId`, (SELECT `comments`.`text` FROM `comments` WHERE `comments`.`newsId` = `news`.`newsId` order by `comments`.`date` desc limit 1) FROM `news` , `comments` where `news`.`newsId` = `comments`.`newsId` GROUP BY `news`.`newsId` order by news.date desc; ```<issue_comment>username_1: You have your check in the wrong place: you manipulate the date as soon as you read it in, and the result is no longer `'0'` when you get back to the top of the loop. Try this: ``` date = input('\nEnter Date (YYYYMMDD) : ') while(date != '0'): date = date[:4] + '-' + date[4:6] + '-' + date[5:] file.write(date) date = input('\nEnter Date (YYYYMMDD) : ') ``` ANother check is the most basic of debugging: put in a `print` command to show *exactly* what you read in. Perhaps something like ``` print("date is ||", date"||") ``` The vertical bars will show any leading or trailing white space, such as the newline character. (Get rid of that with the `strip` method.) Upvotes: 2 <issue_comment>username_2: An alternative solution to username_1's is to use an `if` statement with a `break`: ``` while(True): date=input('\nEnter Date (YYYYMMDD) : ') if(date=='0'): break ...#your work here ``` This way you don't have to have an additional input outside the loop. Upvotes: 0
2018/03/21
457
1,585
<issue_start>username_0: How can I copy an array so that it copies into each cell going down Column F, instead of going across a certain row, like I have in my code now. In this case it's row "7". How can I do this and start at a certain cell, let's say F3. I am currently using ExcelJS, but would be open to try other things. **Index.Js** ``` var Excel = require('exceljs'); var captureNames = [1,2,3,A,B,C]; workbook.xlsx.readFile("X:\\TESTING_DATA\\eclipse-database\\myExcelFile.xlsx") .then(function() { var sheet = workbook.addWorksheet('My Sheets'); var worksheet = workbook.getWorksheet("My Sheets"); var row = worksheet.getRow(7); row.values = captureNames; return workbook.xlsx.writeFile("X:\\TESTING_DATA\\eclipse-database\\myExcelFile.xlsx"); }) ``` **What I get now** [![enter image description here](https://i.stack.imgur.com/gmB97.png)](https://i.stack.imgur.com/gmB97.png) **What I want** [![enter image description here](https://i.stack.imgur.com/SPjtg.png)](https://i.stack.imgur.com/SPjtg.png)<issue_comment>username_1: Didn't test because of lack of example file, but you should do something similar: ``` captureNames.forEach(function(name, i) { worksheet.getCell('F' + (3 + i)).value = name }) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Just had to add a formula like this, thanks @dotsu ! ``` captureNames.forEach(function(name, i) { worksheet.cell('F' + (3 + i)).value(name); }) ``` Upvotes: 1
2018/03/21
236
834
<issue_start>username_0: Im trying to save form input after submitting the form, I tried this: ``` public $username; public function loginForm() { $this->login = "" . "" . if (isset($\_POST["submit"]) && (empty($\_POST["username"]))) { $this->username = $\_POST["username"]; ``` It still says that variable username is not defined, what am I doing wrong?<issue_comment>username_1: You are missing some quotes here: ``` public $username; public function loginForm() { $this->login = '' . '' . if (isset($\_POST["submit"]) && (empty($\_POST["username"]))) { $this->username = $\_POST["username"]; ``` Upvotes: -1 <issue_comment>username_2: Fixed by putting the var inside the function: ``` public function displayLogin() { $username = isset($_POST['username']) ? $_POST['username'] : ''; ``` Upvotes: 0
2018/03/21
1,153
3,942
<issue_start>username_0: I have table like below: ``` fld_bank_cash_particular_id fld_cr_dr fld_account_id fld_amount 1 Dr 26 1000 2 Dr 26 2000 3 Dr 26 3000 4 Cr 26 4000 5 Dr 26 5000 6 Cr 26 6000 7 Dr 26 7000 8 Dr 26 8000 9 Dr 26 9000 10 Cr 26 10000 11 Dr 27 1000 12 Dr 27 2000 13 Dr 27 3000 14 Cr 27 4000 15 Dr 27 5000 16 Cr 27 6000 17 Dr 27 7000 18 Dr 27 8000 19 Dr 27 9000 20 Cr 27 1000 ``` I want SUM() of all amount with column value 'Dr' as Payments and SUM() of all amount with column value 'Cr' as Receipts[Result should display AccountId wise Payments and Receipts]. Same Output like below: ``` AccountId Payments Receipts 26 35000 20000 27 35000 20000 ``` Currently i'm getting below result: ``` AccountId Payments Receipts 26 0 20000 26 35000 0 27 0 20000 27 35000 0 ```<issue_comment>username_1: ``` SELECT tam.fld_account_id AS [Account Id], MAX(CASE WHEN tbcep.fld_cr_dr = 'Dr' THEN SUM(ISNULL(fld_amount,0)) ELSE 0 END) AS Payments, MAX(CASE WHEN tbcep.fld_cr_dr = 'Cr' THEN SUM(ISNULL(fld_amount,0)) ELSE 0 END) AS Receipts FROM tbl_bank_cash_entry_particulars tbcep INNER JOIN tbl_bank_cash_entry tbce ON tbce.fld_bank_cash_entry_id = tbcep.fld_bank_cash_entry_id AND tbce.fld_fy_id=1 AND tbce.fld_is_active=1 AND tbce.fld_is_delete=0 LEFT JOIN tbl_account_master tam ON tam.fld_account_id = tbcep.fld_account_id AND tam.fld_is_active=1 AND tam.fld_is_delete=0 WHERE tam.fld_account_group_id=36 AND tbcep.fld_is_active=1 AND tbcep.fld_is_delete=0 GROUP BY tam.fld_account_id ``` USE MAX to select only the max value. so this approach will give you output in a single row Upvotes: -1 <issue_comment>username_2: Replace "TestTable" with your table: ``` SELECT DISTINCT AccountID, COALESCE(SumPay, 0) AS Payments, COALESCE(SumRec, 0) AS Receipts FROM (SELECT fld_account_id AS AccountID , (SELECT SUM([fld_amount]) FROM TestTable WHERE fld_cr_dr = 'Dr' AND fld_account_id = t.fld_account_id) AS SumPay , (SELECT SUM([fld_amount]) FROM TestTable WHERE fld_cr_dr = 'Cr' AND fld_account_id = t.fld_account_id) AS SumRec FROM TestTable t) AS tmp ``` ...may not be the most efficient, as it runs duplicate queries, but unless you're running it a hundred times a minute and/or your table is millions of records long, it should be ok. Upvotes: 0 <issue_comment>username_3: Try this, it should work! It is easy and clear! ``` SELECT DR.AccountId ,Payments ,Receipts FROM ( (SELECT fld_account_id AccountId ,SUM(fld_amount) Payments FROM table_name WHERE fld_cr_dr = 'Dr' GROUP BY fld_account_id) DR INNER JOIN (SELECT fld_account_id AccountId ,SUM(fld_amount) Receipts FROM table_name WHERE fld_cr_dr = 'Cr' GROUP BY fld_account_id) CR ON DR.AccountId = CR.AccountId ) ``` Upvotes: 2 [selected_answer]
2018/03/21
1,541
5,555
<issue_start>username_0: I'm following these instructions. The app is a Xamarin.Forms iOS app. <https://xamarinhelp.com/ios-universal-links/> Here's what I'm not sure about. First, I add a well-known folder to my MVC 5 Web App. I could not add a .well-known folder. Since I could not add the "." in front of the folder, I added a virtual directory using the Azure Portal. [![enter image description here](https://i.stack.imgur.com/Fx72D.png)](https://i.stack.imgur.com/Fx72D.png) When I try to access the file using <https://portal.mydomain.com/.well-known/apple-app-site-association>, I get the following message. "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable." Second, I had to edit the Entitlements.plist using the XML text editor. Here is what my entry looks like. ``` com.apple.developer.associated-domains applinks: portal.mydomain.com ``` Next, here's what ContinueUserActivity and OpenUrl looks like. //AppLinks app running > > > ``` > public override bool ContinueUserActivity(UIApplication application, NSUserActivity userActivity, UIApplicationRestorationHandler completionHandler) > { > try > { > > if (userActivity.ActivityType == "NSUserActivityTypeBrowsingWeb") > { > if (userActivity.WebPageUrl.AbsoluteString.Contains("/PublicOffers/OffersPage")) > { > > ((App)Xamarin.Forms.Application.Current).AppLinkRequest(new > Uri(userActivity.WebPageUrl.AbsoluteString)); > return true; > } > > } > > } > catch > { > // Ignore issue for now > } > > return base.ContinueUserActivity(application, userActivity, completionHandler); > } > > ``` > > //AppLinks app not running > > > ``` > public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options) > { > > try > { > var components = new NSUrlComponents(url, true); > var path = components.Path; > var query = components.Query; > > // Is this a known format? > if (path == "/PublicOffers/OffersPage") > { > // Send to App.xaml.cs > ((App)Xamarin.Forms.Application.Current).AppLinkRequest(new > Uri(url.AbsoluteString)); > return true; > } > } > catch > { > // Ignore issue for now > } > > //return false; > > return base.OpenUrl(app, url, options); > } > > ``` > > Finally, I created this method that calls OnAppLinkRequestReceived. > > > ``` > public async void AppLinkRequest(Uri uri) > { > OnAppLinkRequestReceived(uri); > } > > ``` > > The problem is that ContinueUserActivity and OpenUrl never get called. Here is an example of the Url I want to open/prompt the app using Universal Links. <https://portal.mydomain.com/PublicOffers/OffersPage?id=SOMEGUID&cid=SOMEGUID> Any ideas, help or suggestions are greatly appreciated. Thanks! **UPDATE 1** I added a new web.config file to my well-known folder and configured it like so. I can now access both files. My iOS Universal Links are still not working, though. ``` xml version="1.0" encoding="UTF-8"? ``` **UPDATE 2** I finally realized why my Entitlements.plist file didn't contain an option for Associated Domains. In order to see that option, you have to right click on the file, select "Open With..." and choose "Property List Editor". <https://learn.microsoft.com/en-us/xamarin/ios/deploy-test/provisioning/entitlements?tabs=vswin> ***UPDATE 3*** I just ran this validator tool and everything was green. It looks for the apple-app-site-association file. <http://branch.io/resources/aasa-validator/> Your domain is valid (valid DNS). Your file is served over HTTPS. Your server does not return error status codes greater than 400. Your file's 'content-type' header was found :) Your JSON is validated. **UPDATE 4** I just did a clean, rebuild and build. Universal Links are still not working. **UPDATE 5** I upgraded to Visual Studio 2017 Enterprise and Xamarin.iOS 172.16.31.10. I'm now using the 11.3 SDK and I still can't get Universal Links to work. I upgraded to Xamarin.Forms 2.5.1.444934 as well.<issue_comment>username_1: I had the same issues, apple-app-site-association file validated just fine and I implemented the ContinueUserActivity and OpenUrl-methods in AppDelegate.cs but my universal links were not working when building and deploying from my Windows machine using an external Mac build host. So I figured that I should try the same procedure but this time running everything locally on my Mac build host with Visual Studio for Mac. Cloned the project, deleted the app from my phone, re-built the project, deployed and voilá, it worked like a charm. Upvotes: 1 <issue_comment>username_2: I finally got it to work by removing the space from this line. ``` applinks: portal.mydomain.com ``` It now reads like this. ``` applinks:portal.mydomain.com. ``` I figured it out because I was getting an error on submitting the app to the app store. The error was: > > your application bundle's signature contains code signing entitlements that are not supported on iOS. Specifically, value applinks: portal.mydomain.com for key com.apple.developer.associated-domains in Payload... > > > Upvotes: 4 [selected_answer]
2018/03/21
352
1,133
<issue_start>username_0: In our java application, users can export data to excel files which are prone to [CSV Injection](https://www.owasp.org/index.php/CSV_Injection). To avoid this vulnerability, I want to restrict the user input such as **=HYPERLINK(E3, F3)** if any parameter start with following chars: ``` Equals to ("=") Plus ("+") Minus ("-") At ("@") ``` I tried some regexes: ``` ^[^+=@-] ^((?![+=@-]).)* ``` But these are not working as expected in bean validation.<issue_comment>username_1: You just need to escape the special characters in your regex like this: ``` String csvInjectionRegex = "^[^\\+\\=@\\-]"; ``` The following characters are the ones that need to be escaped in a regex: <([{\^-=$!|]})?\*+.> To escape them you either : * use the backslash `"\\"` * or use enclosed each special character in the both `\Q` and `\E` .Example:`("\\Q|\\E")` * If you have any doubts use the Pattern.quote(specialString): `String csvInjectionRegex = "^[^"+Pattern.quote("+-=@")+"]";` Upvotes: 2 <issue_comment>username_2: Try this: ``` if (value.matches("^[+=@-].*")) { //DO M } ``` Upvotes: 1
2018/03/21
3,146
10,600
<issue_start>username_0: I want to declare identifiers for scopes which will be used to automatically populate a field of any logging statements within the innermost scope. They will usually, but not always (e.g. lambdas, blocks introduced with `{}`), match the "name" of the enclosing block. Usage would look something like this: ```cpp namespace app { LOG_CONTEXT( "app" ); class Connector { LOG_CONTEXT( "Connector" ); void send( const std::string & msg ) { LOG_CONTEXT( "send()" ); LOG_TRACE( msg ); } }; } // namespace app // not inherited LOG_CONTEXT( "global", false ); void fn() { LOG_DEBUG( "in fn" ); } int main() { LOG_CONTEXT( "main()" ); LOG_INFO( "starting app" ); fn(); Connector c; c.send( "hello world" ); } ``` with the result being something like: ```none [2018-03-21 10:17:16.146] [info] [main()] starting app [2018-03-21 10:17:16.146] [debug] [global] in fn [2018-03-21 10:17:16.146] [trace] [app.Connector.send()] hello world ``` We can get the inner-most scope by defining the `LOG_CONTEXT` macro such that it declares a struct. Then in the `LOG_*` macros we call a static method on it to retrieve the name. We pass the whole thing to a callable object, e.g.: ```cpp namespace logging { spdlog::logger & instance() { auto sink = std::make_shared(); decltype(sink) sinks[] = {sink}; static spdlog::logger logger( "console", std::begin( sinks ), std::end( sinks ) ); return logger; } // TODO: stack-able context class log\_context { public: log\_context( const char \* name ) : name\_( name ) {} const char \* name() const { return name\_; } private: const char \* name\_; }; class log\_statement { public: log\_statement( spdlog::logger & logger, spdlog::level::level\_enum level, const log\_context & context ) : logger\_ ( logger ) , level\_ ( level ) , context\_( context ) {} template void operator()( const T & t, U&&... u ) { std::string fmt = std::string( "[{}] " ) + t; logger\_.log( level\_, fmt.c\_str(), context\_.name(), std::forward( u )... ); } private: spdlog::logger & logger\_; spdlog::level::level\_enum level\_; const log\_context & context\_; }; } // namespace logging #define LOGGER ::logging::instance() #define CHECK\_LEVEL( level\_name ) \ LOGGER.should\_log( ::spdlog::level::level\_name ) #define CHECK\_AND\_LOG( level\_name ) \ if ( !CHECK\_LEVEL( level\_name ) ) {} \ else \ ::logging::log\_statement( \ LOGGER, \ ::spdlog::level::level\_name, \ \_\_log\_context\_\_::context() ) #define LOG\_TRACE CHECK\_AND\_LOG( trace ) #define LOG\_DEBUG CHECK\_AND\_LOG( debug ) #define LOG\_INFO CHECK\_AND\_LOG( info ) #define LOG\_WARNING CHECK\_AND\_LOG( warn ) #define LOG\_ERROR CHECK\_AND\_LOG( err ) #define LOG\_CRITICAL CHECK\_AND\_LOG( critical ) #define LOG\_CONTEXT( name\_ ) \ struct \_\_log\_context\_\_ \ { \ static ::logging::log\_context context() \ { \ return ::logging::log\_context( name\_ ); \ } \ } LOG\_CONTEXT( "global" ); ``` Where I'm stuck is building the stack of contexts to use when defining an inner-most `__log_context__`. We may use a differently-named structure and macro convention to add 1 or 2 levels (e.g. `LOG_MODULE` can define a `__log_module__`), but I want a more general solution. Here are the restrictions I can think of to make things easier: 1. Scope nesting level may be reasonably bounded, but the user should not have to provide the current level/code may be moved to a different scope without being changed. Maybe 16 levels is enough (that gives us orgname::app::module::subsystem::subsubsystem::detail::impl::detail::util with some room to spare...) 2. Number of next-level scopes within a scope (in a single translation unit) may be bounded, but should be much larger than the value for 1. Maybe 256 is reasonable, but I'm sure someone will have a counterexample. 3. Ideally the same macro could be used for any context. I have considered the following approaches: 1. `using __parent_context__ = __log_context__; struct __log_context__ ...` hoping that `__parent_context__` picks up the outer context, but I was getting compiler errors indicating that a type name must refer unambiguously to a single type in the same scope. This restriction applies only when used in the body of a class, this would otherwise work for functions and namespaces. 2. Tracking the structures applicable to a scope in something like `boost::mpl::vector` The examples in the tutorial lead me to believe I would run into the same issue as in 1, since the vector after being pushed to needs to be given a distinct name which would need to be referred to specifically in nested scopes. 3. Generating the name of the applicable outer scope with a preprocessor counter. This would work in my simple usage example above, but would fail in the presence of discontinuous declarations in a namespace or method definitions outside of the corresponding class. How can this information be accessed in the nested scopes?<issue_comment>username_1: Writing an example would take some time, but I'll share how I'd approach this problem. * Your `LOG_CONTEXT` can be invoked anywhere, so if we create multiple static objects then order of their construction is unknown. * Your contexts can be sorted by line number, which is accessible with `__LINE__` * `LOG_CONTEXT` can create static objects of `LoggingContext` struct, which self-registers to local container under creation. (By local I mean unique in compilation object, might be achieved with anonymous namespace) * `LOG_*` should take their current line and take the most recent LoggingContext from local register. (Or few last, if needed) * I think all of it is possible with `constexpr` sematics (but quite a challange) Open problems: * Static objects in functions (created in first call) * Nesting of contexts (maybe comparing `__FUNCTION__` would work)? PS. I'll try to implement it on weekend Upvotes: 0 <issue_comment>username_2: Okay, I found a solution. The trick is that a `decltype(var)` for `var` visible in the outer scope will resolve to the type of that outer scope `var` even if we define `var` later in the same scope. This allows us to shadow the outer type but still access it, via an otherwise unused variable of the outer type, while allowing us to define a variable of the same name to be accessed in inner scopes. Our general construction looks like ``` struct __log_context__ { typedef decltype(__log_context_var__) prev; static const char * name() { return name_; } static ::logging::log_context context() { return ::logging::log_context( name(), chain<__log_context__>::get() ); } }; static __log_context__ __log_context_var__; ``` The only other detail is that we need a terminating condition when iterating up the context chain, so we use `void*` as a sentinel value and specialize for it in the helper classes used for constructing the output string. C++11 is required for `decltype` and to allow local classes to be passed to template parameters. ``` #include namespace logging { spdlog::logger & instance() { auto sink = std::make\_shared(); decltype(sink) sinks[] = {sink}; static spdlog::logger logger( "console", std::begin( sinks ), std::end( sinks ) ); return logger; } class log\_context { public: log\_context( const char \* name, const std::string & scope\_name ) : name\_ ( name ) , scope\_( scope\_name ) {} const char \* name() const { return name\_; } const char \* scope() const { return scope\_.c\_str(); } private: const char \* name\_; std::string scope\_; }; class log\_statement { public: log\_statement( spdlog::logger & logger, spdlog::level::level\_enum level, const log\_context & context ) : logger\_ ( logger ) , level\_ ( level ) , context\_( context ) {} template void operator()( const T & t, U&&... u ) { std::string fmt = std::string( "[{}] " ) + t; logger\_.log( level\_, fmt.c\_str(), context\_.scope(), std::forward( u )... ); } private: spdlog::logger & logger\_; spdlog::level::level\_enum level\_; const log\_context & context\_; }; } // namespace logging // Helpers for walking up the lexical scope chain. template struct chain { static std::string get() { return (chain::get() + ".") + T::name(); } }; template struct chain { static std::string get() { return T::name(); } }; #define LOGGER ::logging::instance() #define CHECK\_LEVEL( level\_name ) \ LOGGER.should\_log( ::spdlog::level::level\_name ) #define CHECK\_AND\_LOG( level\_name ) \ if ( !CHECK\_LEVEL( level\_name ) ) {} \ else \ ::logging::log\_statement( \ LOGGER, \ ::spdlog::level::level\_name, \ \_\_log\_context\_\_::context() ) #define LOG\_TRACE CHECK\_AND\_LOG( trace ) #define LOG\_DEBUG CHECK\_AND\_LOG( debug ) #define LOG\_INFO CHECK\_AND\_LOG( info ) #define LOG\_WARNING CHECK\_AND\_LOG( warn ) #define LOG\_ERROR CHECK\_AND\_LOG( err ) #define LOG\_CRITICAL CHECK\_AND\_LOG( critical ) #define LOG\_CONTEXT\_IMPL(prev\_type,name\_) \ struct \_\_log\_context\_\_ \ { \ typedef prev\_type prev; \ static const char \* name() { return name\_; } \ static ::logging::log\_context context() \ { \ return ::logging::log\_context( \ name(), chain<\_\_log\_context\_\_>::get() ); \ } \ }; \ static \_\_log\_context\_\_ \_\_log\_context\_var\_\_ #define LOG\_CONTEXT(name\_) \ LOG\_CONTEXT\_IMPL(decltype(\_\_log\_context\_var\_\_),name\_) #define ROOT\_CONTEXT(name\_) \ LOG\_CONTEXT\_IMPL(void\*,name\_) // We include the root definition here to ensure that // \_\_log\_context\_var\_\_ is always defined for any uses of // LOG\_CONTEXT. ROOT\_CONTEXT( "global" ); ``` which with an approximation of the code in my initial post ``` #include namespace app { LOG\_CONTEXT( "app" ); class Connector { LOG\_CONTEXT( "Connector" ); public: void send( const std::string & msg ) { LOG\_CONTEXT( "send()" ); LOG\_TRACE( msg ); } }; } // namespace app void fn() { LOG\_DEBUG( "in fn" ); } int main() { LOG\_CONTEXT( "main()" ); LOGGER.set\_level( spdlog::level::trace ); LOG\_INFO( "starting app" ); fn(); app::Connector c; c.send( "hello world" ); } ``` yields ``` [2018-03-22 22:35:06.746] [console] [info] [global.main()] starting app [2018-03-22 22:35:06.747] [console] [debug] [global] in fn [2018-03-22 22:35:06.747] [console] [trace] [global.app.Connector.send()] hello world ``` as desired. Conditionally inheriting an outer scope as mentioned in the question example is left as an exercise. Upvotes: 3 [selected_answer]
2018/03/21
1,874
6,201
<issue_start>username_0: I am calling a fade in on a `table` which contains several smaller divs in it. The whole schema boils down to this: ``` Resources ========= | | | | ``` CSS boils down to this ``` tr#tierIIResources, div#resources, { display: none; } ``` When I call `.fadeIn()` on `$('#resources')`, it ends up displaying both `tierI` and `tierII` resources. I would like to make it so only `tierI` is displayed. I can get around it by calling `('#tierIIResources').css('display', 'none)` but this is not optimal, and I would like to know how to do it purely with CSS or without the need for an additional function. Thank you!<issue_comment>username_1: Writing an example would take some time, but I'll share how I'd approach this problem. * Your `LOG_CONTEXT` can be invoked anywhere, so if we create multiple static objects then order of their construction is unknown. * Your contexts can be sorted by line number, which is accessible with `__LINE__` * `LOG_CONTEXT` can create static objects of `LoggingContext` struct, which self-registers to local container under creation. (By local I mean unique in compilation object, might be achieved with anonymous namespace) * `LOG_*` should take their current line and take the most recent LoggingContext from local register. (Or few last, if needed) * I think all of it is possible with `constexpr` sematics (but quite a challange) Open problems: * Static objects in functions (created in first call) * Nesting of contexts (maybe comparing `__FUNCTION__` would work)? PS. I'll try to implement it on weekend Upvotes: 0 <issue_comment>username_2: Okay, I found a solution. The trick is that a `decltype(var)` for `var` visible in the outer scope will resolve to the type of that outer scope `var` even if we define `var` later in the same scope. This allows us to shadow the outer type but still access it, via an otherwise unused variable of the outer type, while allowing us to define a variable of the same name to be accessed in inner scopes. Our general construction looks like ``` struct __log_context__ { typedef decltype(__log_context_var__) prev; static const char * name() { return name_; } static ::logging::log_context context() { return ::logging::log_context( name(), chain<__log_context__>::get() ); } }; static __log_context__ __log_context_var__; ``` The only other detail is that we need a terminating condition when iterating up the context chain, so we use `void*` as a sentinel value and specialize for it in the helper classes used for constructing the output string. C++11 is required for `decltype` and to allow local classes to be passed to template parameters. ``` #include namespace logging { spdlog::logger & instance() { auto sink = std::make\_shared(); decltype(sink) sinks[] = {sink}; static spdlog::logger logger( "console", std::begin( sinks ), std::end( sinks ) ); return logger; } class log\_context { public: log\_context( const char \* name, const std::string & scope\_name ) : name\_ ( name ) , scope\_( scope\_name ) {} const char \* name() const { return name\_; } const char \* scope() const { return scope\_.c\_str(); } private: const char \* name\_; std::string scope\_; }; class log\_statement { public: log\_statement( spdlog::logger & logger, spdlog::level::level\_enum level, const log\_context & context ) : logger\_ ( logger ) , level\_ ( level ) , context\_( context ) {} template void operator()( const T & t, U&&... u ) { std::string fmt = std::string( "[{}] " ) + t; logger\_.log( level\_, fmt.c\_str(), context\_.scope(), std::forward( u )... ); } private: spdlog::logger & logger\_; spdlog::level::level\_enum level\_; const log\_context & context\_; }; } // namespace logging // Helpers for walking up the lexical scope chain. template struct chain { static std::string get() { return (chain::get() + ".") + T::name(); } }; template struct chain { static std::string get() { return T::name(); } }; #define LOGGER ::logging::instance() #define CHECK\_LEVEL( level\_name ) \ LOGGER.should\_log( ::spdlog::level::level\_name ) #define CHECK\_AND\_LOG( level\_name ) \ if ( !CHECK\_LEVEL( level\_name ) ) {} \ else \ ::logging::log\_statement( \ LOGGER, \ ::spdlog::level::level\_name, \ \_\_log\_context\_\_::context() ) #define LOG\_TRACE CHECK\_AND\_LOG( trace ) #define LOG\_DEBUG CHECK\_AND\_LOG( debug ) #define LOG\_INFO CHECK\_AND\_LOG( info ) #define LOG\_WARNING CHECK\_AND\_LOG( warn ) #define LOG\_ERROR CHECK\_AND\_LOG( err ) #define LOG\_CRITICAL CHECK\_AND\_LOG( critical ) #define LOG\_CONTEXT\_IMPL(prev\_type,name\_) \ struct \_\_log\_context\_\_ \ { \ typedef prev\_type prev; \ static const char \* name() { return name\_; } \ static ::logging::log\_context context() \ { \ return ::logging::log\_context( \ name(), chain<\_\_log\_context\_\_>::get() ); \ } \ }; \ static \_\_log\_context\_\_ \_\_log\_context\_var\_\_ #define LOG\_CONTEXT(name\_) \ LOG\_CONTEXT\_IMPL(decltype(\_\_log\_context\_var\_\_),name\_) #define ROOT\_CONTEXT(name\_) \ LOG\_CONTEXT\_IMPL(void\*,name\_) // We include the root definition here to ensure that // \_\_log\_context\_var\_\_ is always defined for any uses of // LOG\_CONTEXT. ROOT\_CONTEXT( "global" ); ``` which with an approximation of the code in my initial post ``` #include namespace app { LOG\_CONTEXT( "app" ); class Connector { LOG\_CONTEXT( "Connector" ); public: void send( const std::string & msg ) { LOG\_CONTEXT( "send()" ); LOG\_TRACE( msg ); } }; } // namespace app void fn() { LOG\_DEBUG( "in fn" ); } int main() { LOG\_CONTEXT( "main()" ); LOGGER.set\_level( spdlog::level::trace ); LOG\_INFO( "starting app" ); fn(); app::Connector c; c.send( "hello world" ); } ``` yields ``` [2018-03-22 22:35:06.746] [console] [info] [global.main()] starting app [2018-03-22 22:35:06.747] [console] [debug] [global] in fn [2018-03-22 22:35:06.747] [console] [trace] [global.app.Connector.send()] hello world ``` as desired. Conditionally inheriting an outer scope as mentioned in the question example is left as an exercise. Upvotes: 3 [selected_answer]
2018/03/21
1,070
3,740
<issue_start>username_0: I need to show a page loading image until data is saved in the database and the View is redirected to another page when the submit button is clicked. In my View I have a loading image inside a div with id `divLoading`. I wish to show the loading image until the data is saved and the View redirected to another page by clicking the submit button. I've tried many ways, but it's not working. The View and Controller code is given below. View: ``` @using (Html.BeginForm("SaveCountry","Country",FormMethod.Post)) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) State Creation -------------- @Html.Label("Display Name", new { @class = "control-label" }) @Html.TextBoxFor(model => model.DisplayName, new { @class = "form-control", type = "text", id = "Date" }) @Html.ValidationMessageFor(model => model.DisplayName) @Html.Label("Print Name", new { @class = "control-label" }) @Html.TextBoxFor(model => model.PrintName, new { @class = "form-control", type = "text", id = "Date" }) @Html.ValidationMessageFor(model => model.PrintName) @Html.Label("Country") @Html.DropDownList("CountryID", null, "Select", new { @class = "form-control required" }) @Html.ValidationMessageFor(model => model.CountryID) Save [*Details*](@Url.Action() ![](~/images/Img) } ``` Controller: ``` public ActionResult SaveCountry(CountryViewModel CVM) { return RedirectToAction("CountryDetails"); } public ActionResult CountryDetails() { var objVisitorsList = db.Country.ToList(); return View(objVisitorsList.ToList()); } ``` It's simple question, but I've tried many javascript codes and it's not working. Please help me to resolve this issue. Thanks.<issue_comment>username_1: There are many ways to do this, and I'll suggest one that should get you started off:- (i) Assign a unique id to your form (eg `form-id`) by changing your form code to: ``` @using (Html.BeginForm("SaveCountry", "Country", FormMethod.Post, new { id = "form-id" })) { } ``` (ii) Put the loader on your page with a unique id (I've changed your code for the loader, which won't work properly: your didn't close the div and assigned "Id" instead of "id"). The div is hidden until the form is submitted: ``` ![](path/to/your/image/loading-image.png) ``` (iii) Style the loading div to go somewhere useful. This example css centers the div: ``` #divLoading{ position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); transform: -webkit-translate(-50%, -50%); transform: -moz-translate(-50%, -50%); transform: -ms-translate(-50%, -50%); } ``` (iv) Reference some script (I've assumed you're using jQuery here) to show the loader when the form is submitted (and after any validation has been completed), for example: ``` $("#form-id").on("submit", function () { $("#divLoading").show(); }); ``` (v) Given that your page will redirect, you can probably leave the loader until the page redirects, but if you need to hide the loader before that happens, you can use: ``` $("#divLoading").hide(); ``` on some event to hide the loader, and for it to be ready for the next form submit. Upvotes: 1 <issue_comment>username_2: Use Ajax Form Here is sample code: View: ``` @using (Ajax.BeginForm("SaveCountry","Country", new AjaxOptions { OnSuccess = "onSuccess", LoadingElementId = "divLoading" },new { @id = "countryForm" })){ Form Elements.... ![](~/images/Img) } ``` In Javascript: ``` var onSuccess = function(result) { if (result.url) { window.location.href = result.url; } } ``` In Controller: ``` public ActionResult SaveCountry(CountryViewModel CVM) { return Json(new { url = Url.Action("CountryDetails") }); } ``` Upvotes: 0
2018/03/21
1,079
4,154
<issue_start>username_0: I try to enable placeholder at my SignUp form with 4 fields: phone, email, password1, password2. For first two fields all correct, but for password field it doesn't work. **forms.py** ``` from django import forms from django.contrib.auth.forms import UserCreationForm from customuser.models import User from django.forms import TextInput,EmailInput,PasswordInput class SignUpForm(UserCreationForm): class Meta: model = User fields = ('phone', 'email', 'password1', 'password2', 'is_client','is_partner') widgets = { 'email': EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email adress'}), 'phone': TextInput(attrs={'class': 'form-control', 'placeholder': 'Phone number +79011234567'}), 'password1': PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password from numbers and letters of the Latin alphabet'}), 'password2': PasswordInput(attrs={'class': 'form-control', 'placeholder': ' Password confirmation'}), } ```<issue_comment>username_1: The `Meta.widgets` option doesn't apply to fields that were declared in the form. See the [note in the docs](https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/#overriding-the-default-fields). In this case, `password1` and `password2` are declare on the `UserCreationForm` (they aren't model fields), therefore you can't use them in `widgets`. You could set the widget in the `__init__` method instead: ``` class SignUpForm(UserCreationForm): class Meta: model = User fields = ('phone', 'email', 'is_client', 'is_partner') widgets = { 'email': EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email adress'}), 'phone': TextInput(attrs={'class': 'form-control', 'placeholder': 'Phone number +79011234567'}), } def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) self.fields['password1'].widget = PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password from numbers and letters of the Latin alphabet'}) self.fields['password2'].widget = PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password confirmation'}) ``` Upvotes: 3 <issue_comment>username_2: This code works fine ``` class SignUpForm(UserCreationForm): password1 = forms.CharField(max_length=16, widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password from numbers and letters of the Latin alphabet'})) password2 = forms.CharField(max_length=16, widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password confirm'})) class Meta: model = User fields = ('phone', 'email', 'password1', '<PASSWORD>', 'is_client','is_partner') widgets = { 'email': EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email adress'}), 'phone': TextInput(attrs={'class': 'form-control', 'placeholder': 'Phone number format +79011234567'}), } ``` Upvotes: 2 <issue_comment>username_3: I tested the @username_1 ´s solution and work for me this way: ``` from django import forms from django.contrib import auth from django.contrib.auth.forms import UserCreationForm from django.utils.translation import ugettext_lazy as _ class RegistrationForm(UserCreationForm): first_name = forms.CharField(label=_("First name"), widget=forms.TextInput(attrs={'placeholder': _("First name")})) email = forms.EmailField(label=_("Email"), widget=forms.TextInput(attrs={'placeholder': _("Email")})) class Meta(UserCreationForm.Meta): model = auth.get_user_model() fields = [ 'first_name', 'email', '<PASSWORD>', 'password2' ] def __init__(self, *args, **kwargs): super(InviteRegistrationForm, self).__init__(*args, **kwargs) self.fields['password1'].widget = forms.PasswordInput(attrs={'placeholder': _("<PASSWORD>")}) self.fields['password2'].widget = forms.PasswordInput(attrs={'placeholder': _("<PASSWORD>")}) ``` Upvotes: 1
2018/03/21
524
1,796
<issue_start>username_0: I have a table, which displays data in ngFor. When I delete an element, I want to hide it. I figured I have to do a variable in my record component `hide:boolean` which is false by default, but when I click od delete button, it changes to true. I don't know how to "catch" this variable in my table. ``` | Id | Name | Surname | Actions | | --- | --- | --- | --- | | | | ``` And my record component: ``` {{record.id}} | {{record.name}} | {{record.surname}} | Remove | ``` What am I doing wrong? I have my data in json file, connected by json-server. I delete record with `http.delete()` function. It gets deleted from my file, but the table does not reload by itself. record component, removeRecod function: ``` removeRecord(id) { var url = this.data_url + "/" + id; this.http.delete(url).subscribe(); this.hide = true; } ```<issue_comment>username_1: You only have the id of your object. Do it this way: ``` removeRecord(id: number){ var url = this.data_url + "/" + id; this.http.delete(url).subscribe(); this.records.forEach(element => { if(element.id === id){ element.hide = true; } }); } ``` Upvotes: 0 <issue_comment>username_2: Two basic options here: 1. pass in the entire record object to the delete function and switch "hide" to true ``` removeRecord(record) { record.hide = true; let id = record.id; // do whatever to delete on server } ``` 2. (better) remove the record from the list itself rather than trying to hide it. ``` removeRecord(id) { //do whatever to delete the record on server let recordIndex = this.records.findIndex(r => r.id === id); this.records = this.records.splice(recordIndex, 1); } ``` Upvotes: 2 [selected_answer]
2018/03/21
927
3,809
<issue_start>username_0: I'm writing a web app where people can download PDFs unique to them. I want to use PayPal to allow buyers to enter payment (as comprehensive as possible) without leaving my page, and then to be sent to my PHP script which will receive an ID variable in order to deliver their unique PDF. For this, I'm trying to work out which PayPal technologies would be appropriate. I get the impression (possibly incorrect) that "PayPal Express Checkout" enables payment without leaving my page, but I don't know the ancillary technologies that allow the passing of the unique ID variable through this, to redirect to the PDF-generator script. I'm also reviewing "Direct Payments" if this is relevant. I have a PayPal business account, with a sandbox account set up. Any general guidelines hugely appreciated.<issue_comment>username_1: I'm working on basically the exact same thing right now. Yes, Express Checkout is the way to go; there are 3 main ways to use Express Checkout: <https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/set-up-a-payment/> You'll want to go with the Server-side REST setup. Take a look at their demo page here <https://developer.paypal.com/demo/checkout/#/pattern/server> In a nutshell, the flow you'll want to look at is: 1.) User lands on the payment page 2.) User clicks one of the payment buttons 3.) #2 triggers your php page, CREATE\_URL (see the demo) 4.) Your CREATE\_URL php will need to use the paypal REST API to create a `payment`. You'll likely want the intent to be `sale` but there are three options (sale, authorized payment, or order) 5.) Once a payment is created, a box pops up which allows the user to make the payment 6.) If the user makes the payment ("authorizes" in paypal terms), you then need to execute the payment. Your EXECUTE\_URL php page is triggered 7.) On your EXECUTE\_URL php page, you execute the payment again using paypal's REST API. Assuming the payment is successful and the status = completed (meaning, the funds were actually transferred from the user's accuont to your paypal business account) then you can return the unique download id back to the client's browser A few important notes: * There's quite a bit of error handling involved, and paypal docs are horrid. Create payment can fail, user might not authorize the payment, execute payment may fail, etc. * Just because the payment is executed does not mean the funds have been transferred to your account yet. The user may have used an eCheck or other funding instrument that may take a day or two to complete. You need to inspect the `status` value of the `sale` to determine this * You'll also want to set up a listener URL and a webhook, so that you'll be notified of payments which do not complete instantly It's....taking awhile to get this done in a solid fashion. If PayPal's docs were better, I would've been done a day ago. Good luck. Upvotes: 1 <issue_comment>username_1: If you aren't familiar with how php and js can communicate, you may give this a try (it's easier to set up than the server-side REST), although I would recommend hiring a developer who knows the Paypal API well. Paypal Express Checkout - Client-side REST <https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/client-side-REST-integration/> When the user has finished paying, line 47 of your code will run (line 47 of this demo: <https://developer.paypal.com/demo/checkout/#/pattern/client>) When that happens, you can call a php script using AJAX; that php script should return the unique id. You can then use javascript to redirect the user. **Important Note** A very simple/basic hacker could get access to your pdf without paying, as nothing in javascript on the client is secure. Upvotes: 0
2018/03/21
1,065
4,176
<issue_start>username_0: I have a large and complicated #create method in my controller. While creating a model instance I am also saving a large file to a server, doing a bunch of processing on it, and some other stuff. Now in my other tests I want all those 'side effects' to be available. So in Factory Bot it's not sufficient to simply create a model instance, so I need to run the whole `#create` action from the controller. My questions are: What is the syntax for running the controller action in the factory file? Can't seem to find it. Is that a normal practice for this sort of thing? Or should I avoid depending on controller's create action and write a minimal version of it in the factory? Thanks.<issue_comment>username_1: > > ... in Factory Bot it's not sufficient to simply create a model instance > > > Factory Bot is not built to work with controllers, as it is focused solely on the object. As the repo description states, it is "A library for setting up Ruby objects as test data." > > Now in my other tests I want all those 'side effects' to be available ... I need to run the whole #create action from the controller. > > > Think of Factory Bot as only there to mock model data for a test. Your factories don't care about what you have in your controller and views. If you want to test controller actions, you should look at [controller specs](https://relishapp.com/rspec/rspec-rails/docs/controller-specs) or [request specs](https://relishapp.com/rspec/rspec-rails/v/3-7/docs/request-specs/request-spec). (Links assume use of rspec.) When writing a controller or request spec, you can use your factory to create an object that you can then use within your controller/request spec, therefore testing the effect your create action has on that object. > > I have a large and complicated #create method in my controller. > > > I'd also suggest breaking your create action up if it's getting long. Two ways to accomplish this are through [controller concerns](https://www.sitepoint.com/dry-off-your-rails-code-with-activesupportconcerns/) or [service objects](https://hackernoon.com/the-3-tenets-of-service-objects-c936b891b3c2). Both of these methods would also make testing easier because you can test each concern/service object separately. You may also consider moving tasks into the background (or on the client side) if they become expensive because that can hold up the request and negatively affect performance. --- To answer your questions directly: > > What is the syntax for running the controller action in the factory file? > > > There isn't one because this is not what Factory Bot is built for. > > Is that a normal practice for this sort of thing? > > > No. > > Or should I avoid depending on controller's create action and write a minimal version of it in the factory? > > > Nope. But if the controller gets long and messy, feel free to break the logic up among concerns or service objects. Upvotes: 2 <issue_comment>username_2: So after giving it some thought and with the help of @username_1 I realised that FactoryBot is not a good fit for firing 'create' action. Instead I am running it in a `before :each` block as that seems to be the way to do it. Upvotes: 1 [selected_answer]<issue_comment>username_3: There's another way that could solve this problem, which is to take advantage of FactoryBot's callbacks. In my users#create action, I automatically add the users to a specific organization, so I've replicated this behavior for seed data by adding an `after(:create)` block to the users factory. I've also found that I can keep the rest of my test suite from getting slower by putting that `after(:create)` block inside a trait like so: ``` FactoryBot.define do factory :user do first_name { Faker::Name.unique.first_name } trait :with_organization do after(:create) do |user| org = Organization.find_by(name: 'Doctors Without Borders') FactoryBot.create(:organization_user, organization: org, user: user) end end end end ``` Perhaps there's an even more elegant solution than this, but it's worked well for my needs thus far. Upvotes: 0
2018/03/21
727
2,735
<issue_start>username_0: Hi I am trying to do a `ModPow` calculation as fast as possible, the calculation is as such **P^e%n**. Test data is 888999000^202404606%237291793913, **I am aware of the BigInteger.ModPow(P, e, n)** however I am not supposed to use this function so I have written the following function which is relatively slow, and I really need to speed up the process. (I am sure that maybe if I split the calculation numbers in half and turn it into two individual calculations it will speed up the process hopefully), anyway heres what I've written so far. ``` private static BigInteger ModPow(BigInteger baseNum, BigInteger exponent, BigInteger modulus) { BigInteger c; if (modulus == 1) return 0; c = 1; for (BigInteger e_prime = 1; e_prime <= exponent; e_prime++) { c = (c * baseNum) % modulus; } return c; } ```<issue_comment>username_1: What you need is probably [Exponentiation by squaring](https://en.wikipedia.org/wiki/Exponentiation_by_squaring#Further_applications) which works for modulo power as well. The code should be something like this: ``` private static BigInteger ModPow(BigInteger baseNum, BigInteger exponent, BigInteger modulus) { BigInteger pow = 1; if (modulus == 1) return 0; BigInteger curPow = baseNum % modulus; BigInteger res = 1; while(exponent > 0){ if (exponent % 2 == 1) res = (res * curPow) % modulus; exponent = exponent / 2; curPow = (curPow * curPow) % modulus; // square curPow } return res; } ``` This method performance is `O(log(exponent))` rather than `O(exponent)` for your code in term of number of multiplications and modulo operations (that are probably not `O(1)` for `BigInteger` but details depend on implementation). Also note that the code above should not be used for any real world crypto-related implementations because it introduces vulnerability (performance depends on actual value of the `exponent`, particularly how many `1` bits there are there (see [Timing attack](https://en.wikipedia.org/wiki/Timing_attack) for some details). Upvotes: 3 [selected_answer]<issue_comment>username_2: Well, try this ============== ``` private static BigInteger ModPow(BigInteger baseNum, BigInteger exponent, BigInteger modulus) { BigInteger B, D; B = baseNum; B %= modulus; D = 1; if ((exponent & 1) == 1) { D = B; } while (exponent > 1) { exponent >>= 1; B = (B * B) % modulus; if ((exponent & 1) == 1) { D = (D * B) % modulus; } } return (BigInteger)D; } ``` Upvotes: 1
2018/03/21
745
2,676
<issue_start>username_0: I am making a script which is going to add together a bunch of inputs. I am almost there, but when testing the script i seem to get the alert: Notice: Undefined index: number in C:\xampp\htdocs\Archers.php on line 25. Even though I have declared it earlier and even when using it now. The script is below. Thanks in advance. ``` Enter how many values you would like to enter: php $number = 0; $result = 0; if (isset($\_POST["submit"])){ $number = $\_POST['number']; $x = 0; echo "<form method=\"post\""; while ($x != $number) { echo "Enter score: "; $x = $x + 1; } echo ""; } if (isset($\_POST["submit2"])){ $y = 0; $number = $\_POST['number']; while ($y != $number){ $value = $\_POST["a".$y]; $result = $result + $value; $y = $y + 1; } echo $result; } ?> ```<issue_comment>username_1: What you need is probably [Exponentiation by squaring](https://en.wikipedia.org/wiki/Exponentiation_by_squaring#Further_applications) which works for modulo power as well. The code should be something like this: ``` private static BigInteger ModPow(BigInteger baseNum, BigInteger exponent, BigInteger modulus) { BigInteger pow = 1; if (modulus == 1) return 0; BigInteger curPow = baseNum % modulus; BigInteger res = 1; while(exponent > 0){ if (exponent % 2 == 1) res = (res * curPow) % modulus; exponent = exponent / 2; curPow = (curPow * curPow) % modulus; // square curPow } return res; } ``` This method performance is `O(log(exponent))` rather than `O(exponent)` for your code in term of number of multiplications and modulo operations (that are probably not `O(1)` for `BigInteger` but details depend on implementation). Also note that the code above should not be used for any real world crypto-related implementations because it introduces vulnerability (performance depends on actual value of the `exponent`, particularly how many `1` bits there are there (see [Timing attack](https://en.wikipedia.org/wiki/Timing_attack) for some details). Upvotes: 3 [selected_answer]<issue_comment>username_2: Well, try this ============== ``` private static BigInteger ModPow(BigInteger baseNum, BigInteger exponent, BigInteger modulus) { BigInteger B, D; B = baseNum; B %= modulus; D = 1; if ((exponent & 1) == 1) { D = B; } while (exponent > 1) { exponent >>= 1; B = (B * B) % modulus; if ((exponent & 1) == 1) { D = (D * B) % modulus; } } return (BigInteger)D; } ``` Upvotes: 1
2018/03/21
850
3,199
<issue_start>username_0: I am building a java application with Gradle and I want to transfer the final jar file in another folder. I want to copy the file on each `build` and delete the file on each `clean`. Unfortunately, I can do only one of the tasks and not both. When I have the task `copyJar` activated, it successfully copies the JAR. When I include the `clean` task, the JAR is not copied and if there is a file there it is deleted. It is as if there is some task that calls `clean`. Any solutions? ``` plugins { id 'java' id 'base' id 'com.github.johnrengelman.shadow' version '2.0.2' } dependencies { compile project(":core") compile project("fs-api-reader") compile project(":common") } task copyJar(type: Copy) { copy { from "build/libs/${rootProject.name}.jar" into "myApp-app" } } clean { file("myApp-app/${rootProject.name}.jar").delete() } copyJar.dependsOn(build) allprojects { apply plugin: 'java' apply plugin: 'base' repositories { mavenCentral() } dependencies { testCompile 'junit:junit:4.12' compile 'org.slf4j:slf4j-api:1.7.12' testCompile group: 'ch.qos.logback', name: 'logback-classic', version: '0.9.26' } sourceSets { test { java.srcDir 'src/test/java' } integration { java.srcDir 'src/test/integration/java' resources.srcDir 'src/test/resources' compileClasspath += main.output + test.output runtimeClasspath += main.output + test.output } } configurations { integrationCompile.extendsFrom testCompile integrationRuntime.extendsFrom testRuntime } task integration(type: Test, description: 'Runs the integration tests.', group: 'Verification') { testClassesDirs = sourceSets.integration.output.classesDirs classpath = sourceSets.integration.runtimeClasspath } test { reports.html.enabled = true } clean { file('out').deleteDir() } } ```<issue_comment>username_1: ``` clean { file("myApp-app/${rootProject.name}.jar").delete() } ``` This will delete the file on evaluation every time, which is not what you want. Change it to: ``` clean { delete "myApp-app/${rootProject.name}.jar" } ``` This configures the clean task and adds the JAR to be deleted on execution. Upvotes: 4 [selected_answer]<issue_comment>username_2: @username_1 is right about the `clean` task, but you also need to fix your `copyJar` task. The `copy { ... }` method is called during configuration phase, so everytime gradle is invoked. Simple remove the method and use the configuration methods of the `Copy` task type: ``` task copyJar(type: Copy) { from "build/libs/${rootProject.name}.jar" into "myApp-app" } ``` The same problem applies for the `clean` task in the `allprojects` closure. Simply replace `file('out').deleteDir()` with `delete 'out'`. Check out more information about the difference between *configuration phase* and *execution phase* in the [documentation](https://docs.gradle.org/current/userguide/build_lifecycle.html#sec:build_phases). Upvotes: 2
2018/03/21
346
1,077
<issue_start>username_0: The image displays as a white box with a small image icon in the top left corner. Html code: ``` ![](DukeGrafitti_TRANS) ``` css code: ``` img { display: block; margin-left: auto; margin-right: auto; margin-top: 100px; height: 215.83px; width: 401.83px; } ```<issue_comment>username_1: Your img src is missing a valid extension, eg: `.jpg` `.gif` `.png` ``` ![](DukeGrafitti_TRANS.jpg) ``` Your code also assumes that the image is in the same directory as the current file you are working on. So make sure that is the case or provide a full path to the image. Upvotes: 1 <issue_comment>username_2: ### I think you need to include the file extension of the image. Try something like this: ``` ![DukeGrafitti_TRANS](DukeGrafitti_TRANS.gif) ``` * An absolute URL - points to another web site (like src="http://www.example.com/image.gif") * A relative URL - points to a file within a web site (like src="image.gif") This answer is referenced from this [link](https://www.w3schools.com/tags/att_img_src.asp) Upvotes: 0
2018/03/21
322
1,071
<issue_start>username_0: just read Scala collection implementation and noticed a subtile difference: * **immutable HashMap** : `class HashMap[A, +B]()` * **mutable HashMap** : `class HashMap[A, B]()` Could you please explain me why the immutable's value type is covariant while the mutable's one is not ? Thanks for your help<issue_comment>username_1: The mutable `HashMap` has methods taking `B` as argument, e.g. `def update(key: A, value: B): Unit`. Presence of such methods means `B` can't be covariant, or you could write ``` val map: mutable.HashMap[Int, AnyRef] = mutable.HashMap.empty[Int, String] map.update(0, new AnyRef) // call update(Int, AnyRef) where (Int, String) is expected ``` The immutable one doesn't. Upvotes: 2 <issue_comment>username_2: If the mutable map were covariant, it would be possible to do something like this: ``` val m1: mutable.Map[String, Int] = mutable.Map.empty[String, Int] val m2: mutable.Map[String, Any] = m1 m2 += ("foo" -> "bar") m1("foo") // returns "bar" out of a Map[String, Int]??? ``` Upvotes: 4 [selected_answer]
2018/03/21
386
983
<issue_start>username_0: I want to convert a number to a decimal. I've been using: ``` sprintf("%02d", $price / 12); ``` Only sometimes `$price` is a whole number, so instead of `6`, I get `06`. How do I ensure that it converts to 2 decimal places, but also doesn't prepend a zero before the whole number ?<issue_comment>username_1: ``` sprintf('%.2f', $price/12) =~ s/\.00\z//r # 5.14+ ``` or ``` do { my $s = sprintf('%.2f', $price/12); $s =~ s/\.00\z//; $s } ``` For both of the above, * If `$price/12 == 5.999`, evaluates to `6` * If `$price/12 == 6`, evaluates to `6` * If `$price/12 == 6.001`, evaluates to `6` * If `$price/12 == 6.2`, evaluates to `6.20` * If `$price/12 == 6.22`, evaluates to `6.22` * If `$price/12 == 6.222`, evaluates to `6.22` * If `$price/12 == 6.229`, evaluates to `6.23` Upvotes: 2 [selected_answer]<issue_comment>username_2: ``` int( $price / 6 + 0.5 ); ``` Perl automatically changes between string and numbers as needed. Upvotes: 0
2018/03/21
1,077
4,083
<issue_start>username_0: I have a function that loops through a large dataset. It takes multiple inputs and contains a lot of conditions. For testing, I sometimes like to run the function without certain conditions, but it is a time consuming to uncomment the conditions - which is what I do know. Is it possible to give the function an input that always makes the condition true - both for strings and numeric values? A simplified example: ``` def function(a,b,c....): ..... item = dict(zip(header,row)) for row in list: if item["variable"] == a: print row .... return something ``` Now I want to print any row. `function(any,b,c...)` I thought about giving it `item["variable"]` as input, but this does not work.<issue_comment>username_1: Something like this could work. ``` def function(a,b,c,test=False): ..... item = dict(zip(header,row)) for row in list: if test: print row else: if item["vaariable"] == a: print row .... return something ``` Upvotes: 0 <issue_comment>username_2: If you're looking for a function that returns true for any arguments: ``` def always(*args, **kw): return True ``` If you're looking for an object that always compares `==` to any object, you can *almost* do that: ``` class AlwaysEqual: def __eq__(self, other): return True ``` But just almost—if, say, you put this irresistible force of truthiness up against an immovable object of falsity, whoever's on the left will win. And if you want to overload multiple comparisons in ways that aren't consistent for any plausible value, like making it equal everything and also be less than everything, there's nothing stopping you. (After all, `math.nan` is not equal to anything, including itself, and that's required by standards written by people who thought it through in great detail, so Python's not going to stop you from doing something similar.) Upvotes: 3 [selected_answer]<issue_comment>username_3: You could use a function that takes a boolean and returns `True` if you're running tests, and the boolean's real value otherwise: ```py def func(x, y, test=False): def _bool(b): return True if test else b if _bool(foo == x): if _bool(bar == y): do_something() ``` Upvotes: 0 <issue_comment>username_4: I sometimes instrument my programs with a comparable item, turning debug tracing off and on. In your case, imbue each condition with a short-circuiting `or` on a flag: ``` all_true = True # all_true = False ... if all_true or item["vaariable"] == a: ... ``` Do this once; you can now control it by changing the comment mark. Perhaps more useful, you can turn it on and off during the run. Upvotes: 0 <issue_comment>username_5: Split the code into 'debug mode' and 'release mode' and use explicit check in conditions. Stay away from fancy approaches as it will cause more troubles in future. ``` debug = True if debug or len(something) > 2: # something always on in debug mode do_something() if not debug and len(some_other_thing) > 7: # something always off in debug mode do_something_else() ``` Upvotes: 1 <issue_comment>username_6: From reading your code I think you need a Python object which when you use `==` to compare it to any other Python object the result always will be `True`; First you need to define a class the property I mentioned then use one instance of it instead of `any` to call the `function`: ``` class AnyObject(object): def __eq__(self, anything): return True 1 == AnyObject() '' == AnyObject() None == AnyObject() ``` Your code: ``` def function(a,b,c....): ..... item = dict(zip(header,row)) for row in list: if item["variable"] == a: print row .... return something ``` You only need to use an instance of `AnyObject` class in place of `any` when you call `function`: ``` any = AnyObject() function(any,b,c...) ``` Now the condition is true for all the rows! Upvotes: 0
2018/03/21
561
2,277
<issue_start>username_0: I am trying to edit a div's class name that is on my homepage based on a toggle switch but the toggle switch is on a different page. This script worked when the div was on the same page but now its not functioning. ``` function changeStatus(obj,temp) { var toggleid = $(obj).attr('name'); var toggle = document.getElementsByClassName("statusinput")[toggleid]; var statusEffect = $.get('index.html', null, function(text){ alert($(text).find('#name')); }); if(toggle.checked){ statusEffect.innerHTML = "Arrived"; statusEffect.classList.remove("statusp"); statusEffect.classList.add("statusa"); }else{ statusEffect.innerHTML = "Pending"; statusEffect.classList.remove("statusa"); statusEffect.classList.add("statusp"); } ``` every time I run this I get a error [Object object]. This is supposed to make it so when the user checks the box the div switches from "Pending" to "Arrived"<issue_comment>username_1: You can only amend the DOM of the page which is currently loaded. If you want to change a different page based on an action in a another one you'd need to persist the state of the user's interactions and then amend the other page when it loads. To do that you can use localStorage, sessionStorage, session, cookies, or AJAX to store information on the server Upvotes: 1 <issue_comment>username_2: Depending on your version of JQuery: ``` var statusEffect = $.get('index.html', null, function(text){ alert($(text).find('#name')); }); ``` $.get() will return a promise, not a DOM element. [Link to docs](https://api.jquery.com/jQuery.get/) Further down, you are trying to use it like a DOM element. ``` if(toggle.checked){ statusEffect.innerHTML = "Arrived"; statusEffect.classList.remove("statusp"); statusEffect.classList.add("statusa"); }else{ statusEffect.innerHTML = "Pending"; statusEffect.classList.remove("statusa"); statusEffect.classList.add("statusp"); } ``` If you wish to alter the class name of a div on another page you would have to store that information somewhere, such as a cookie. When that page loads check the cookie to give the div the correct class name. Upvotes: 0
2018/03/21
532
1,785
<issue_start>username_0: I've got a JQuery function using getJSON to bring some userifo. It's like that: ``` $.getJSON("http://server.com/?apirequested=userinfo", function(data){ ... ... }); ``` This works fine, but I'm trying to change it to use same code for several servers using relatives url's. I'm trying several things like: ``` $.getJSON($(location).attr('hostname')+"/?apirequested=userinfo" ... ``` or ``` $.getJSON($(location).attr('protocol')+$(location).attr('hostname')+"/?apirequested=userinfo", ``` or ``` $.getJSON(location.hostame+"/?apirequested=userinfo" ... ``` But it does not work. What am I doing wrong? Any suggestions? Thanks in advance for your time.<issue_comment>username_1: This might be help you. <http://tech-blog.maddyzone.com/javascript/get-current-url-javascript-jquery> ``` $(location).attr('host'); www.test.com:8082 $(location).attr('hostname'); www.test.com $(location).attr('port'); 8082 $(location).attr('protocol'); http: $(location).attr('pathname'); index.php $(location).attr('href'); http://www.test.com:8082/index.php#tab2 $(location).attr('hash'); #tab2 $(location).attr('search'); ?foo=123 ``` Upvotes: 2 <issue_comment>username_2: I found the problem. It works with: ``` $.getJSON($(location).attr('protocol')+"//"+$(location).attr('hostname')+"/?apirequested=userinfo", ... ``` Upvotes: 1 <issue_comment>username_3: ``` let myurl = location.protocol+"//"+location.hostname+"/?apirequested=userinfo"; $.getJSON(myurl); ``` or perhaps simpler ``` let myurl = location.origin + "/?apirequested=userinfo"; $.getJSON(myurl); ``` Upvotes: 0
2018/03/21
1,813
3,691
<issue_start>username_0: Suppose that we have a data table with missing values (see example below). ``` library(data.table) mat <- matrix(rnorm(50), ncol = 5) mat[c(1,3,5,9,10,11,14,37,38)] <- NA DT <- as.data.table(mat) ``` In total, we have 5 unique missing data patterns in our example (see `unique(!is.na(DT))`). Suppose now further that we would like to find these patterns and identify them according to their frequency of occurrence (starting with the most frequent pattern indicated by 1). ``` DTna <- as.data.table(!is.na(DT)) DTna <- DTna[, n := .N, by = names(x = DTna)] DTna <- DTna[, id := 1:nrow(x = DTna)] DTna <- DTna[order(n, decreasing = TRUE)] DTna <- DTna[, m := .GRP, by = eval(names(x = DT))] ``` Finally, observations with a particular pattern should be subsetted according to a prespecification (here e.g. 1 for the most frequent pattern). ``` pattern <- 1 i <- DTna[m == pattern, id] DT[i] ``` In summary, I need to find observations which share the same missing data pattern and subsequently subset them according to a prespecification (e.g. the most frequent pattern). Please note that I need to subset `DT` instead of `DTna`. **Question** So far, the above code works as expected, but is there a more elegant way using data.table?<issue_comment>username_1: I would add a grouping column to DT to join and filter on: ``` DT[, nag := do.call(paste0, lapply(.SD, function(x) +is.na(x)))] nagDT = DT[, .N, by=nag][order(-N), nagid := .I][, setorder(.SD, nagid)] # nag N nagid # 1: 10000 4 1 # 2: 00000 2 2 # 3: 00010 2 3 # 4: 11000 1 4 # 5: 01000 1 5 # subsetting my_id = 1L DT[nagDT[nagid == my_id, nag], on=.(nag), nomatch=0] ``` which gives ``` V1 V2 V3 V4 V5 nag 1: NA 1.3306093 -2.1030978 0.06115726 -0.2527502 10000 2: NA 0.2852518 -0.1894425 0.86698633 -0.2099998 10000 3: NA -0.1325032 -0.5201166 -0.94392417 0.6515976 10000 4: NA 0.3199076 -1.0152518 -1.61417902 -0.6458374 10000 ``` If you want to omit the new column in the result: ``` DT[nagDT[nagid == my_id, nag], on=.(nag), nomatch=0, !"nag"] ``` And to also omit the blank columns: ``` DT[nagDT[nagid == my_id, nag], on=.(nag), nomatch=0, !"nag"][, Filter(function(x) !anyNA(x), .SD)] ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: An alternative, which is undoubtedly inferior (but nonetheless provided for variety), is ``` DT[, patCnt := setDT(stack(transpose(DT)))[, paste(+(is.na(values)), collapse=""), by="ind"][, patCnt := .N, by=(V1)]$patCnt] ``` which returns ``` DT V1 V2 V3 V4 V5 patCnt 1: NA NA -1.5062011 -0.9846015 0.12153714 1 2: 1.4176784 -0.08078952 -0.8101335 0.6437340 -0.49474613 2 3: NA -0.08410076 -1.1709337 -0.9182901 0.67985806 4 4: 0.2104999 NA -0.1458075 0.8192693 0.05217464 1 5: NA -0.73361504 2.1431392 -1.0041705 0.29198857 4 6: 0.3841267 -0.75943774 0.6931461 -1.3417511 -1.53291515 2 7: -0.8011166 0.26857593 1.1249757 NA -0.57850361 2 8: -1.5518674 0.52004986 1.6505470 NA -0.34061924 2 9: NA 0.83135928 0.9155882 0.1856450 0.31346976 4 10: NA 0.60328545 1.3042894 -0.5835755 -0.17132227 4 ``` Then subset ``` DT[patCnt == max(patCnt)] V1 V2 V3 V4 V5 patCnt 1: NA -0.08410076 -1.1709337 -0.9182901 0.6798581 4 2: NA -0.73361504 2.1431392 -1.0041705 0.2919886 4 3: NA 0.83135928 0.9155882 0.1856450 0.3134698 4 4: NA 0.60328545 1.3042894 -0.5835755 -0.1713223 4 ``` Upvotes: 2
2018/03/21
326
1,300
<issue_start>username_0: I am using `ObjectOutputStream` to write the data into a file. Following is the code snippet. ``` try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) { oos.writeObject(allObjects); } ``` Questions: 1. Do I need to split the object construction of OOS and FOS separately in try-with-resources? I assume that OOS internally also closes the FOS. So the above code line should be fine. 2. Do I need to explicitly call flush? The problem being I saw once the file was corrupted and while debugging I had the above mentioned queries.<issue_comment>username_1: 1. No: Closing ObjectOutputStream will automatically close FileOutputStream 2. No: The stream will be flushed automatically on close. Upvotes: 4 [selected_answer]<issue_comment>username_2: I believe developers should rely on the published general contract. There is no evidence that an `ObjectOutputStream`'s `close()` method calls `flush()`. OpenJDK's `ObjectOutputStream#close` is just a vendor implementation, I believe. And it won't hurt if we flush on the try-with-resources. ```java try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) { oos.writeObject(allObjects); oos.flush(); // What's possibly going wrong with this? } ``` Upvotes: 2
2018/03/21
526
1,640
<issue_start>username_0: ``` function square(arr) { var result=[].concat(arr); result.forEach(function(i){ i=i*i; console.log(i); }) return result; } var arr=[1,2,3,4]; console.log(square(arr)) ``` The task is to square all elements in an array, now my output is the original array. I wonder why. P.s. the first console.log gives me the output1;4;9;16. the second console.log outputs [1,2,3,4]<issue_comment>username_1: * Re-assigning that value to `i` won't update the original array. * You don't need to concat that array, just initialize that array as empty `[]`. * Add every square value to the new array. ```js function square(arr) { var result = []; arr.forEach(function(i) { i = i * i; result.push(i); }); return result; } var arr = [1, 2, 3, 4]; console.log(square(arr)) ``` Upvotes: 0 <issue_comment>username_2: `forEach` is iterating the array but it is not returning anyvvalue.Use map function which will return a new array with updated result ```js function square(arr) { return arr.map(function(i) { return i * i; }) } var arr = [1, 2, 3, 4]; console.log(square(arr)) ``` If you still intend to use `forEach` push the updated values in an array and return that array Upvotes: 3 [selected_answer]<issue_comment>username_3: You could define a square function for a single value as callback for [`Array#map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) for getting a squared array. ```js function square(v) { return v * v; } var array = [1, 2, 3, 4]; console.log(array.map(square)); ``` Upvotes: 2
2018/03/21
819
2,885
<issue_start>username_0: I have 2 activities. Activity A sends a Number to activity B and activity recieves and uses the Number. The problem is that activity B produces FormatExeption errors. Activty A code: ``` EditText set_limit = findViewById(R.id.editText2); Bundle set_limit_basic = new Bundle(); set_limit_basic.putString("limit_basic", String.valueOf(set_limit)); Intent Aintent = new Intent(A.this, B.class); Aintent.putExtras(set_limit_basic); startActivity(Aintent); ``` Activity B code: ``` Bundle set_limit_basic = getIntent().getExtras(); if (set_limit_basic != null) { String B_string = set_limit_basic.getString("limit_basic"); if ( B_string .trim().length() == 0){ limit_number = Integer.parseInt(B_string); ```<issue_comment>username_1: In `1st Activity` you are trying to use `String.valueOf(edittext);` * ( `set_limit` is a variable of type `EditText` so the string value will be `@djfjckckc78` something like this...which is surely not a number) try ``` String.valueOf(set_limit.getText().toString()); ``` i.e, ``` set_limit_basic.putString("limit_basic",String.valueOf(set_limit.getText().toString())); ``` and also in `Activity B`, ``` if ( B_string .trim().length() > 0){ } ``` > > If you try to convert `String.valueOf(variable)` to a **number** it will throw a `NumberFormatException` at runtime because that string aint a number !! > > > Upvotes: 0 <issue_comment>username_2: Several points: 1. You shouldn't be converting `set_limit` to a string; `set_limit` is an `EditText` widget. Instead, you should be putting the *contents* of the view (the text it is displaying). 2. There's no reason to explicitly construct your own extras bundle. Just use one of the `putExtra` methods defined in the `Intent` class. 3. The error checking is probably better handled in activity A instead of activity B. 4. You seem to have a logic error in activity B, in that you are only attempting to parse the limit number when the trimmed text is empty. That seems backwards. Putting all this together, I'd rewrite your code as follows: Activity A: ``` EditText set_limit = findViewById(R.id.editText2); CharSequence text = set_limit.getText(); if (TextUtils.isEmpty(text)) { // handle case of no text } else { try { int limit_number = Integer.parseInt(text.toString()); Intent intent = new Intent(A.this, B.class); intent.putExtra("limit_basic", limit_number); startActivity(intent); } catch (NumberFormatException e) { // handle case of improperly formatted text } } ``` Activity B: ``` limit_number = getIntExtra("limit_basic", -1 /* or other default value */); // or, if you want to explicitly check for presence of the extra: if (hasExtra("limit_basic")) { limit_number = getIntExtra("limit_basic", -1); } ``` Upvotes: 2 [selected_answer]
2018/03/21
6,325
12,177
<issue_start>username_0: When trying to scrape a web page, this table has no `| | |` tags, and is all tags. The site inspector that I'm trying to scrape looks as follows: [inspector screenshot](https://i.stack.imgur.com/u6bhf.png) I'd like to be able to grab the info from the `table-row` class, but the scrape never returns anything. With the code below, when I scrape the `.table-header`, or just `.practiceDataTable`, I'm able to get the data from that. ``` import bs4 import requests res = requests.get('https://www.nascar.com/results/race_center/2018/monster-energy-nascar-cup-series/auto-club-400/stn/race/') soup = bs4.BeautifulSoup(res.text, 'lxml') soup.select('.nrwgt-lbh .practiceDataTable') for i in soup.select('.nrwgt-lbh .practiceDataTable .table-row'): print(i.text) ``` I also noticed that in the inspector, the class "practiceDataTable" has a space after it and then "dataTable", but when I use that anywhere in the code, the code doesn't work.<issue_comment>username_1: If you want the text from every table-row you can do this: ``` import bs4 import requests res = requests.get('https://www.nascar.com/results/race_center/2018/monster-energy-nascar-cup-series/auto-club-400/stn/race/') soup = bs4.BeautifulSoup(res.text, 'lxml') tds = soup.find_all('div', class_='table-row') for td in tds: print(td.text) ``` Upvotes: 1 <issue_comment>username_2: An inspection of the source from a `urllib.urlopen` object shows that the site is dynamic, as no updated div object with class `table-row` can be found. Thus, you need to use a browser manipulation tool such as `selenium`: ``` from bs4 import BeautifulSoup as soup import re import urllib from selenium import webdriver d = webdriver.Chrome() classes = ['position', 'chase', 'car-number', 'driver', 'manufacturer', 'start-position not-mobile', 'laps not-mobile', 'laps-led not-mobile', 'final-status', 'points not-mobile', 'bonus not-mobile'] d.get('https://www.nascar.com/results/race_center/2018/monster-energy-nascar-cup-series/auto-club-400/stn/race/') new_data = [filter(None, [b.text for b in i.find_all('div', {'class':re.compile('|'.join(classes))})]) for i in soup(d.page_source, 'lxml').find_all('div', {'class':'table-row'})] ``` Output: ``` [[u'00', u'JeffreyEarnhardt'], [u'1', u'JamieMcMurray'], [u'2', u'BradKeselowski'], [u'3', u'AustinDillon'], [u'4', u'KevinHarvick'], [u'6', u'TrevorBayne'], [u'9', u'ChaseElliott'], [u'10', u'AricAlmirola'], [u'11', u'DennyHamlin'], [u'12', u'RyanBlaney'], [u'13', u'TyDillon'], [u'14', u'ClintBowyer'], [u'15', u'RossChastain'], [u'17', u'RickyStenhouse Jr.'], [u'18', u'KyleBusch'], [u'19', u'DanielSuarez'], [u'20', u'ErikJones'], [u'21', u'PaulMenard'], [u'22', u'JoeyLogano'], [u'23', u'GrayGaulding'], [u'24', u'WilliamByron'], [u'31', u'RyanNewman'], [u'32', u'MattDiBenedetto'], [u'34', u'MichaelMcDowell'], [u'37', u'ChrisBuescher'], [u'38', u'DavidRagan'], [u'41', u'KurtBusch'], [u'42', u'KyleLarson'], [u'43', u'DarrellWallace Jr.'], [u'47', u'AJAllmendinger'], [u'48', u'JimmieJohnson'], [u'51', u'TimmyHill'], [u'55', u'ReedSorenson'], [u'72', u'ColeWhitt'], [u'78', u'MartinTruex Jr.'], [u'88', u'AlexBowman'], [u'95', u'KaseyKahne'], [u'1', u'4', u'KevinHarvick'], [u'2', u'14', u'ClintBowyer'], [u'3', u'10', u'AricAlmirola'], [u'4', u'31', u'RyanNewman'], [u'5', u'42', u'KyleLarson'], [u'6', u'11', u'DennyHamlin'], [u'7', u'78', u'MartinTruex Jr.'], [u'8', u'20', u'ErikJones'], [u'9', u'3', u'AustinDillon'], [u'10', u'88', u'AlexBowman'], [u'11', u'1', u'JamieMcMurray'], [u'12', u'18', u'KyleBusch'], [u'13', u'41', u'KurtBusch'], [u'14', u'48', u'JimmieJohnson'], [u'15', u'9', u'ChaseElliott'], [u'16', u'37', u'ChrisBuescher'], [u'17', u'22', u'JoeyLogano'], [u'18', u'43', u'DarrellWallace Jr.'], [u'19', u'21', u'PaulMenard'], [u'20', u'2', u'BradKeselowski'], [u'21', u'19', u'DanielSuarez'], [u'22', u'32', u'MattDiBenedetto'], [u'23', u'12', u'RyanBlaney'], [u'24', u'13', u'TyDillon'], [u'25', u'17', u'RickyStenhouse Jr.'], [u'26', u'24', u'WilliamByron'], [u'27', u'47', u'AJAllmendinger'], [u'28', u'6', u'TrevorBayne'], [u'29', u'34', u'MichaelMcDowell'], [u'30', u'38', u'DavidRagan'], [u'31', u'95', u'KaseyKahne'], [u'32', u'15', u'RossChastain'], [u'33', u'72', u'ColeWhitt'], [u'34', u'00', u'JeffreyEarnhardt'], [u'35', u'51', u'TimmyHill'], [u'36', u'*55', u'ReedSorenson'], [u'37', u'23', u'GrayGaulding'], [u'1', u'78', u'MartinTruex Jr.'], [u'2', u'18', u'KyleBusch'], [u'3', u'42', u'KyleLarson'], [u'4', u'20', u'ErikJones'], [u'5', u'3', u'AustinDillon'], [u'6', u'22', u'JoeyLogano'], [u'7', u'41', u'KurtBusch'], [u'8', u'12', u'RyanBlaney'], [u'9', u'31', u'RyanNewman'], [u'10', u'4', u'KevinHarvick'], [u'11', u'2', u'BradKeselowski'], [u'12', u'37', u'ChrisBuescher'], [u'13', u'6', u'TrevorBayne'], [u'14', u'21', u'PaulMenard'], [u'15', u'1', u'JamieMcMurray'], [u'16', u'17', u'RickyStenhouse Jr.'], [u'17', u'13', u'TyDillon'], [u'18', u'32', u'MattDiBenedetto'], [u'19', u'43', u'DarrellWallace Jr.'], [u'20', u'23', u'GrayGaulding'], [u'21', u'38', u'DavidRagan'], [u'22', u'34', u'MichaelMcDowell'], [u'23', u'00', u'JeffreyEarnhardt'], [u'24', u'55', u'ReedSorenson'], [u'25', u'11', u'DennyHamlin'], [u'26', u'14', u'ClintBowyer'], [u'27', u'10', u'AricAlmirola'], [u'28', u'88', u'AlexBowman'], [u'29', u'24', u'WilliamByron'], [u'30', u'19', u'DanielSuarez'], [u'31', u'9', u'ChaseElliott'], [u'32', u'47', u'AJAllmendinger'], [u'33', u'48', u'JimmieJohnson'], [u'34', u'95', u'KaseyKahne'], [u'35', u'51', u'TimmyHill'], [u'36', u'15', u'RossChastain'], [u'37', u'72', u'ColeWhitt'], [u'1', u'78', u'MartinTruex Jr.', u'1', u'200', u'125', u'Running', u'60', u'7'], [u'2', u'42', u'KyleLarson', u'3', u'200', u'0', u'Running', u'43', u'0'], [u'3', u'18', u'KyleBusch', u'2', u'200', u'62', u'Running', u'51', u'0'], [u'4', u'2', u'BradKeselowski', u'11', u'200', u'0', u'Running', u'49', u'0'], [u'5', u'22', u'JoeyLogano', u'6', u'200', u'9', u'Running', u'45', u'0'], [u'6', u'11', u'DennyHamlin', u'25', u'200', u'1', u'Running', u'39', u'0'], [u'7', u'20', u'ErikJones', u'4', u'200', u'0', u'Running', u'39', u'0'], [u'8', u'12', u'RyanBlaney', u'8', u'200', u'0', u'Running', u'29', u'0'], [u'9', u'48', u'JimmieJohnson', u'33', u'200', u'0', u'Running', u'38', u'0'], [u'10', u'3', u'AustinDillon', u'5', u'200', u'0', u'Running', u'27', u'0'], [u'11', u'14', u'ClintBowyer', u'26', u'199', u'0', u'Running', u'30', u'0'], [u'12', u'10', u'AricAlmirola', u'27', u'199', u'0', u'Running', u'25', u'0'], [u'13', u'88', u'AlexBowman', u'28', u'199', u'0', u'Running', u'24', u'0'], [u'14', u'41', u'KurtBusch', u'7', u'199', u'0', u'Running', u'27', u'0'], [u'15', u'24', u'WilliamByron', u'29', u'199', u'1', u'Running', u'23', u'0'], [u'16', u'9', u'ChaseElliott', u'31', u'199', u'0', u'Running', u'21', u'0'], [u'17', u'1', u'JamieMcMurray', u'15', u'199', u'1', u'Running', u'20', u'0'], [u'18', u'17', u'RickyStenhouse Jr.', u'16', u'199', u'0', u'Running', u'19', u'0'], [u'19', u'21', u'PaulMenard', u'14', u'199', u'0', u'Running', u'18', u'0'], [u'20', u'43', u'DarrellWallace Jr.', u'19', u'199', u'0', u'Running', u'17', u'0'], [u'21', u'31', u'RyanNewman', u'9', u'199', u'0', u'Running', u'16', u'0'], [u'22', u'47', u'AJAllmendinger', u'32', u'199', u'0', u'Running', u'15', u'0'], [u'23', u'19', u'DanielSuarez', u'30', u'199', u'0', u'Running', u'14', u'0'], [u'24', u'95', u'KaseyKahne', u'34', u'199', u'1', u'Running', u'13', u'0'], [u'25', u'38', u'DavidRagan', u'21', u'199', u'0', u'Running', u'12', u'0'], [u'26', u'34', u'MichaelMcDowell', u'22', u'199', u'0', u'Running', u'11', u'0'], [u'27', u'13', u'TyDillon', u'17', u'198', u'0', u'Running', u'10', u'0'], [u'28', u'72', u'ColeWhitt', u'37', u'198', u'0', u'Running', u'9', u'0'], [u'29', u'15', u'RossChastain', u'36', u'198', u'0', u'Running', u'0', u'0'], [u'30', u'37', u'ChrisBuescher', u'12', u'197', u'0', u'Running', u'7', u'0'], [u'31', u'32', u'MattDiBenedetto', u'18', u'196', u'0', u'Running', u'6', u'0'], [u'32', u'23', u'GrayGaulding', u'20', u'194', u'0', u'Running', u'5', u'0'], [u'33', u'51', u'TimmyHill', u'35', u'193', u'0', u'Running', u'0', u'0'], [u'34', u'55', u'ReedSorenson', u'24', u'193', u'0', u'Running', u'3', u'0'], [u'35', u'4', u'KevinHarvick', u'10', u'191', u'0', u'Running', u'2', u'0'], [u'36', u'00', u'JeffreyEarnhardt', u'23', u'189', u'0', u'Running', u'1', u'0'], [u'37', u'6', u'TrevorBayne', u'13', u'108', u'0', u'Accident', u'1', u'0'], [u'1', u'78', u'MartinTruex Jr.', u'60'], [u'2', u'18', u'KyleBusch', u'60'], [u'3', u'22', u'JoeyLogano', u'60'], [u'4', u'2', u'BradKeselowski', u'60'], [u'5', u'48', u'JimmieJohnson', u'60'], [u'6', u'42', u'KyleLarson', u'60'], [u'7', u'41', u'KurtBusch', u'60'], [u'8', u'20', u'ErikJones', u'60'], [u'9', u'14', u'ClintBowyer', u'60'], [u'10', u'11', u'DennyHamlin', u'60'], [u'11', u'3', u'AustinDillon', u'60'], [u'12', u'1', u'JamieMcMurray', u'60'], [u'13', u'10', u'AricAlmirola', u'60'], [u'14', u'9', u'ChaseElliott', u'60'], [u'15', u'24', u'WilliamByron', u'60'], [u'16', u'19', u'DanielSuarez', u'60'], [u'17', u'21', u'PaulMenard', u'60'], [u'18', u'88', u'AlexBowman', u'60'], [u'19', u'6', u'TrevorBayne', u'60'], [u'20', u'37', u'ChrisBuescher', u'60'], [u'21', u'31', u'RyanNewman', u'60'], [u'22', u'17', u'RickyStenhouse Jr.', u'60'], [u'23', u'95', u'KaseyKahne', u'60'], [u'24', u'38', u'DavidRagan', u'59'], [u'25', u'34', u'MichaelMcDowell', u'59'], [u'26', u'43', u'DarrellWallace Jr.', u'59'], [u'27', u'32', u'MattDiBenedetto', u'59'], [u'28', u'47', u'AJAllmendinger', u'59'], [u'29', u'15', u'RossChastain', u'59'], [u'30', u'72', u'ColeWhitt', u'59'], [u'31', u'13', u'TyDillon', u'59'], [u'32', u'12', u'RyanBlaney', u'59'], [u'33', u'23', u'GrayGaulding', u'58'], [u'34', u'55', u'ReedSorenson', u'58'], [u'35', u'51', u'TimmyHill', u'58'], [u'36', u'4', u'KevinHarvick', u'57'], [u'37', u'00', u'JeffreyEarnhardt', u'56'], [u'1', u'78', u'MartinTruex Jr.', u'120'], [u'2', u'2', u'BradKeselowski', u'120'], [u'3', u'18', u'KyleBusch', u'120'], [u'4', u'11', u'DennyHamlin', u'120'], [u'5', u'20', u'ErikJones', u'120'], [u'6', u'22', u'JoeyLogano', u'120'], [u'7', u'48', u'JimmieJohnson', u'120'], [u'8', u'42', u'KyleLarson', u'120'], [u'9', u'14', u'ClintBowyer', u'120'], [u'10', u'24', u'WilliamByron', u'120'], [u'11', u'41', u'KurtBusch', u'120'], [u'12', u'10', u'AricAlmirola', u'120'], [u'13', u'31', u'RyanNewman', u'120'], [u'14', u'9', u'ChaseElliott', u'120'], [u'15', u'88', u'AlexBowman', u'120'], [u'16', u'1', u'JamieMcMurray', u'120'], [u'17', u'19', u'DanielSuarez', u'120'], [u'18', u'3', u'AustinDillon', u'120'], [u'19', u'12', u'RyanBlaney', u'120'], [u'20', u'17', u'RickyStenhouse Jr.', u'120'], [u'21', u'37', u'ChrisBuescher', u'120'], [u'22', u'95', u'KaseyKahne', u'120'], [u'23', u'38', u'DavidRagan', u'120'], [u'24', u'47', u'AJAllmendinger', u'120'], [u'25', u'43', u'DarrellWallace Jr.', u'120'], [u'26', u'34', u'MichaelMcDowell', u'120'], [u'27', u'32', u'MattDiBenedetto', u'120'], [u'28', u'15', u'RossChastain', u'119'], [u'29', u'21', u'PaulMenard', u'119'], [u'30', u'72', u'ColeWhitt', u'119'], [u'31', u'13', u'TyDillon', u'118'], [u'32', u'23', u'GrayGaulding', u'117'], [u'33', u'55', u'ReedSorenson', u'116'], [u'34', u'51', u'TimmyHill', u'115'], [u'35', u'00', u'JeffreyEarnhardt', u'114'], [u'36', u'4', u'KevinHarvick', u'113'], [u'37', u'6', u'TrevorBayne', u'108']] ``` Edit: to install selenium, run `pip install selenium`, and then install the appropriate bindings for your browser: Chrome driver: <https://sites.google.com/a/chromium.org/chromedriver/downloads> Firefox driver: <https://github.com/mozilla/geckodriver/releases> Then, to run the code, create a driver object with the classname corresponding to your browser of choice, passing the path to the driver: ``` d = webdriver.Firefox("/path/to/driver") ``` or ``` d = webdriver.Chrome("/path/to/driver") ``` **Edit** Writing data to csv file: ``` import csv write = csv.writer(open('nascarDrivers.csv', 'w')) write.writerows(new_data) #new_data is the list of lists containing the table data ``` Upvotes: 3 [selected_answer]
2018/03/21
848
3,111
<issue_start>username_0: I started learning angular 5 3 days ago so I'm quite new at it. I also use angularJS and React to develop applications and I think I don't understand how angular 5 components fully work. If I create for example a custom button that has a custom text inside (I'm not saying this should be done this way but it's a simple example that shows my point) like this: ``` My Text ``` The rendered DOM results in: ``` My Text ``` which is unreadable, I wanted to know if there's a way to remove this wrapping elements and just place the components layout replacing the tags resulting in the following structure: ``` My Text ``` If there's no way of removing them what are your suggestions? thanks!<issue_comment>username_1: Angular components are directives with templates. [According to this](https://angular.io/guide/cheatsheet#cheat-sheet): > > Directive configuration @Directive({ property1: value1, ... }) > > > selector: '.cool-button:not(a)' Specifies a CSS selector that > identifies this directive within a template. Supported selectors > include element, [attribute], .class, and :not(). > > > So component selectors can be also attribute selectors. For your example, instead of writing this: **parent.component.html:** ``` My Text ``` write this: **parent.component.html:** ``` My Text ``` where : **app-button.component.ts** ``` ... selector: '[app-button]', template: ` ... ``` **app-text.component.ts** ``` ... selector: '[app-text]', template: `` ... ``` this would be rendered as you expected: [![enter image description here](https://i.stack.imgur.com/AgLeo.png)](https://i.stack.imgur.com/AgLeo.png) **Update after your comment about styling those buttons:** To style the buttons from inside the button component, and set class in parent component, use `:host-context` pseudo-class. It is not deprecated and works well **button.component.css** ``` :host-context(.button-1) { background: red; } :host-context(.button-2) { background: blue; } ``` **app.component.html** ``` My Text My Text ``` Here is the [DEMO](https://stackblitz.com/edit/angular-wujdwm) Upvotes: 4 [selected_answer]<issue_comment>username_2: I had a similar issue. I'll provide my solution in case someone else has the same problem. My component should be able to be used either within other components or as a route from . When I used the selector as an attribute `[my-component]` things worked perfectly provided it was used within other components. But when created by a were created automatically. To avoid that, we can simply **use multiple selectors**, and consider that the selectors can be combined. Consider this: I want my component to use the attribute `my-component` and if it ever should be created by the it should be wrapped in a . To achieve this simply use: ``` @Component( selector: 'section[my-component], my-component', ... ) ``` The result will be, if used inside another tag: ``` ... component content ... ``` If used as a route: ``` ... component content ... ``` Upvotes: 2
2018/03/21
1,090
3,424
<issue_start>username_0: I have created a template for send out emails to clients of the new user I have created. The current code have it to remove the space and add a period. For Example: **<NAME>** will be turned into **<EMAIL>** ``` StringReplace, UserID, UserID, %A_SPACE%, . , All ``` I would like to create a script to remove the space and letters up to the first letter creating **<EMAIL>** Here is the current script I have: ``` InputBox, ClientE, Client Name, Please type the name of Company if ClientE = test { EmailE = test.com } if (A_hour >= 12) { InputBox, UserID, User's Name, Please type the user's name InputBox, PASSWE, Password, Please type the password sleep, 700 Send, Good Afternoon ,{Enter 2}This e-mail is to inform you that the requested new user account for{space} Send, ^b Send, %UserID% Send, ^b Send, {space}has been created as follows;{ENTER 2} StringReplace, UserID, UserID, %A_SPACE%, . , All Send, Desktop user name = %UserID% {ENTER}E-mail address = %UserID%@%EmailE%{SPACE} {ENTER}Password = {SPACE}{ENTER 2}Please let me know if you need anything further.{ENTER 2}Best regards,{ENTER 2}<NAME> } else { InputBox, UserID, User's Name, Please type which user sleep, 700 Send, Good Morning ,{Enter 2}This e-mail is to inform you that the requested new user account for{space} Send, ^b Send, %UserID% Send, ^b Send, {space}has been created as follows;{ENTER 2} StringReplace, UserID, UserID, %A_SPACE%, . , All Send, Desktop user name = Send, ^b Send, %UserID% Send, ^b Send, {ENTER}E-mail address = %UserID%@%EmailE%{SPACE} {ENTER}Password = Send, ^b Send, %PASSWE% Send, ^b Send, {SPACE}{ENTER 2}Please let me know if you need anything further.{ENTER 2}Best regards,{ENTER 2} } return ```<issue_comment>username_1: ``` UserID := "John Smith" stringSplit, user_first_last, UserID, %A_Space% StringLeft, first_initial, user_first_last1, 1 email := first_initial . user_first_last2 . "@test.com" msgbox, %email% return ``` Upvotes: 1 <issue_comment>username_2: Here is the code with the updated/additional scrit ``` { if (A_hour >=12) { RTYH = Good Afternoon } Else { RTYH = Good Morning } InputBox, ClientE, Client Name, Please type the name of Company InputBox, UserID, User's Name, Please type the user's name ;InputBox, PASSWE, Password, Please type the password sleep, 700 Send, %RTYH% ,{Enter 2}This e-mail is to inform you that the requested new user account for{space} Send, ^b Send, %UserID% Send, ^b Send, {space}has been created as follows;{ENTER 2} if ClientE = test { UserID := UserID stringSplit, user_first_last, UserID, %A_Space% StringLeft, first_initial, user_first_last1, 1 UserID4 := first_initial . user_first_last2 UserID5 := first_initial . user_first_last2 . "@test.com" } if ClientE = testing { UserID := UserID stringSplit, user_first_last, UserID, %A_Space% StringReplace, UserID4, UserID, %A_SPACE%, . , All UserID4 := UserID4 UserID5 := UserID4 . "@testing.com" } Send, Desktop user name = Send, ^b Send, %UserID4% Send, ^b Send, {ENTER}E-mail address = %UserID5%{SPACE} {ENTER}Password ={SPACE}{ENTER 2}Please let me know if you need anything further.{ENTER 2}Best regards,{ENTER 2} } return ``` Upvotes: 0
2018/03/21
750
2,324
<issue_start>username_0: How can I raise an exception if `loadid` is `null` when I compare `loadid = V_LOAD_ID`? `E_NULL_ID` is the exception which I then wanted to use. Here is my procedure: ``` CREATE OR REPLACE PROCEDURE GET_INFO(P_CURDATE DATE) AS V_LOAD_ID CARSALES.LOADID%TYPE; E_NULL_ID EXCEPTION; BEGIN -- Get load id from LoadIds table for current date. SELECT LoadId INTO V_LOAD_ID FROM LoadIds WHERE DateLoad = P_CURDATE; -- Select brand name and total sales. SELECT BrandName, SUM(Cost) FROM CarSales Sales INNER JOIN CarLables Lables ON Lables.CarBrandId = Sales.CarBrandId WHERE LoadId = V_LOAD_ID GROUP BY CarBrandId EXCEPTION WHEN E_NULL_ID THEN DMBS.OUTPUT.PUT_LINE('No loadId found'); END; ```<issue_comment>username_1: ``` UserID := "<NAME>" stringSplit, user_first_last, UserID, %A_Space% StringLeft, first_initial, user_first_last1, 1 email := first_initial . user_first_last2 . "@test.com" msgbox, %email% return ``` Upvotes: 1 <issue_comment>username_2: Here is the code with the updated/additional scrit ``` { if (A_hour >=12) { RTYH = Good Afternoon } Else { RTYH = Good Morning } InputBox, ClientE, Client Name, Please type the name of Company InputBox, UserID, User's Name, Please type the user's name ;InputBox, PASSWE, Password, Please type the password sleep, 700 Send, %RTYH% ,{Enter 2}This e-mail is to inform you that the requested new user account for{space} Send, ^b Send, %UserID% Send, ^b Send, {space}has been created as follows;{ENTER 2} if ClientE = test { UserID := UserID stringSplit, user_first_last, UserID, %A_Space% StringLeft, first_initial, user_first_last1, 1 UserID4 := first_initial . user_first_last2 UserID5 := first_initial . user_first_last2 . "@test.com" } if ClientE = testing { UserID := UserID stringSplit, user_first_last, UserID, %A_Space% StringReplace, UserID4, UserID, %A_SPACE%, . , All UserID4 := UserID4 UserID5 := UserID4 . "@testing.com" } Send, Desktop user name = Send, ^b Send, %UserID4% Send, ^b Send, {ENTER}E-mail address = %UserID5%{SPACE} {ENTER}Password ={SPACE}{ENTER 2}Please let me know if you need anything further.{ENTER 2}Best regards,{ENTER 2} } return ``` Upvotes: 0
2018/03/21
299
1,261
<issue_start>username_0: I have an java api which give me as parameter as type: `modelClass: Class` with this parameter I want to call a kotlin reified method : `intance()`. It's possible to pass my modelClass as parameter? I have no access to the source code of the reified method.<issue_comment>username_1: This is not possible. When calling an inline function with a reified type parameter, you need to provide a class which is known at compile time, and references to that class will be substituted directly into the body of the function where the inline function is invoked. Classes which are only known at runtime cannot be handled in that way. Upvotes: 4 <issue_comment>username_2: It's possible if you can modify the source of the Kotlin class. You have to delegate the implementation of the inline/reified function to a non-inline one: ``` class Foo { inline fun myMethod() = myMethod(T::class.java) fun myMethod(type: Class) { // implementation here } } ``` This is always good practice if you expect your code to be called from Java projects. And even if it's Kotlin-only, this is a good way to go from `inline` to not `inline`, allowing you to actually call private implementation methods from your exposed `inline` method. Upvotes: 0
2018/03/21
768
2,111
<issue_start>username_0: What I want is the first loop iterating from `1` to `4` and the second loop from `5` to `6`. Here is my code: ``` php for ($i = 1 ; $i <= 4 ; $i++) { echo $i . "<br"; } ?> --- php for ($i = 1 ; $i <= 2 ; $i++) { echo $i . "<br"; } ?> ```<issue_comment>username_1: Your problem ------------ The second `for` loop resets your `$i` variable to `1`: ``` for ($i = 1 ; $i <= 2 ; $i++) ``` Solution -------- You can use a [`while` loop](https://www.w3schools.com/php/php_looping.asp) instead of your second `for` loop: ``` php for ($i = 1; $i <= 4; $i++) { echo $i . "<br"; } ?> --- php while ($i <= 6) // `<= 6` instead of `<= 2`, since we keep $1's value { echo $i . "<br"; $i++; } ?> ``` Upvotes: 1 <issue_comment>username_2: The loops you've given are: 1st loop: from 1 to 4 2nd loop: from 1 to 2 First loop is ok, but seconds needs to be modified. Use `$i<=6` and don't initialize `$i` variable. This will give you: 1st loop: from 1 to 4 2nd loop: from (value that 1st loop have ended)+1 to 6, so (4+1) to 6, 5 to 6 ``` php $i = 0; // be sure 'i' is visible in both loops for ($i=1; $i<=4; $i++) // form 1 to 4 { echo $i . "<br"; } ?> --- php $i++; // start from 5, not 4 for (; $i<=6; $i++) // from the previous value to 6 { echo $i . "<br"; } ?> ``` Upvotes: 2 <issue_comment>username_3: Rather than using two loops for this, why not just output the `---` tag at the appropriate point within the same one? If you carry on with adding extra loops, first of all you'll run into confusing problems like this about (re-)initialising variables, and you'll also quickly end up with a lot of unnecessary duplicated code. You can use the [PHP modulo operator (%)](http://php.net/manual/en/language.operators.arithmetic.php) to output the `---` tag after every fourth element, which will both reduce the complexity and be a lot more extensible if you later add more elements: ``` for ($i=1; $i<=6; $i++) { echo $i . " "; if ($i % 4 === 0) { echo " --- "; } } ``` See <https://eval.in/976102> Upvotes: -1
2018/03/21
1,120
3,570
<issue_start>username_0: When I run my program my 'if' statement is compiled as unreachable code which in turn, causes my contains method to continuously print false even though the number exists within the tree. I can't figure out why could any one help me please? I'm fairly new to programming. Here is my node class. ``` class Node where T : IComparable { private T data; private int balanceFactor = 0; //added for AVLTree public Node Left, Right; public Node(T item) { data = item; Left = null; Right = null; } public T Data { set { data = value; } get { return data; } } } ``` Here is my binary search tree class. ``` class BSTree : BinTree where T : IComparable { //root declared as protected in Parent Class – Binary Tree public BSTree() { root = null; } public void InsertItem(T item) { insertItem(item, ref root); } private void insertItem(T item, ref Node tree) { if (tree == null) tree = new Node(item); else if (item.CompareTo(tree.Data) < 0) insertItem(item, ref tree.Left); else if (item.CompareTo(tree.Data) > 0) insertItem(item, ref tree.Right); } public int Height() //Return the max level of the tree { return Height(root); } protected int Height(Node current) { if (current == null) return 0; return 1 + Math.Max(Height(current.Left), Height(current.Right)); } public int Count() //Return the number of nodes in the tree { return Height(root); } public int Count(ref Node current) //Return the number of nodes in the tree { int counter = 0; if (current == null) { return 0; } else if (current.Left != null) { counter += Count(ref current.Left); counter++; } if (current.Right != null) { counter += Count(ref current.Right); counter++; } return counter; } public Boolean Contains(T item) //Return true if the item is contained in the BSTree, false //otherwise. { Node current = root; if (current.Data.CompareTo(item) == 0) { { return true; } if (current.Data.CompareTo(item) > 0) { current = current.Left; } if (current.Data.CompareTo(item) < 0) { current = current.Right; } } return false; } private T leastItem(Node tree) { if (tree.Left == null) return tree.Data; else return leastItem(tree.Left); } } ``` Lastly my main class. ``` class Program { static void Main(string[] args) { BSTree treeBranch = new BSTree(); treeBranch.InsertItem(77); treeBranch.InsertItem(20); treeBranch.InsertItem(37); treeBranch.InsertItem(15); treeBranch.InsertItem(22); treeBranch.InsertItem(30); Console.WriteLine(treeBranch.Count()); Console.WriteLine(treeBranch.Height()); Console.WriteLine(treeBranch.Contains(15)); string InOrder = "in order :"; treeBranch.InOrder(ref InOrder); Console.WriteLine(InOrder); Console.WriteLine("\n"); Console.ReadKey(); } } ```<issue_comment>username_1: To many `{` and `}` in this code ``` if (current.Data.CompareTo(item) == 0) { { return true; } ``` Upvotes: 1 <issue_comment>username_2: ``` if (current.Data.CompareTo(item) == 0) { { <==== here return true; } if (current.Data.CompareTo(item) > 0) { current = current.Left; } if (current.Data.CompareTo(item) < 0) { current = current.Right; } } ``` There's no condition to `return true;`. Change your code to this: ``` if (current.Data.CompareTo(item) == 0) { return true; } else if (current.Data.CompareTo(item) > 0) { current = current.Left; } else if (current.Data.CompareTo(item) < 0) { current = current.Right; } ``` Upvotes: 3
2018/03/21
489
1,617
<issue_start>username_0: I'm trying to implement a vue2 `modal` as described in the vue docs at <https://v2.vuejs.org/v2/examples/modal.html>. It looks something like this: ``` | | | | | --- | --- | --- | | @{{ item.name }} | | Show Modal | ### Hello World Vue.component('modal', { template: '#modal-template', data: function() { return { item: '' } } }); ``` While the button shows up and does pop up the modal, I get a warning that `Property or method "item" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.`, and when I inspect the `modal` component in the Vue dev tools, the `item` is still `''`, it's not populated by the `:item` binding. What's the right way to pass the `item` object into the modal so we can use it in the window?<issue_comment>username_1: To many `{` and `}` in this code ``` if (current.Data.CompareTo(item) == 0) { { return true; } ``` Upvotes: 1 <issue_comment>username_2: ``` if (current.Data.CompareTo(item) == 0) { { <==== here return true; } if (current.Data.CompareTo(item) > 0) { current = current.Left; } if (current.Data.CompareTo(item) < 0) { current = current.Right; } } ``` There's no condition to `return true;`. Change your code to this: ``` if (current.Data.CompareTo(item) == 0) { return true; } else if (current.Data.CompareTo(item) > 0) { current = current.Left; } else if (current.Data.CompareTo(item) < 0) { current = current.Right; } ``` Upvotes: 3
2018/03/21
1,106
4,292
<issue_start>username_0: i'm trying to run a docker container on Windows 10 which should execute a windows executable (myprogram.exe). Below you find my dockerfile: ``` FROM microsoft/windowsservercore COPY mydir/myprogram.exe /mydir/ CMD ["/mydir/myprogram.exe","someparameter"] ``` So i build the image with: `docker image build --tag myimage .` and run the container with: `docker run myimage` Unfortunately if I check the status of the container with: `docker ps -a` I can see that the container has exited with > > exit code 3221225781 > > > , which seems to point to a missing dll. To debug the problem I run the command: `docker run -it --name debug microsoft/windowsservercore cmd`, stopped the container and copied the windows executable in the container file system : `docker cp myprogram.exe debug:c:/myprogram.exe` Now I start the container again using `docker start -i debug` and enter `myprogram.exe myparameter`. Unfortunately the program exits immediately (usually it runs about 30 sec) without any output, error code ... My only explanation for this behavior is that if some cmd program is missing some dll's the corresponding error message is not included in the STDERR but rather in a message dialog. Apparently docker doesn't support this feature??? So what is the best was to solve this problem. Using dependency walker to go through all dll's needed is possible but would take some time and I'm looking for some more elegant solution.<issue_comment>username_1: This is quite an open-ended question, so it is not possible to give precise answer. Here are a few thoughts: 1. This is *your* program that is missing a dependency. Presumably, you as the program author should be aware of what dependencies are required. You need to make sure to include them in your docker image, when you build it. 2. You are creating your image based on Windows Core, which does not have the whole slew of UI components. This looks like the most obvious thing that could go wrong, given the symptoms. So what I would do is try and make sure that your program can run on Windows Core in principle. Which brings me to the next point. 3. The most practical way to troubleshoot, in my opinion, is to remove Docker from the equation. You want to run your program on Windows Core. So setup a machine (physical or VM) with Windows Core inside and try to run your program there. There is a good chance that it won't run with the same symptoms. If that's the case, you now have reduced complexity, because you know that your problem has nothing to do with docker (or not). 4. Finally, when you have your Windows Core machine up and running, you might be able to see a message box pop up with the error immediately (even on Core you can run some programs with UI can run, and message boxes are not an uncommon site), and failing that you can run sysinternals procmon/procexp even on Windows Core, so using those to locate missing dependencies could help. There is also [Dependencies](https://github.com/lucasg/Dependencies). *Note: by "Windows Core" in this answer I mean [Core option of Windows Server](https://learn.microsoft.com/en-us/windows-server/administration/server-core/what-is-server-core)* Upvotes: 2 <issue_comment>username_2: You need to install Visual C++ redistributable. 1. Download the appropriate version of vc\_redist.x64.exe and place it in the folder containing your Dockerfile 2. Edit your Dockerfile so you preinstall VC++ redistributables when you build your image by adding: FROM **mcr.microsoft.com/windows/sservercore** WORKDIR c:\mydir **COPY "vc\_redist.x64.exe" .** **RUN vc\_redist.x64.exe /install /passive /norestart /log out.txt** COPY mydir/myprogram.exe c:\mydir CMD ["c:\mydir\myprogram.exe","someparameter"] Your application should run now. Note: you need 64-bit build of VC++ redistributable and the appropriate version. You can find some download urls [here](https://blogs.technet.microsoft.com/jagbal/2017/09/04/where-can-i-download-the-old-visual-c-redistributables/) Upvotes: 4 [selected_answer]<issue_comment>username_3: I went to <http://www.dependencywalker.com/>, downloaded the program and opened my .exe with it to find out what the dependencies were. It came in handy because I didn't have any exit log either. Upvotes: 0
2018/03/21
1,643
4,734
<issue_start>username_0: I have this array : ``` var res_data = [ {"id": "1", "text": "AAA", "category": "food", "value": "1"}, {"id": "2", "text": "BBB", "category": "food", "value": "2"}, {"id": "3", "text": "CCC", "category": "drinks", "value": "3"} ]; ``` I want to get this ``` { "food": [ { "id": "1", "text": "AAA", "category": "food", "value": "1" }, { "id": "2", "text": "BBB", "category": "food", "value": "2" } ], "drinks": [ { "id": "3", "text": "CCC", "category": "drinks", "value": "3" } ] } ``` I've tried to do so by iterating and set the "category" value - as a key , inside a new array, like this : ``` var res = []; $.each(obj, function () { if (this.hasOwnProperty("category")) { res[this['category']] = this; console.log(this['category']); } }) ``` but the "food" index is keep overriding.... ``` drinks:{id: "3", text: "CCC", category: "drinks", value: "3"} food: {id: "3", text: "CCC", category: "food", value: "2"} ```<issue_comment>username_1: A common iteration technique when converting an array into another structure is to use reduction: ```js const arr = [ {"id": "1", "text": "AAA", "category": "food", "value": "1"}, {"id": "2", "text": "BBB", "category": "food", "value": "2"}, {"id": "3", "text": "CCC", "category": "drinks", "value": "3"} ] const result = arr.reduce((hash, item) => { if (!hash.hasOwnProperty(item.category)) { hash[item.category] = [] } hash[item.category].push(item) return hash }, {}) console.log(result) ``` Upvotes: 2 <issue_comment>username_2: Assuming a valid output, you can use the function `reduce`. ```js var data = [ {"id": "1", "text": "AAA", "category": "food", "value": "1"}, {"id": "2", "text": "BBB", "category": "food", "value": "2"}, {"id": "3", "text": "CCC", "category": "drinks", "value": "3"}], result = data.reduce((a, c) => { (a[c.category] || (a[c.category] = [])).push(c); return a; }, {}); console.log(result); ``` Upvotes: 1 <issue_comment>username_3: ```js var res_data = [ {"id": "1", "text": "AAA", "category": "food", "value": "1"}, {"id": "2", "text": "BBB", "category": "food", "value": "2"}, {"id": "3", "text": "CCC", "category": "drinks", "value": "3"} ]; var result = {}; for(var i = 0; i < res_data.length; i++){ if(result[res_data[i].category] == undefined) result[res_data[i].category] = []; result[res_data[i].category].push(res_data[i]) } console.log(result) ``` Upvotes: 2 <issue_comment>username_4: Try this: ``` var res_data = [ {"id": "1", "text": "AAA", "category": "food", "value": "1"}, {"id": "2", "text": "BBB", "category": "food", "value": "2"}, {"id": "3", "text": "CCC", "category": "drinks", "value": "3"} ]; function filter(arr, key, value) { var res = []; for(var x = 0, max = arr.length; x < max; x = x + 1) { if(typeof arr[x] === 'object' && arr[x].hasOwnProperty(key) && arr[x][key] === value) { res.push(arr[x]); } } return res; } ``` Then you can filter by any property like this: ``` filter(res_data, 'category', 'food'); ``` It will return: ``` [ {"id": "1", "text": "AAA", "category": "food", "value": "1"}, {"id": "2", "text": "BBB", "category": "food", "value": "2"} ] ``` Upvotes: 0 <issue_comment>username_5: You can also use [`forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) for array. > > ES5 > > > ```js var arr = [{ "id": "1", "text": "AAA", "category": "food", "value": "1" }, { "id": "2", "text": "BBB", "category": "food", "value": "2" }, { "id": "3", "text": "CCC", "category": "drinks", "value": "3" } ], outpt = {}; arr.forEach(function(item) { if (!outpt.hasOwnProperty(item.category)) { outpt[item.category] = [] } outpt[item.category].push(item) }); console.log(outpt) ``` > > ES6 > > > ```js let arr = [{ "id": "1", "text": "AAA", "category": "food", "value": "1" }, { "id": "2", "text": "BBB", "category": "food", "value": "2" }, { "id": "3", "text": "CCC", "category": "drinks", "value": "3" } ], outpt = {}; arr.forEach((item) => { if (!outpt.hasOwnProperty(item.category)) { outpt[item.category] = [] } outpt[item.category].push(item) }); console.log(outpt) ``` Upvotes: 3 [selected_answer]
2018/03/21
397
1,504
<issue_start>username_0: I am new to programming Python using Pycharm. I would like to access **openpyxl** (which I installed) but get the following error message: ``` Traceback (most recent call last): File "", line 1, in File "D:\PyCharm\PyCharm Community Edition 2017.3.3\helpers\pydev\\_pydev\_bundle\pydev\_import\_hook.py", line 20, in do\_import module = self.\_system\_import(name, \*args, \*\*kwargs) ModuleNotFoundError: No module named 'openpyxl' ``` This is probably a very simple problem but I just don't know how to proceed. Thanks in advance for your help.<issue_comment>username_1: In the `pycharm`, go to `File`->`settings`->`project Interpreter` Then click the right top corner `+` button you will get pop up window to install packages. Then search for `openpyxl` you will get the latest package. Then click `Install package` to install it. Upvotes: 4 <issue_comment>username_2: Exactly how user5777975 explained however on some systems "Project Interpreter" is named "Python Interpreter" and the interface is slightly different. So: In the pycharm, go to File->settings->Python Interpreter Then click the + button ion the top left of the table of installed packages, you will get pop up window to install packages. Then search for openpyxl and you will get the latest package (default option). Then click Install package to install it. You will get notification if successful. Upvotes: 2 <issue_comment>username_3: go to terminal and type "pip install openpyxl" Upvotes: 0
2018/03/21
987
2,709
<issue_start>username_0: How can i parse strings with regex to calculate the total seconds? The strings will be in example: ``` 40s 11m1s 1h47m3s ``` I started with the following regex ``` ((\d+)h)((\d+)m)((\d+)s) ``` But this regex will only match the last example. How can i make the parts optional? Is there a better regex?<issue_comment>username_1: You could use optional non-capture groups, for each (`\dh`, `\dm`, `\ds`): ``` $strs = ['40s', '11m1s', '1h47m3s']; foreach ($strs as $str) { if (preg_match('~(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?~', $str, $matches)) { print_r($matches); } } ``` Outputs: ``` Array ( [0] => 40s [1] => // h [2] => // m [3] => 40 // s ) Array ( [0] => 11m1s [1] => // h [2] => 11 // m [3] => 1 // s ) Array ( [0] => 1h47m3s [1] => 1 // h [2] => 47 // m [3] => 3 // s ) ``` Regex: ``` (?: # non-capture group 1 ( # capture group 1 \d+ # 1 or more number ) # end capture group1 h # letter 'h' ) # end non-capture group 1 ? # optional (?: # non-capture group 2 ( # capture group 2 \d+ # 1 or more number ) # end capture group1 m # letter 'm' ) # end non-capture group 2 ? # optional (?: # non-capture group 3 ( # capture group 3 \d+ # 1 or more number ) # end capture group1 s # letter 's' ) # end non-capture group 3 ? # optional ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: This expression: ``` /(\d*?)s|(\d*?)m(\d*?)s|(\d*?)h(\d*?)m(\d*?)s/gm ``` returns 3 matches, one for each line. Each match is separated into the salient groups of only numbers. The gist is that this will match either any number of digits before an 's' or that plus any number of digits before an 'm' or that plus any number of digits before an 'h'. Upvotes: 0 <issue_comment>username_3: The format that you are using is very similar to the one that is used by java.time.Duration: <https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-> Maybe you can use it instead of writing something custom? Duration uses a format like this: ``` P1H47M3S ``` Maybe you can add the leading "P", and parse it (not sure if you have to uppercase)? The format is called "ISO-8601": <https://en.wikipedia.org/wiki/ISO_8601> For example, ``` $set = array( '40s', '11m1s', '1h47m3s' ); $date = new DateTime(); $date2 = new DateTime(); foreach ($set as $value) { $date2->add(new DateInterval('PT'.strtoupper($value))); } echo $date2->getTimestamp() - $date->getTimestamp(); // 7124 = 1hour 58mins 44secs. ``` Upvotes: 2
2018/03/21
1,171
3,617
<issue_start>username_0: I just used brew to install Python 3 on OS X. The `python3` command now starts the interpreter using brew Python 3.6, but `python` still opens the interpreter with the default system Python 2.7. My understanding was that, by default, brew Python should now override system Python. (I.e., see [Order of /usr/bin and /usr/local/bin and more in $PATH](https://stackoverflow.com/questions/34984870/order-of-usr-bin-and-usr-local-bin-and-more-in-path)). In my PATH, /usr/local/bin comes before /usr/bin, so it shouldn't be a PATH issue. I have tried restarting Terminal, with no effect. Here is my full PATH in case that is relevant. ``` /Users/**/.rvm/gems/ruby-1.9.3-p362/bin:/Users/**/.rvm/gems/ruby-1.9.3-p362@global/bin:/Users/**/.rvm/rubies/ruby-1.9.3-p362/bin:/Users/**/.rvm/bin:/Users/**/.rvm/bin:/Users/**/Python/PmagPy/programs/conversion_scripts2/:/Users/**/Python/PmagPy/programs/conversion_scripts/:/Users/**/Python/PmagPy/programs:/usr/local/heroku/bin:./bin:/usr/local/sbin:/usr/local/bin:/usr/local/share/npm/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/opt/X11/bin ``` Why isn't brew Python taking precedence? And how can I fix (or troubleshoot) this? If I can't find another option, I can create an alias, but I prefer to understand what's happening and get to the root of the problem. Update: I checked out the "possible duplicate" question, but my issue doesn't appear to be a linking problem: ``` ~ brew link --overwrite --dry-run python Warning: Already linked: /usr/local/Cellar/python/3.6.4_4 To relink: brew unlink python && brew link python ~ ```<issue_comment>username_1: I tried a few of the proposed solutions in [How to link home brew python version and set it as default](https://stackoverflow.com/questions/19340871/how-to-link-home-brew-python-version-and-set-it-as-default), but none of them worked. Ultimately I solved this by symlinking python3 --> python: ``` ln -s /usr/local/bin/python3 /usr/local/bin/python ``` Upvotes: -1 <issue_comment>username_2: **TL;DR** Add the following to your `.bash_profile` (or equivalent): `export PATH="/usr/local/opt/python/libexec/bin:$PATH"` **Explanation** It seems python via homebrew is now handled differently (see <https://docs.brew.sh/Homebrew-and-Python>). > > * `python3` points to Homebrew’s Python 3.x (if installed) > * `python2` points to Homebrew’s Python 2.7.x (if installed) > * `python` points to Homebrew’s Python 2.7.x (if installed) otherwise the macOS system Python. Check out `brew info python` if you wish to add > Homebrew’s 3.x python to your PATH. > > > Checking out `brew info python` hints at what you need to do: > > Unversioned symlinks `python`, `python-config`, `pip` etc. pointing to > `python3`, `python3-config`, `pip3` etc., respectively, have been > installed into /usr/local/opt/python/libexec/bin > > > The hint being that you therefore have to add `/usr/local/opt/python/libexec/bin` before `/usr/bin` in your path (not `/usr/local/bin` as stated in some sources e.g. <https://docs.python-guide.org/starting/install3/osx/>) See also <https://github.com/Homebrew/homebrew-core/issues/15746> Upvotes: 6 [selected_answer]<issue_comment>username_3: One-liner to get homebrew python working: zsh ```sh echo -n 'export PATH="/usr/local/opt/python/libexec/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc ``` bash ```sh echo -n 'export PATH="/usr/local/opt/python/libexec/bin:$PATH"' >> ~/.bashrc && source ~/.bashrc ``` Explanation: `>> filename` appends at the end of the file `source filename` reloads the file Upvotes: 3
2018/03/21
3,271
8,418
<issue_start>username_0: I have a problem that is *similar* to [this question](https://stackoverflow.com/questions/39451385/how-to-count-the-number-of-occurrences-in-either-of-two-columns), but just different enough that it can't be solved with the same solution... I've got two dataframes, `df1` and `df2`, like this: ``` import pandas as pd import numpy as np np.random.seed(42) names = ['jack', 'jill', 'jane', 'joe', 'ben', 'beatrice'] df1 = pd.DataFrame({'ID_a':np.random.choice(names, 20), 'ID_b':np.random.choice(names,20)}) df2 = pd.DataFrame({'ID':names}) >>> df1 ID_a ID_b 0 joe ben 1 ben jack 2 jane joe 3 ben jill 4 ben beatrice 5 jill ben 6 jane joe 7 jane jack 8 jane jack 9 ben jane 10 joe jane 11 jane jill 12 beatrice joe 13 ben joe 14 jill beatrice 15 joe beatrice 16 beatrice beatrice 17 beatrice jane 18 jill joe 19 joe joe >>> df2 ID 0 jack 1 jill 2 jane 3 joe 4 ben 5 beatrice ``` What I'd like to do is add in a column to `df2`, with the **count** of rows in `df1` where the given name can be found in **either** column `ID_a` or `ID_b`, resulting in this: ``` >>> df2 ID count 0 jack 3 1 jill 5 2 jane 8 3 joe 9 4 ben 7 5 beatrice 6 ``` This loop gets what I need, but is inefficient for large dataframes, and if someone could suggest an alternative, nicer solution, I'd be very grateful: ``` df2['count'] = 0 for idx,row in df2.iterrows(): df2.loc[idx, 'count'] = len(df1[(df1.ID_a == row.ID) | (df1.ID_b == row.ID)]) ``` Thanks in advance!<issue_comment>username_1: The "either" part complicates things, but should still be doable. --- **Option 1** Since other users decided to turn this into a speed-race, here's mine: ``` from collections import Counter from itertools import chain c = Counter(chain.from_iterable(set(x) for x in df1.values.tolist())) df2['count'] = df2['ID'].map(Counter(c)) df2 ID count 0 jack 3 1 jill 5 2 jane 8 3 joe 9 4 ben 7 5 beatrice 6 ``` ``` 176 µs ± 7.69 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) ``` --- **Option 2** (Original answer) `stack` based ``` c = df1.stack().groupby(level=0).value_counts().count(level=1) ``` Or, ``` c = df1.stack().reset_index(level=0).drop_duplicates()[0].value_counts() ``` Or, ``` v = df1.stack() c = v.groupby([v.index.get_level_values(0), v]).count().count(level=1) # c = v.groupby([v.index.get_level_values(0), v]).nunique().count(level=1) ``` And, ``` df2['count'] = df2.ID.map(c) df2 ID count 0 jack 3 1 jill 5 2 jane 8 3 joe 9 4 ben 7 5 beatrice 6 ``` --- **Option 3** `repeat`-based Reshape and counting ``` v = pd.DataFrame({ 'i' : df1.values.reshape(-1, ), 'j' : df1.index.repeat(2) }) c = v.loc[~v.duplicated(), 'i'].value_counts() df2['count'] = df2.ID.map(c) df2 ID count 0 jack 3 1 jill 5 2 jane 8 3 joe 9 4 ben 7 5 beatrice 6 ``` --- **Option 4** `concat` + `mask` ``` v = pd.concat( [df1.ID_a, df1.ID_b.mask(df1.ID_a == df1.ID_b)], axis=0 ).value_counts() df2['count'] = df2.ID.map(v) df2 ID count 0 jack 3 1 jill 5 2 jane 8 3 joe 9 4 ben 7 5 beatrice 6 ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Below are a couple of ways based on `numpy` arrays. Benchmarking below. **Important**: Take these results with a grain of salt. Remember, performance is dependent on your data, environment and hardware. In your choice, you should also consider readability / adaptability. **Categorical data**: The superb performance with categorical data in `jp2` (i.e. factorising strings to integers via an internal dictionary-like structure) is data-dependent, but if it works it should be applicable across all the below algorithms with good performance *and* memory benefits. ``` import pandas as pd import numpy as np from itertools import chain from collections import Counter # Tested on python 3.6.2 / pandas 0.20.3 / numpy 1.13.1 %timeit original(df1, df2) # 48.4 ms per loop %timeit jp1(df1, df2) # 5.82 ms per loop %timeit jp2(df1, df2) # 2.20 ms per loop %timeit brad(df1, df2) # 7.83 ms per loop %timeit cs1(df1, df2) # 12.5 ms per loop %timeit cs2(df1, df2) # 17.4 ms per loop %timeit cs3(df1, df2) # 15.7 ms per loop %timeit cs4(df1, df2) # 10.7 ms per loop %timeit wen1(df1, df2) # 19.7 ms per loop %timeit wen2(df1, df2) # 32.8 ms per loop def original(df1, df2): for idx,row in df2.iterrows(): df2.loc[idx, 'count'] = len(df1[(df1.ID_a == row.ID) | (df1.ID_b == row.ID)]) return df2 def jp1(df1, df2): for idx, item in enumerate(df2['ID']): df2.iat[idx, 1] = np.sum((df1.ID_a.values == item) | (df1.ID_b.values == item)) return df2 def jp2(df1, df2): df2['ID'] = df2['ID'].astype('category') df1['ID_a'] = df1['ID_a'].astype('category') df1['ID_b'] = df1['ID_b'].astype('category') for idx, item in enumerate(df2['ID']): df2.iat[idx, 1] = np.sum((df1.ID_a.values == item) | (df1.ID_b.values == item)) return df2 def brad(df1, df2): names1, names2 = df1.values.T v2 = df2.ID.values mask1 = v2 == names1[:, None] mask2 = v2 == names2[:, None] df2['count'] = np.logical_or(mask1, mask2).sum(axis=0) return df2 def cs1(df1, df2): c = Counter(chain.from_iterable(set(x) for x in df1.values.tolist())) df2['count'] = df2['ID'].map(Counter(c)) return df2 def cs2(df1, df2): v = df1.stack().groupby(level=0).value_counts().count(level=1) df2['count'] = df2.ID.map(v) return df2 def cs3(df1, df2): v = pd.DataFrame({ 'i' : df1.values.reshape(-1, ), 'j' : df1.index.repeat(2) }) c = v.loc[~v.duplicated(), 'i'].value_counts() df2['count'] = df2.ID.map(c) return df2 def cs4(df1, df2): v = pd.concat( [df1.ID_a, df1.ID_b.mask(df1.ID_a == df1.ID_b)], axis=0 ).value_counts() df2['count'] = df2.ID.map(v) return df2 def wen1(df1, df2): return pd.get_dummies(df1, prefix='', prefix_sep='').sum(level=0,axis=1).gt(0).sum().loc[df2.ID] def wen2(df1, df2): return pd.Series(Counter(list(chain(*list(map(set,df1.values)))))).loc[df2.ID] ``` **Setup** ``` import pandas as pd import numpy as np np.random.seed(42) names = ['jack', 'jill', 'jane', 'joe', 'ben', 'beatrice'] df1 = pd.DataFrame({'ID_a':np.random.choice(names, 10000), 'ID_b':np.random.choice(names, 10000)}) df2 = pd.DataFrame({'ID':names}) df2['count'] = 0 ``` Upvotes: 3 <issue_comment>username_3: By using `get_dummies` ``` pd.get_dummies(df1, prefix='', prefix_sep='').sum(level=0,axis=1).gt(0).sum().loc[df2.ID] Out[614]: jack 3 jill 5 jane 8 joe 9 ben 7 beatrice 6 dtype: int64 ``` I think this should be fast ... ``` from itertools import chain from collections import Counter pd.Series(Counter(list(chain(*list(map(set,df1.values)))))).loc[df2.ID] ``` Upvotes: 2 <issue_comment>username_4: Here's a solution where you effectively do the nested "in" loop by expanding dimensionality of `ID` from `df2` to take advantage of NumPy broadcasting: ``` >>> def count_names(df1, df2): ... names1, names2 = df1.values.T ... v2 = df2.ID.values[:, None] ... mask1 = v2 == names1 ... mask2 = v2 == names2 ... df2['count'] = np.logical_or(mask1, mask2).sum(axis=1) ... return df2 >>> %timeit -r 5 -n 1000 count_names(df1, df2) 144 µs ± 10.4 µs per loop (mean ± std. dev. of 5 runs, 1000 loops each) >>> %timeit -r 5 -n 1000 jp(df1, df2) 224 µs ± 15.5 µs per loop (mean ± std. dev. of 5 runs, 1000 loops each) >>> %timeit -r 5 -n 1000 cs(df1, df2) 238 µs ± 2.37 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) >>> %timeit -r 5 -n 1000 wen(df1, df2) 921 µs ± 15.3 µs per loop (mean ± std. dev. of 5 runs, 1000 loops each) ``` The shape of the masks will be `(len(df1), len(df2))`. Upvotes: 2
2018/03/21
652
2,413
<issue_start>username_0: I'm pretty new to WPF and I'm trying to make a database system. What I currently have is a `Login` Window. When you enter the user and password you are supposed to go to another window `StudentInfoSystem` . The code I used is pretty basic and common. ``` var info = new StudentInfoSystem.MainWindow(); info.Show(); this.Close(); ``` So, what this would do, is after you press the login button, you get transferred to `StudentInfoSystem` and the login window closes. The problem I have with `Show()` is that it opens a window and immediately returns, right? It doesn't wait for the new window to close. So, my question is how can I open a new window and WORK with it? When I say work, I meant to show out information in my textboxes (In the NEWLY opened window) depending on the role the user has, etc...<issue_comment>username_1: Try `window.Activate()` to focus the new window and/or `[any element].Focus()` to focus any element within window. Upvotes: 3 [selected_answer]<issue_comment>username_2: I'm guessing the above code is in the button click handler for the Login Window, which would make the Login Window the parent of the StudentInfoSystem window. Since WPF will close the parent and any child(ren) window(s) when closing the parent window, your StudentInfo window will also close when calling ``` this.Close(); ``` One option might be to instead call ``` this.Hide(); ``` but without seeing how the rest of your app is set up, not 100% sure this is the best approach. Perhaps see these SO questions: 1. [wpf-create-sibling-window-and-close-current-one](https://stackoverflow.com/questions/6672187/wpf-create-sibling-window-and-close-current-one) 2. [how-to-close-current-window-in-code-when-launching-new-window](https://stackoverflow.com/questions/19248822/how-to-close-current-window-in-code-when-launching-new-window) Upvotes: 2 <issue_comment>username_3: As I understand, this should do what you want: ``` info.ShowDialog(); ``` You could also check `ShutdownMode` property. I would rather say, login window is sth you want to close after login, but do what you want :). Usage of `ShutdownMode` property: ``` public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); this.ShutdownMode = System.Windows.ShutdownMode.OnLastWindowClose; } } ``` Upvotes: 1
2018/03/21
1,220
3,904
<issue_start>username_0: In es6, how can i simplify the following lines using destructuring?: ``` const array0 = someArray[0].data; const array1 = someArray[1].data; const array2 = someArray[2].data; ```<issue_comment>username_1: Whether using destructuring would actually be a simplification is debatable but this is how it can be done: ``` const [ { data: array0 }, { data: array1 }, { data: array2 } ] = someArray ``` Live Example: ```js const someArray = [ { data: 1 }, { data: 2 }, { data: 3 } ]; const [ { data: array0 }, { data: array1 }, { data: array2 } ] = someArray console.log(array0, array1, array2); ``` What is happening is that you're first extracting each object from `someArray` then destructuring each object by extracting the `data` property and renaming it: ``` // these 2 destructuring steps const [ obj1, obj2, obj3 ] = someArray // step 1 const { data: array0 } = obj1 // step 2 const { data: array1 } = obj2 // step 2 const { data: array2 } = obj3 // step 2 // written together give const [ { data: array0 }, { data: array1 }, { data: array2 } ] = someArray ``` Maybe combine destructuring with mapping for (potentially) more readable code: ``` const [array0, array1, array2] = someArray.map(item => item.data) ``` Live Example: ```js const someArray = [ { data: 1 }, { data: 2 }, { data: 3 } ]; const [array0, array1, array2] = someArray.map(item => item.data) console.log(array0, array1, array2); ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: I believe what you actually want is ``` const array = someArray.map(x => x.data) ``` If you really want three variables (*Hint: you shouldn't*), you can combine that `map`ping with destructuring: ``` const [array0, array1, array2] = someArray.map(x => x.data) ``` Upvotes: 4 <issue_comment>username_3: If you want to do with this pure JS then follow this code snippet. It will help you. ```js let myArray = [ { "_id": "1", "subdata": [ { "subid": "11", "name": "A" }, { "subid": "12", "name": "B" } ] }, { "_id": "2", "subdata": [ { "subid": "12", "name": "B" }, { "subid": "33", "name": "E" } ] } ] const array = myArray.map(x => x.subdata).flat(1) const isExist = (key,value, a) => { return a.find(item => item[key] == value) } let a = array.reduce((acc, curr) => { if(!isExist('subid', curr.subid, acc)) { acc.push(curr) } return acc }, []) console.log(a) ``` Upvotes: 1 <issue_comment>username_4: ``` const myInfo = someArray.map((item) => { const {itemval1, itemval2} = item; return( //return data how you want it eg: {itemval1} {itemval2} ) }) ``` This is how I did it in react, correct me if m wrong, I'm still new to this world Upvotes: 0 <issue_comment>username_5: @Daniel, I presume you were looking to destructure a nested Object in an array of Objects. Following @username_1 was able to extract the nested Object's property using his pattern. What is happening is that you're first extracting each object from addresses array then destructuring each object by extracting its properties and renaming it including the nested Object: ```js addresses = [ { locality:"Sarjapura, Bangalore", coordinates:{latitude:"12.901160", longitude:"77.711680"} }, { locality:"Vadakara, Kozhikode", coordinates:{latitude:"11.588980", longitude:"75.596450"} } ] const [ {locality:loc1, coordinates:{latitude:lat1, longitude:ltd1}}, {locality:loc2, coordinates:{latitude:lat2, longitude:ltd2}} ] = addresses console.log(`Latitude of Vadakara :: ${lat2}`) ``` Upvotes: 0
2018/03/21
512
1,521
<issue_start>username_0: I need a regular expression for a string with has at least 8 symbols and only one uppercase character. Java For example, it should match: * Asddffgf * asdAsadasd * asdasdaA But not: * adadAasdasAsad * AsdaAadssadad * asdasdAsadasdA I tried this: `^[a-z]*[A-Z][a-z]*$` This works good, but I need at least 8 symbols. Then I tried this: `(^[a-z]*[A-Z][a-z]*$){8,}` But it doesn't work<issue_comment>username_1: `^(?=[^A-Z]*[A-Z][^A-Z]*$).{8,}$` <https://regex101.com/r/zTrbyX/6> Explanation: `^` - Anchor to the beginning of the string, so that the following lookahead restriction doesn't skip anything. `(?= )` - Positive lookahead; assert that the beginning of the string is followed by the contained pattern. `[^A-Z]*[A-Z][^A-Z]*$` - A sequence of any number of characters that are not capital letters, then a single capital letter, then more non capital letters until the end of the string. This insures that there will be one and only one capital letter throughout the string. `.{8,}` - Any non-newline character eight or more times. `$` - Anchor at the end of the string (possibly unnecessary depending on your requirements). Upvotes: 3 [selected_answer]<issue_comment>username_2: In your first regex `^[a-z]*[A-Z][a-z]*$` you could append a positive lookahead `(?=[a-zA-Z]{8,})` right after the `^`. That will assert that what follows matches at least 8 times a lower or uppercase character. [`^(?=[a-zA-Z]{8,})[a-z]*[A-Z][a-z]*$`](https://regex101.com/r/DPrs4A/1) Upvotes: 0
2018/03/21
473
1,505
<issue_start>username_0: Often look at other applications that can make the color different but close to the color. It's like the two colors of the appendix. How can UIColor be achieved? [![enter image description here](https://i.stack.imgur.com/eIVPb.png)](https://i.stack.imgur.com/eIVPb.png) [![enter image description here](https://i.stack.imgur.com/q8xW0.png)](https://i.stack.imgur.com/q8xW0.png)<issue_comment>username_1: ``` let color = UIColor.red //Your uicolor let softColor = color.withAlphaComponent(0.5) //0<->1.0 ``` Upvotes: 1 <issue_comment>username_2: A better solution than lowering the alpha (which may cause other things behind it to appear) is to lower the color's saturation. Here's a `UIColor` extension that gets the HSB of a color, lowers the saturation, and returns the new color with the same alpha: ``` extension UIColor { func softer() -> UIColor { var h: CGFloat = 0 var s: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 if self.getHue(&h, saturation: &s, brightness: &b, alpha: &a) { // Change the 0.5 to suit your needs return UIColor(hue: h, saturation: s * 0.5, brightness: b, alpha: a) } else { return self } } } // Examples: let orange = UIColor.orange let softOrange = orange.softer() let brown = UIColor(red: 0.4392, green: 0.2510, blue: 0.1882, alpha: 1.0) let softBrown = brown.softer() ``` Upvotes: 3 [selected_answer]
2018/03/21
2,199
8,691
<issue_start>username_0: I' struggling with some basic UIStackView distribution and alignment stuff. I have an UICollectionViewCell which has a horizontal UIStackView at the contentView subview. This UIStackView has a vertical UIStackView for the three labels itself, and of course the UIImageView. This is the code snippet for the screenshot below: ``` func createSubViews() { // contains the UIStackview with the 3 labels and the UIImageView containerStackView = UIStackView() containerStackView.axis = .horizontal containerStackView.distribution = .fill containerStackView.alignment = .top contentView.addSubview(containerStackView) // the UIStackView for the labels verticalStackView = UIStackView() verticalStackView.axis = .vertical verticalStackView.distribution = .fill verticalStackView.spacing = 10.0 containerStackView.addArrangedSubview(verticalStackView) categoryLabel = UILabel() categoryLabel.font = UIFont.preferredFont(forTextStyle: .caption1) categoryLabel.textColor = UIColor.lightGray verticalStackView.addArrangedSubview(categoryLabel) titleLabel = UILabel() titleLabel.numberOfLines = 3 titleLabel.lineBreakMode = .byWordWrapping verticalStackView.addArrangedSubview(titleLabel) timeLabel = UILabel() timeLabel.font = UIFont.preferredFont(forTextStyle: .caption1) timeLabel.textColor = UIColor.lightGray verticalStackView.addArrangedSubview(timeLabel) // UIImageView imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.layer.cornerRadius = 5 layer.masksToBounds = true containerStackView.addArrangedSubview(imageView) } ``` [![enter image description here](https://i.stack.imgur.com/y8tfL.png)](https://i.stack.imgur.com/y8tfL.png) What I want to achive is, that the "time label" ("3 days ago") is always placed at the bottom of each UICollectionViewCell (aligned with the bottom of the UIImageView), regardless of the different title label lines. I've played with various UIStackView distributions, constraining the "time label" and with the hugging priority of the "title label". But anyhow I can't get it right. Any hints?<issue_comment>username_1: The problem is the vertical stack view. You apparently want to say: the middle label's top should hug the MyCustomLabel bottom, but the 3 Days Ago bottom should hug the overall bottom. That is not something you can say to a stack view. And even if that is not what you want to say, you would still need to make the vertical stack view take on the full height of the cell, and how are you going to do that? In the code you showed, you don't do that at all; in fact, your stack view has *zero size* based on that code, which will lead to all sorts of issues. I would suggest, therefore, that you just get rid of all the stack views and just configure the layout directly. Your layout is an easy one to configure using autolayout constraints. Upvotes: 0 <issue_comment>username_2: ### UPDATE Since you're setting `titleLabel.numberOfLines = 3`, one way to do this is simply to append three newlines to the title text. That will force `titleLabel` to always consume its full height of three lines, forcing `timeLabel` to the bottom. That is, when you set `titleLabel.text`, do it like this: ``` titleLabel.text = theTitle + "\n\n\n" ``` ### ORIGINAL If you let one of the labels stretch vertically, the stretched label's text will be centered vertically within the stretched label's bounds, which is not what you want. So we can't let the labels stretch vertically. Therefore we need to introduce a padding view that can stretch but is otherwise invisible. If the padding view gets squeezed down to zero height, the stack view will still put spacing before and after it, leading to double-spacing between `titleLabel` and `timeLabel`, which you also don't want. So we'll need to implement all the spacing using padding views. Change `verticalStackView.spacing` to 0. Add a generic `UIView` named `padding1` to `verticalStackView` after `categoryLabel`, before `titleLabel`. Constrain its height to equal 10. Add a generic `UIView` named `padding2` to `verticalStackView` after `titleLabel`, before `timeLabel`. Constrain its height to greater than or equal to 10 so that it can stretch. Set the vertical hugging priorities of `categoryLabel`, `titleLabel`, and `timeLabel` to required, so that they will not stretch vertically. Constrain the height of `verticalStackView` to the height of `containerStackView` so that it will stretch one or more of its arranged subviews if needed to fill the vertical space available. The only arranged subview that can stretch is `padding2`, so it will stretch, keeping the title text near the top and the time text at the bottom. Also, constrain your `containerStackView` to the bounds of `contentView` and set `containerStackView.translatesAutoresizingMaskIntoConstraints = false`. Result: [![short title](https://i.stack.imgur.com/YJMXm.png)](https://i.stack.imgur.com/YJMXm.png) [![long title](https://i.stack.imgur.com/MqeaS.png)](https://i.stack.imgur.com/MqeaS.png) Here's my playground: ``` import UIKit import PlaygroundSupport class MyCell: UICollectionViewCell { var containerStackView: UIStackView! var verticalStackView: UIStackView! var categoryLabel: UILabel! var titleLabel: UILabel! var timeLabel: UILabel! var imageView: UIImageView! func createSubViews() { // contains the UIStackview with the 3 labels and the UIImageView containerStackView = UIStackView() containerStackView.axis = .horizontal containerStackView.distribution = .fill containerStackView.alignment = .top contentView.addSubview(containerStackView) // the UIStackView for the labels verticalStackView = UIStackView() verticalStackView.axis = .vertical verticalStackView.distribution = .fill verticalStackView.spacing = 0 containerStackView.addArrangedSubview(verticalStackView) categoryLabel = UILabel() categoryLabel.font = UIFont.preferredFont(forTextStyle: .caption1) categoryLabel.textColor = UIColor.lightGray verticalStackView.addArrangedSubview(categoryLabel) let padding1 = UIView() verticalStackView.addArrangedSubview(padding1) titleLabel = UILabel() titleLabel.numberOfLines = 3 titleLabel.lineBreakMode = .byWordWrapping verticalStackView.addArrangedSubview(titleLabel) let padding2 = UIView() verticalStackView.addArrangedSubview(padding2) timeLabel = UILabel() timeLabel.font = UIFont.preferredFont(forTextStyle: .caption1) timeLabel.textColor = UIColor.lightGray verticalStackView.addArrangedSubview(timeLabel) // UIImageView imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.layer.cornerRadius = 5 layer.masksToBounds = true containerStackView.addArrangedSubview(imageView) categoryLabel.setContentHuggingPriority(.required, for: .vertical) titleLabel.setContentHuggingPriority(.required, for: .vertical) timeLabel.setContentHuggingPriority(.required, for: .vertical) imageView.setContentHuggingPriority(.defaultHigh, for: .horizontal) containerStackView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ contentView.leadingAnchor.constraint(equalTo: containerStackView.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: containerStackView.trailingAnchor), contentView.topAnchor.constraint(equalTo: containerStackView.topAnchor), contentView.bottomAnchor.constraint(equalTo: containerStackView.bottomAnchor), verticalStackView.heightAnchor.constraint(equalTo: containerStackView.heightAnchor), padding1.heightAnchor.constraint(equalToConstant: 10), padding2.heightAnchor.constraint(greaterThanOrEqualToConstant: 10), ]) } } let cell = MyCell(frame: CGRect(x: 0, y: 0, width: 320, height: 110)) cell.backgroundColor = .white cell.createSubViews() cell.categoryLabel.text = "MY CUSTOM LABEL" cell.titleLabel.text = "This is my title" cell.timeLabel.text = "3 days ago" cell.imageView.image = UIGraphicsImageRenderer(size: CGSize(width: 110, height:110)).image { (context) in UIColor.blue.set() UIRectFill(.infinite) } PlaygroundPage.current.liveView = cell ``` Upvotes: 2 [selected_answer]
2018/03/21
1,071
3,785
<issue_start>username_0: (alternative description could be 'how to rename a sphinx-autodoc package name?') using sphinx version 1.7 on Python 2.7.13 --- I would like to automatically create documentation using docstrings and `sphinx-apidoc`. My project structure is as follows: ``` myPythonProject <- my Python package name and git repository. |-- docs | |-- _build | | |-- html <- where final HTML doc is created. | | | |-- apidocs <- contains the autodoc created '.rst' files. | |-- _static | |-- _templates | | | | conf.py <- 4 Sphinx doc files, auto generated with sphinx-quickstart. | | index.rst <- | | make.rst <- | | Makefile <- | | |-- src | | __init__.py <- important for 'setup.py'. | | myModule1.py | | myModule2.py | | myModule3.py | | setup.py ``` The `myModule` files contain docstrings. After performing the `sphinx-quickstart` with quite standard options *(extensions autodoc and intersphinx. No separated source and build directories. Adding `make.bat` and `Makefile` files.)* And some minor change to the `conf.py` where I uncommented and changed: ``` # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. import os import sys sys.path.insert(0, os.path.abspath('../')) ``` When running: `sphinx-apidoc -f -o docs/apidocs src` The docstrings are found but it is convinced **src** is my package name. It clearly does not observe my `setup.py` file or something. It does look at **\_\_init\_\_.py** though, if I remove it I can create docs with only modules, no package at all. But also this is not desired, but closer at least. The content of **src** is installed as 'MyPythonProject'. Therefore `Setup.py` is configured as follows to install this package and leaving out the 'src' reference when importing: ``` from setuptools import setup setup( name='MyPythonProject', packages={'MyPythonProject': 'src'}, package_dir={'MyPythonProject': 'src'}, ``` (Is this an unorthodox structure? Otherwise I would also be interested in a more common layout which autodoc does support.) --- Currently ``` sphinx-apidoc -f -o docs/apidocs src sphinx-build -a -b html docs/ docs/_build/html ``` returns the following document: [you can ignore the red.](https://i.stack.imgur.com/4yD6I.png) Question -------- How can I create documentation showing `myPythonProject.myModule1.def1()` it's docstring, and not `src.myModule1.def1()`?<issue_comment>username_1: Rename `src` to `myPythonProject`. [Pyramid](https://github.com/pylons/pyramid) is one example that follows this convention. Another example is explained in this [issue for Pyramid](https://github.com/Pylons/pyramid/issues/3022) and examples in [hupper](https://github.com/Pylons/hupper) and [pyramid\_retry](https://github.com/Pylons/pyramid_retry). However, you'll still have `MyPythonProject/src/MyPythonProject`, which although more unwieldly might not be as unsightly. Ultimately whatever you name the directory that is the immediate parent that contains your package shall become the first part of the method's Python dotted name. Upvotes: 0 <issue_comment>username_2: Another alternative would be to include src in your path and specify the module without the src prefix. So change your path setup to the src folder by replacing your line above with this in docs/conf.py: ``` sys.path.insert(0, os.path.abspath('../src')) ``` and in your sphinx index.rst change the automodule:: accordingly. That way, you won't have that src. prefix to your class names. Worked for me, anyway :-) Upvotes: 2 [selected_answer]
2018/03/21
764
2,126
<issue_start>username_0: I am looking for a nicer way to clean up this clunky nest for-loop that I have. ``` names = ['name1', 'name2', 'name3', ...] values = [[1, 2, 3, ...], [10, 20, 30, ...], [100, 200, 300, ...]] for i in range(len(values[0])): for name, value in zip(names, values): print(name, value[i]) ``` Output: ``` name1 1 name2 10 name3 100 name1 2 name2 20 name3 200 name1 3 name2 30 name3 300 ... ``` The above snippet gives the desired output but is certainly not very pythonic.<issue_comment>username_1: While you *could* do this: ``` # assuming your "values" list can be generated dynamically def values(how_many): for i in range(1, how_many + 1): yield [i * 10 ** pow for pow in range(0, how_many)] names = ['name1', 'name2', 'name3'] [name + ' ' + str(val) for vals in values(len(names)) for name, val in zip(names, vals)] ``` which generates this list of values: ``` ['name1 1', 'name2 10', 'name3 100', 'name1 2', 'name2 20', 'name3 200', 'name1 3', 'name2 30', 'name3 300'] ``` I don't think that pressing it all into a single list comprehension is inherently more pythonic. It's a neat little trick, but it's not an improvement. Keep your nested loops, they are straight-forward, readable and won't cause your future self a headache. --- Assuming your values list is static, like your sample shows, I don't think this is much of an improvement either. ``` names = ['name1', 'name2', 'name3'] values = [[1, 2, 3], [10, 20, 30], [100, 200, 300]] [name + ' ' + str(value[i]) for i in range(len(values[0])) for name, value in zip(names, values)] ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: This function might be helpful in general: ``` def nested_indices(lol, indices_so_far=None): indices_so_far = indices_so_far or [] if not isinstance(lol, list): yield indices_so_far return for i in range(len(lol)): for ni in nested_indices(lol[i], indices_so_far + [i]): yield ni ``` Now you can do this sort of thing: ``` for i,j in nested_indices(values): print(names[i], values[i][j]) ``` Upvotes: 0
2018/03/21
513
1,511
<issue_start>username_0: I have a working chunk of regex, but I cannot get it to work in R. (Using <https://regex101.com/> to verify the regex works.) I have this string: ``` pbb-nae-49/N2-A.N49AV048.SUP-DAMP ``` I need everything after the last period, which can be basically any characters (but I don't think spaces will ever exist after the last period). I have this which works in getting the string as a group: ``` \.([-0-9a-zA-Z\s]+\z) ``` And I also have this, which works a little differently (I am unsure which one will provide me better results with real data after testing): ``` [\w\d\/\.-]+\.([\w-]+) ``` Neither of these lines work to extract the strings in R: ``` tester = "pbb-nae-49/N2-A.N49AV048.SUP-DAMP" gsub("[\\w\\d\\/\\.-]+\\.([\\w-]+)","POOP",tester) #returns original string gsub("\\.([-0-9a-zA-Z\\s]+\\z)","POOP",tester) #returns original string ``` Any ideas how to fix this? Or what I am missing?<issue_comment>username_1: You can get this with ``` sub(".*\\.(.*)", "\\1", S) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Or another option is `str_match` ``` library(stringr) str_match(tester, ".*\\.([^.]+$)")[,2] #[1] "SUP-DAMP" ``` --- Or using the `base R` `sub` where we match the characters (`.*`) followed by a dot (`\\.`) and capture one or more characters that are not a dot (`[^.]+`) until the end (`$`) of the string and replace it with the backreference of that capture group (`\\1`) ``` sub(".*\\.([^.]+)", "\\1", tester) ``` Upvotes: 1
2018/03/21
1,532
5,466
<issue_start>username_0: How do I mock the timeout call, here? ``` $scope.submitRequest = function () { var formData = getData(); $scope.form = JSON.parse(formData); $timeout(function () { $('#submitForm').click(); }, 2000); }; ``` I want to see timeout has been called with the correct function. I would like an example of the spyon function mocking $timeout. ``` spyOn(someObject,'$timeout') ```<issue_comment>username_1: First of all, DOM manipulation should only be performed in directives. Also, it's better to use angular.element(...), than $(...). Finally, to do this, you can expose your element's click handler to the scope, spy on it, and check if that handler has been called: ``` $timeout.flush(2000); $timeout.verifyNoPendingTasks(); expect(scope.myClickHandler).toHaveBeenCalled(); ``` EDIT: since that's a form and there is no ng-click handler, you can use ng-submit handler, or add a name to your form and do: ``` $timeout.flush(2000); $timeout.verifyNoPendingTasks(); expect(scope.formName.$submitted).toBeTruthy(); ``` Upvotes: 3 <issue_comment>username_2: Create mock for $timeout provider: ``` var f = () => {} var myTimeoutProviderMock = () => f; ``` Use it: ``` beforeEach(angular.mock.module('myModule', ($provide) => { $provide.factory('$timeout', myTimeoutProviderMock); })) ``` Now you can test: ``` spyOn(f); expect(f).toHaveBeenCalled(); ``` P.S. you'd better test result of function in timeout. Upvotes: 1 <issue_comment>username_3: Assuming that piece of code is within the controller or being created in the test by $controller, then $timeout can be passed in the construction parameter. So you could just do something like: ``` var timeoutStub = sinon.stub(); var myController = $controller('controllerName', timeoutStub); $scope.submitRequest(); expect(timeoutStub).to.have.been.called; ``` Upvotes: 1 <issue_comment>username_4: Unit Tesitng $timeout with flush delay You have to flush the queue of the $timeout service by calling $timeout.flush() ``` describe('controller: myController', function(){ describe('showAlert', function(){ beforeEach(function(){ // Arrange vm.alertVisible = false; // Act vm.showAlert('test alert message'); }); it('should show the alert', function(){ // Assert assert.isTrue(vm.alertVisible); }); it('should hide the alert after 5 seconds', function(){ // Act - flush $timeout queue to fire off deferred function $timeout.flush(); // Assert assert.isFalse(vm.alertVisible); }); }) }); ``` Please checkout this link <http://jasonwatmore.com/post/2015/03/06/angularjs-unit-testing-code-that-uses-timeout> Upvotes: 1 <issue_comment>username_5: I totally agree with [username_1](https://stackoverflow.com/users/1630623/frane-poljak)'s [answer](https://stackoverflow.com/a/49500845/2314242). You should surely follow his way. Second way to do it is by mocking $timeout service like below: ``` describe('MainController', function() { var $scope, $timeout; beforeEach(module('app')); beforeEach(inject(function($rootScope, $controller, $injector) { $scope = $rootScope.$new(); $timeout = jasmine.createSpy('$timeout'); $controller('MainController', { $scope: $scope, $timeout: $timeout }); })); it('should submit request', function() { $scope.submitRequest(); expect($timeout).toHaveBeenCalled(); }); ``` Here is the plunker having both approaches: <http://plnkr.co/edit/s5ls11> Upvotes: 1 <issue_comment>username_6: `$timeout` can be spied or mocked as shown in [this answer](https://stackoverflow.com/a/37220166/3731501): ``` beforeEach(module('app', ($provide) => { $provide.decorator('$timeout', ($delegate) => { var timeoutSpy = jasmine.createSpy().and.returnValue($delegate); // methods aren't copied automatically to spy return angular.extend(timeoutSpy, $delegate); }); })); ``` There's not much to test here, since `$timeout` is called with anonymous function. For testability reasons it makes sense to expose it as scope/controller method: ``` $scope.submitFormHandler = function () { $('#submitForm').click(); }; ... $timeout($scope.submitFormHandler, 2000); ``` Then spied `$timeout` can be tested: ``` $timeout.and.stub(); // in case we want to test submitFormHandler separately scope.submitRequest(); expect($timeout).toHaveBeenCalledWith(scope.submitFormHandler, 2000); ``` And the logic inside `$scope.submitFormHandler` can be tested in different test. Another problem here is that jQuery doesn't work well with unit tests and requires to be tested against real DOM (this is one of many reasons why jQuery should be avoided in AngularJS applications when possible). It's possible to spy/mock jQuery API like shown in [this answer](https://stackoverflow.com/a/36356692/3731501). `$(...)` call can be spied with: ``` var init = jQuery.prototype.init.bind(jQuery.prototype); spyOn(jQuery.prototype, 'init').and.callFake(init); ``` And can be mocked with: ``` var clickSpy = jasmine.createSpy('click'); spyOn(jQuery.prototype, 'init').and.returnValue({ click: clickSpy }); ``` Notice that it's expected that mocked function will return jQuery object for chaining with `click` method. When `$(...)` is mocked, the test doesn't require `#submitForm` fixture to be created in DOM, this is the preferred way for isolated unit test. Upvotes: 2
2018/03/21
1,640
3,639
<issue_start>username_0: I create all three-element permutations without mirroring, using `itertools.product()`: ``` import itertools list_1 = [list(i) for i in itertools.product(tuple(range(4)), repeat=3) if tuple(reversed(i)) >= tuple(i)] ``` Output: ``` [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 1, 3], [0, 2, 0], [0, 2, 1], [0, 2, 2], [0, 2, 3], [0, 3, 0], [0, 3, 1], [0, 3, 2], [0, 3, 3], [1, 0, 1], [1, 0, 2], [1, 0, 3], [1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, 3, 1], [1, 3, 2], [1, 3, 3], [2, 0, 2], [2, 0, 3], [2, 1, 2], [2, 1, 3], [2, 2, 2], [2, 2, 3], [2, 3, 2], [2, 3, 3], [3, 0, 3], [3, 1, 3], [3, 2, 3], [3, 3, 3]] ``` How do I delete these sublisters from the list `list_1`, which have the same number of corresponding values and then leave only one of them? For example, in sublists `[1,1,2], [1,2,1]` the number of given values is the same in all, that is, in each sub-list there are two `1` and one `2`, that's why I consider the sublisters to be the same and that's why I want to leave only the first one, namely `[1,1,2]`. How can this be done? I was thinking about counting the number of corresponding values in each sub-list and creating a list with the occurring feature regarding the amount of given values, and then checking each element from the list list\_1 in the loop or the element with the given feature has not occurred before. But it seems to me to be very complicated.<issue_comment>username_1: Rather than using `product` from the `itertools` module, use [combinations\_with\_replacement](https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement). That does what you want in one line without any massaging afterward: ``` list1 = [list(i) for i in combinations_with_replacement(range(4),3)] ``` The result of `print(list1)` after that is ``` [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 1, 1], [0, 1, 2], [0, 1, 3], [0, 2, 2], [0, 2, 3], [0, 3, 3], [1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 2, 3], [1, 3, 3], [2, 2, 2], [2, 2, 3], [2, 3, 3], [3, 3, 3]] ``` Note that your conversion of the `range` object to a tuple is not necessary. Upvotes: 4 [selected_answer]<issue_comment>username_2: You can sort each sublist and then extract unique sublists out as follows. ``` list_2 = map(sorted, list_1) list_u = [] [list_u.append(x) for x in list_2 if x not in list_u] ``` Output: ``` list_u = [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 1, 1], [0, 1, 2], [0, 1, 3], [0, 2, 2], [0, 2, 3], [0, 3, 3], [1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 2, 3], [1, 3, 3], [2, 2, 2], [2, 2, 3], [2, 3, 3], [3, 3, 3]] ``` Now, there are more efficient options than sorting each sublist, but I will leave that upto you. Upvotes: 1 <issue_comment>username_3: This might do the trick: ``` import itertools def uniqifyList(list): indexToReturn = [] sortedUniqueItems = [] for idx, value in enumerate(list): # check if exists in unique_list or not value.sort() if value not in sortedUniqueItems: sortedUniqueItems.append(value) indexToReturn.append(idx) return [list[i] for i in indexToReturn] list1 = [list(i) for i in itertools.product(tuple(range(4)), repeat=3) if tuple(reversed(i)) >= tuple(i)] print(list1) list2 = uniqifyList(list1) print(list2) ``` Which outputs: ``` [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 1, 1], [0, 1, 2], [0, 1, 3], [0, 2, 2], [0, 2, 3], [0, 3, 3], [1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 2, 3], [1, 3, 3], [2, 2, 2], [2, 2, 3], [2, 3, 3], [3, 3, 3]] ``` Upvotes: 1
2018/03/21
605
1,770
<issue_start>username_0: I want to rename some lines in my `PitchAccent` column in my data frame `total` with the following command: ``` total$PitchAccent <- sub("!H*","H*", total$PitchAccent) ``` So that `!H*` now become `H*`. However, when I check for the number of `H*` afterward, it stays the same as before and `!H*`occurrences seem to be gone. Moreover, now when I do: ``` summary(total$PitchAccent) ``` It doesn't show me: ``` > summary(total$PitchAccent) !H* !H*L *? ..H ..L H% H* H*? H*L H*L? HH*L L% L* 262 2125 0 25 633 0 2056 0 6122 0 6 0 460 L*? L*H L*H? L*HL no !H*L? LH*L L !H H! .L L*!H L*HL? 0 7818 0 53 69569 0 2 1 0 0 1 1 0 ``` ,but instead just: ``` > summary(total$PitchAccent) Length Class Mode 89134 character character ```<issue_comment>username_1: The reason the summary changed is because sub() coerces the input to character. So total$PitchAccent is no longer a factor with different levels, but character. So summary doesn't provide any useful information. Coerce it back to factor with `total$PitchAccent = as.factor(total$PitchAccent)` Upvotes: 2 <issue_comment>username_2: Specifically change the level of the factor from !H\* to H\* ``` total$PitchAccent <- factor(total$PitchAccent) levels(total$PitchAccent)[ levels(total$PitchAccent) == "!H*" ] <- "H*" ``` Then, if you want it back to character format, cast it as follows. ``` total$PitchAccent <- as.character(total$PitchAccent) ``` With `gsub` or `sub`, you can do this ``` gsub("!H*", "H*", total$PitchAccent, fixed = TRUE ) sub("!H*", "H*", total$PitchAccent, fixed = TRUE ) ``` Upvotes: 2 [selected_answer]
2018/03/21
534
1,772
<issue_start>username_0: I have 2 tables: * user * message (which has both *id\_user* AND *id\_user\_from*) I need a list of basic information about the users, and 3 special columns: * COUNT of messages received by the user * COUNT of messages sent by the user * SUM of all the views (both sent and received) of the user's messages This is my current query: ``` SELECT SUM(case when message.id_user = user.id_user THEN 1 ELSE 0 END) AS q_received, SUM(case when message.id_user_from = user.id_user THEN 1 ELSE 0 END) AS q_sent, SUM(message.views) AS views, user.id_user AS id_user, user.name AS name, user.lastname AS lastname, user.date_login AS date_login FROM user LEFT JOIN message ON message.id_user = user.id_user ORDER BY user.date_login DESC ``` The sums are all wrong. Here's the sqlfiddle with all the necessary tables and some records as example: <http://sqlfiddle.com/#!9/4fd838/2> Thanks!<issue_comment>username_1: The reason the summary changed is because sub() coerces the input to character. So total$PitchAccent is no longer a factor with different levels, but character. So summary doesn't provide any useful information. Coerce it back to factor with `total$PitchAccent = as.factor(total$PitchAccent)` Upvotes: 2 <issue_comment>username_2: Specifically change the level of the factor from !H\* to H\* ``` total$PitchAccent <- factor(total$PitchAccent) levels(total$PitchAccent)[ levels(total$PitchAccent) == "!H*" ] <- "H*" ``` Then, if you want it back to character format, cast it as follows. ``` total$PitchAccent <- as.character(total$PitchAccent) ``` With `gsub` or `sub`, you can do this ``` gsub("!H*", "H*", total$PitchAccent, fixed = TRUE ) sub("!H*", "H*", total$PitchAccent, fixed = TRUE ) ``` Upvotes: 2 [selected_answer]
2018/03/21
318
1,110
<issue_start>username_0: In Android Studio I would like to have a Edittext that uses the format `00:00` and where you don't have to type the `:` in `00:00` . Is there a way this can be done in the layout or should this be done programmaticly? Thanks!<issue_comment>username_1: The reason the summary changed is because sub() coerces the input to character. So total$PitchAccent is no longer a factor with different levels, but character. So summary doesn't provide any useful information. Coerce it back to factor with `total$PitchAccent = as.factor(total$PitchAccent)` Upvotes: 2 <issue_comment>username_2: Specifically change the level of the factor from !H\* to H\* ``` total$PitchAccent <- factor(total$PitchAccent) levels(total$PitchAccent)[ levels(total$PitchAccent) == "!H*" ] <- "H*" ``` Then, if you want it back to character format, cast it as follows. ``` total$PitchAccent <- as.character(total$PitchAccent) ``` With `gsub` or `sub`, you can do this ``` gsub("!H*", "H*", total$PitchAccent, fixed = TRUE ) sub("!H*", "H*", total$PitchAccent, fixed = TRUE ) ``` Upvotes: 2 [selected_answer]
2018/03/21
449
1,653
<issue_start>username_0: i'm using jquery change function but when i change input value i got an empty string !! this is my code any help plz : ```js class SearchForm extends React.Component{ constructor(props) { super(props); this.state = {input_term_value: "",spaces_list: ""}; } componentDidMount() { var space_change_value = ""; $("input.sp-autocomplete-spaces").change(function() { space_change_value = $(this).val(); }); this.setState({spaces_list: space_change_value}); } updateInputValue(evt){ this.setState({input_term_value: evt.target.value}); } componentDidUpdate (prevProps, prevState) { this.sendGetRequest(); } sendGetRequest(){ var _this = this; this.serverRequest = axios ```<issue_comment>username_1: The reason the summary changed is because sub() coerces the input to character. So total$PitchAccent is no longer a factor with different levels, but character. So summary doesn't provide any useful information. Coerce it back to factor with `total$PitchAccent = as.factor(total$PitchAccent)` Upvotes: 2 <issue_comment>username_2: Specifically change the level of the factor from !H\* to H\* ``` total$PitchAccent <- factor(total$PitchAccent) levels(total$PitchAccent)[ levels(total$PitchAccent) == "!H*" ] <- "H*" ``` Then, if you want it back to character format, cast it as follows. ``` total$PitchAccent <- as.character(total$PitchAccent) ``` With `gsub` or `sub`, you can do this ``` gsub("!H*", "H*", total$PitchAccent, fixed = TRUE ) sub("!H*", "H*", total$PitchAccent, fixed = TRUE ) ``` Upvotes: 2 [selected_answer]
2018/03/21
4,800
17,049
<issue_start>username_0: I'm trying to extend the \*\*SimpleJpaRepository \*\* by BaseRepository interface and the BaseRepositoryImpl. Tha BaseRepositoryImpl extends \*\*SimpleJpaRepository \*\* and implements BaseRepository. In addition, I have some other Repositories such as CandidateRepository and EmployeeRepository that extends the BaseRepository. Below you can see the code following the error: [To see the project structure click here](https://i.stack.imgur.com/HigXG.jpg) ``` @NoRepositoryBean public interface BaseRepository extends JpaRepository{ //.. } @Repository public abstract class BaseRepositoryImpl extends SimpleJpaRepository implements BaseRepository{ private final EntityManager em; public BaseRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) { super(entityInformation, entityManager); this.em = entityManager; } //.. } ``` The extend Repositories: ``` @NoRepositoryBean public interface CandidateRepository extends BaseRepository{ //.. } @Repository(value="CandidateRepositoryImpl") public class CandidateRepositoryImpl extends BaseRepositoryImpl implements CandidateRepository{ public CandidateRepositoryImpl( JpaEntityInformation entityInformation, EntityManager entityManager) { super(entityInformation, entityManager); } } ``` Here is my configuration: ``` xml version="1.0" encoding="UTF-8"? ``` Service: ``` @Service(value="CandidateServiceImpl") public class CandidateServiceImpl extends BaseServiceImpl implements CandidateService{ private CandidateRepositoryImpl candidateRepository; @Autowired public CandidateServiceImpl ( @Qualifier("CandidateRepositoryImpl") JpaRepository candidateRepository ) { this.candidateRepository = (CandidateRepositoryImpl)candidateRepository; } } ``` The Error: > > Unsatisfied dependency expressed through constructor parameter 0; > nested exception is > org.springframework.beans.factory.NoSuchBeanDefinitionException: No > qualifying bean of type > 'org.springframework.data.jpa.repository.support.JpaEntityInformation' available: expected at least 1 bean which qualifies > as autowire candidate. Dependency annotations: {} > > > I followed the Spring JPA documentation, but can't understand the error attached is the running code > > 4:39:10 PM org.hibernate.Version logVersion INFO: HHH000412: Hibernate > Core {5.2.12.Final} March 21, 2018 4:39:10 PM > org.hibernate.cfg.Environment INFO: HHH000206: > hibernate.properties not found March 21, 2018 4:39:10 PM > org.hibernate.annotations.common.reflection.java.JavaReflectionManager > INFO: HCANN000001: Hibernate Commons Annotations > {5.0.1.Final} March 21, 2018 4:39:12 PM org.hibernate.dialect.Dialect > INFO: HHH000400: Using dialect: > org.hibernate.dialect.MySQL5InnoDBDialect March 21, 2018 4:39:16 PM > org.apache.catalina.core.StandardContext listenerStart SEVERE: > Exception sending context initialized event to listener instance of > class org.springframework.web.context.ContextLoaderListener > org.springframework.beans.factory.UnsatisfiedDependencyException: > Error creating bean with name 'candidateController': Unsatisfied > dependency expressed through field 'candidateBaseService'; nested > exception is > org.springframework.beans.factory.UnsatisfiedDependencyException: > Error creating bean with name 'CandidateServiceImpl' defined in file > [C:\Users\alon\Documents\workspace-sts-3.9.2.RELEASE.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Relocation\WEB-INF\classes\com\projects\service\impl\CandidateServiceImpl.class]: > Unsatisfied dependency expressed through constructor parameter 0; > nested exception is > org.springframework.beans.factory.UnsatisfiedDependencyException: > Error creating bean with name 'CandidateRepositoryImpl' defined in > file > [C:\Users\alon\Documents\workspace-sts-3.9.2.RELEASE.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Relocation\WEB-INF\classes\com\projects\repositories\impl\CandidateRepositoryImpl.class]: > Unsatisfied dependency expressed through constructor parameter 0; > nested exception is > org.springframework.beans.factory.NoSuchBeanDefinitionException: No > qualifying bean of type > 'org.springframework.data.jpa.repository.support.JpaEntityInformation' available: expected at least 1 bean which qualifies > as autowire candidate. Dependency annotations: {} at > org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587) > at > org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) > at > org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373) > at > org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344) > at > org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) > at > org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) > at > org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) > at > org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) > at > org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) > at > org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) > at > org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) > at > org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) > at > org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) > at > org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:409) > at > org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291) > at > org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103) > at > org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5110) > at > org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5633) > at > org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145) > at > org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700) > at > org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690) > at java.util.concurrent.FutureTask.run(FutureTask.java:266) at > java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) > at > java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) > at java.lang.Thread.run(Thread.java:748) Caused by: > org.springframework.beans.factory.UnsatisfiedDependencyException: > Error creating bean with name 'CandidateServiceImpl' defined in file > [C:\Users\alon\Documents\workspace-sts-3.9.2.RELEASE.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Relocation\WEB-INF\classes\com\projects\service\impl\CandidateServiceImpl.class]: > Unsatisfied dependency expressed through constructor parameter 0; > nested exception is > org.springframework.beans.factory.UnsatisfiedDependencyException: > Error creating bean with name 'CandidateRepositoryImpl' defined in > file > [C:\Users\alon\Documents\workspace-sts-3.9.2.RELEASE.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Relocation\WEB-INF\classes\com\projects\repositories\impl\CandidateRepositoryImpl.class]: > Unsatisfied dependency expressed through constructor parameter 0; > nested exception is > org.springframework.beans.factory.NoSuchBeanDefinitionException: No > qualifying bean of type > 'org.springframework.data.jpa.repository.support.JpaEntityInformation' available: expected at least 1 bean which qualifies > as autowire candidate. Dependency annotations: {} at > org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:729) > at > org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:192) > at > org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1270) > at > org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) > at > org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) > at > org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) > at > org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) > at > org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) > at > org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) > at > org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) > at > org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) > at > org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) > at > org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) > at > org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584) > ... 24 more Caused by: > org.springframework.beans.factory.UnsatisfiedDependencyException: > Error creating bean with name 'CandidateRepositoryImpl' defined in > file > [C:\Users\alon\Documents\workspace-sts-3.9.2.RELEASE.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Relocation\WEB-INF\classes\com\projects\repositories\impl\CandidateRepositoryImpl.class]: > Unsatisfied dependency expressed through constructor parameter 0; > nested exception is > org.springframework.beans.factory.NoSuchBeanDefinitionException: No > qualifying bean of type > 'org.springframework.data.jpa.repository.support.JpaEntityInformation' available: expected at least 1 bean which qualifies > as autowire candidate. Dependency annotations: {} at > org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:729) > at > org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:192) > at > org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1270) > at > org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) > at > org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) > at > org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) > at > org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) > at > org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) > at > org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) > at > org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) > at > org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) > at > org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) > at > org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) > at > org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:815) > at > org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:721) > ... 37 more Caused by: > org.springframework.beans.factory.NoSuchBeanDefinitionException: No > qualifying bean of type > 'org.springframework.data.jpa.repository.support.JpaEntityInformation' available: expected at least 1 bean which qualifies > as autowire candidate. Dependency annotations: {} at > org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1509) > at > org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) > at > org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) > at > org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:815) > at > org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:721) > ... 51 more > > > מרץ 21, 2018 4:39:16 PM org.apache.catalina.core.StandardContext > startInternal SEVERE: One or more listeners failed to start. Full > details will be found in the appropriate container log file מרץ 21, > 2018 4:39:16 PM org.apache.catalina.core.StandardContext startInternal > SEVERE: Context [/Relocation] startup failed due to previous errors > מרץ 21, 2018 4:39:16 PM org.apache.catalina.core.ApplicationContext > log INFO: Closing Spring root WebApplicationContext מרץ 21, 2018 > 4:39:16 PM org.apache.catalina.loader.WebappClassLoaderBase > clearReferencesJdbc SEVERE: The web application [/Relocation] > registered the JDBC driver [com.mysql.jdbc.Driver] but failed to > unregister it when the web application was stopped. To prevent a > memory leak, the JDBC Driver has been forcibly unregistered. מרץ 21, > 2018 4:39:16 PM org.apache.catalina.loader.WebappClassLoaderBase > clearReferencesThreads SEVERE: The web application [/Relocation] > appears to have started a thread named [Abandoned connection cleanup > thread] but has failed to stop it. This is very likely to create a > memory leak. מרץ 21, 2018 4:39:16 PM > org.apache.coyote.AbstractProtocol start INFO: Starting > ProtocolHandler ["http-bio-8080"] מרץ 21, 2018 4:39:16 PM > org.apache.coyote.AbstractProtocol start INFO: Starting > ProtocolHandler ["ajp-bio-8009"] מרץ 21, 2018 4:39:16 PM > org.apache.catalina.startup.Catalina start INFO: Server startup in > 17422 ms > > ><issue_comment>username_1: You are doing a somewhat weird combination of things here. On the one hand, you effectively disable all the Spring Data stuff by using `@NoRepositoryBean` on `CandidateRepository` and providing your own implementation. But then your implementation is based extends `SimpleJpaRepository` which is a core component of Spring Data but it doesn't get configured properly since you basically disabled it. I guess it's time to make up your mind: 1. Do you want to change the behavior that is provided by `SimpleJpaRepository`? Possibly adding methods to your base implementation. If so extend it, leaving constructors as they are and use it as your [`repositoryBaseClass`](https://docs.spring.io/spring-data/data-jpa/docs/current/api/org/springframework/data/jpa/repository/config/EnableJpaRepositories.html#repositoryBaseClass--). [Here is a tutorial how to do that](https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-adding-custom-methods-into-all-repositories/). 2. Just provide custom implementation for one (or some) repositories. Then use [custom implementations](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.single-repository-behavior). Upvotes: 3 <issue_comment>username_2: Being pragmatic, you're trying to extend `SimpleJpaRepository`, but once you disabling it Spring does not load any implementation of `JpaEntityInformation` and thus the exception. Also, as @jens-schauder said, your mixing concepts. Try to follow this [very well explained tutorial](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories) to see if it helps. Upvotes: 2
2018/03/21
610
2,427
<issue_start>username_0: As part of my code churn reporting, I am trying to create a code churn report which captures the number of lines changed between local versions of some files and the associated remote files. Assume I have the following project structure: ``` C:\dev_ws\helloApp\services\ServiceA C:\dev_ws\helloApp\services\ServiceB C:\dev_ws\helloApp\services\ServiceC ``` The services A,B,C folders have local versions of `git` files. The idea is to create a report capturing the total number of lines changed across all the files contained in services A,B,C recursively. The `Git` version will always contain the delta i.e. the `Gitlab` version is been worked on by developers. I am doing this on `Windows 7` machine. Any help will be appreciated.<issue_comment>username_1: You are doing a somewhat weird combination of things here. On the one hand, you effectively disable all the Spring Data stuff by using `@NoRepositoryBean` on `CandidateRepository` and providing your own implementation. But then your implementation is based extends `SimpleJpaRepository` which is a core component of Spring Data but it doesn't get configured properly since you basically disabled it. I guess it's time to make up your mind: 1. Do you want to change the behavior that is provided by `SimpleJpaRepository`? Possibly adding methods to your base implementation. If so extend it, leaving constructors as they are and use it as your [`repositoryBaseClass`](https://docs.spring.io/spring-data/data-jpa/docs/current/api/org/springframework/data/jpa/repository/config/EnableJpaRepositories.html#repositoryBaseClass--). [Here is a tutorial how to do that](https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-adding-custom-methods-into-all-repositories/). 2. Just provide custom implementation for one (or some) repositories. Then use [custom implementations](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.single-repository-behavior). Upvotes: 3 <issue_comment>username_2: Being pragmatic, you're trying to extend `SimpleJpaRepository`, but once you disabling it Spring does not load any implementation of `JpaEntityInformation` and thus the exception. Also, as @jens-schauder said, your mixing concepts. Try to follow this [very well explained tutorial](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories) to see if it helps. Upvotes: 2
2018/03/21
457
1,497
<issue_start>username_0: I'm implementing an asp.net core API with admin-on-rest. A custom REST client communicates to the API endpoints, but the mapping is fairly standard. When I try to implement a into the interface, the deletion of elements works fine. Still, I get an error on every edit or deletion view for an element with the following text: "Incorrect Element". The console is empty, and everything works as expected. What causes the error - and how can I solve this? I've attached a screenshot of the error popup. [Screenshot of the error](https://i.stack.imgur.com/uukmx.png) Update 1: Here is the code of my custom REST client: [customrestclient gist](https://gist.github.com/sportluffi/ae7b67110579253d275479cc1752e397) and the included fetch.js: [fetch.js](https://gist.github.com/sportluffi/8714ce0a54e747ae4bda4e1fc904fa0d)<issue_comment>username_1: Double check your custom `restClient` returns at least the `id` of the deleted resource inside a `data` object. Upvotes: 1 <issue_comment>username_2: I was finally able to fix the issue. One of my API endpoints returned a list instead of a single element for one of my ReferenceInput-elements. This was the content response before my change: ``` [{ "languageId": 2, "id": 2, "name": "Danish", "isoCode": "dan" }] ``` And this is the correct response, that does not trigger the error: ``` { "languageId": 2, "id": 2, "name": "Danish", "isoCode": "dan" } ``` Upvotes: 1 [selected_answer]
2018/03/21
816
2,395
<issue_start>username_0: Some questions are similar to this topic ([here](https://stackoverflow.com/questions/37377819/countif-equivalent-in-dplyr-summarise) or [here](https://stackoverflow.com/questions/26469975/creating-a-frequency-table-in-r), as an example) and I know one solution that works, but I want a more elegant response. I work in epidemiology and I have variables 1 and 0 (or NA). Example: Does patient has cancer? **NA or 0 is no** **1 is yes** Let's say I have several variables in my dataset and I want to count only variables with "1". Its a classical frequency table, but dplyr are turning things more complicated than I could imagine at the first glance. My code is working: ``` dataset %>% select(VISimpair, HEARimpai, IntDis, PhyDis, EmBehDis, LearnDis, ComDis, ASD, HealthImpair, DevDelays) %>% # replace to your needs summarise_all(funs(sum(1-is.na(.)))) ``` And you can reproduce this code here: ``` library(tidyverse) dataset <- data.frame(var1 = rep(c(NA,1),100), var2=rep(c(NA,1),100)) dataset %>% select(var1, var2) %>% summarise_all(funs(sum(1-is.na(.)))) ``` But I really want to select all variables I want, count how many 0 (or NA) I have and how many 1 I have and report it and have this output [![ desired output ](https://i.stack.imgur.com/1l5qf.png)](https://i.stack.imgur.com/1l5qf.png) Thanks.<issue_comment>username_1: A quick and dirty method to do this is to coerce your input into factors: `dataset$var1 = as.factor(dataset$var1) dataset$var2 = as.factor(dataset$var2) summary(dataset$var1) summary(dataset$var2)` Summary tells you number of occurrences of each levels of factor. Upvotes: 0 <issue_comment>username_2: What about the following frequency table per variable? First, I edit your sample data to also include 0's and load the necessary libraries. ``` library(tidyr) library(dplyr) dataset <- data.frame(var1 = rep(c(NA,1,0),100), var2=rep(c(NA,1,0),100)) ``` Second, I convert the data using `gather` to make it easier to `group_by` later for the frequency table created by `count`, as mentioned by CPak. ``` dataset %>% select(var1, var2) %>% gather(var, val) %>% mutate(val = factor(val)) %>% group_by(var, val) %>% count() # A tibble: 6 x 3 # Groups: var, val [6] var val n 1 var1 0 100 2 var1 1 100 3 var1 NA 100 4 var2 0 100 5 var2 1 100 6 var2 NA 100 ``` Upvotes: 2
2018/03/21
4,656
12,244
<issue_start>username_0: I have a code that generates some numbers, and now I need to count how frequent they are. For example, the code will generate 100000 numbers, and i need to know how many times does 0 appear, 1, 2... I know that this can be done with strings, but im having a problem turning those values into one big string. You see, all the generated numbers will be the same variable G, so if a ask to turn G into a string, Im going to have a string of the very last number assigned to G, and not of all of them, that is beacuse the variable G changes value each time its printed, because it is inside a loop. is there any way for me to move ALL the printed values into one big string? (If 100000 is too much for a string, i can generate less numbers with little problem) This is the code ``` int a,b,c,d,e,f,g,h,i,k,A,B,C,D,E,F,G; srand(time(NULL)); int seed = rand(); default_random_engine ran { static_cast ( chrono::high\_resolution\_clock::now().time\_since\_epoch().count())}; default\_random\_engine ran\_2 { static\_cast ( chrono::high\_resolution\_clock::now().time\_since\_epoch().count())}; uniform\_int\_distribution range {1,50}; a=range (ran); b = 2; c = 107; d = 109; e = 113; f = 167; g = 173; h = 587; i = 13; for ( k=0; k < 100000; k++) { srand(time(NULL)); int seed = rand(); default\_random\_engine ran { static\_cast ( chrono::high\_resolution\_clock::now().time\_since\_epoch().count())}; default\_random\_engine ran\_2 { static\_cast ( chrono::high\_resolution\_clock::now().time\_since\_epoch().count())}; uniform\_int\_distribution range {1,50}; a=range (ran); b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; f++; f++; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; h--; h--; h--; h--; h--; h--; h--; h--; h--; h--; h--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; A= (a\*b\*c\*f); B= ((A^13)/d\*h-i^a); C= (A\*B^i-b\*h\*g\*e\*a); D= (b+c+d+e+f+g+h+i)\*a; E= ((a\*A\*B\*C\*D)/100000000); F= E % 10; if ( F < 0 ) { G = F\*(-1); } else { G = F; } cout << G; } ``` } Thank you very much! :) Have a great day<issue_comment>username_1: > > and i need to know how many times does 0 appear, 1, 2... > > > And to achieve that you should not store all numbers into one huge string, but you better have `int` array with 10 elements (one counter for each digit) and increase each accordingly when new number generated - at the end you have all your counters: ``` std::vector counters( 10 ); ... for( auto c : std::to\_string( G ) ) ++counters[ c - '0' ]; // at the end all counters in the vector ``` Upvotes: 2 <issue_comment>username_2: > > if a ask to turn G into a string, Im going to have a string of the very last number assigned to G, and not of all of them > > > Simply declare a separate `std::string` variable that your loop can append to each time a new number is assigned to `G`, eg: ``` std::string everything; ... G = ...; everything += std::to_string(G); ... ``` Then after the loop is finished, you can loop through `everything` counting the characters as needed. Or, consider using a `std::map` keyed by digit chars, and let it handle the counting for you: ``` std::map counter; ... G = ...; for (char ch : std::to\_string(G)) counter[ch]++; ... ``` Or, just use a fixed array indexed by digits: ``` int counter[10]; ... G = ...; for (char ch : std::to_string(G)) counter[ch-'0']++; ... ``` Either way, after the loop is finished, you can then loop through `counter` to retrieve the counts of each digit. Upvotes: 2 [selected_answer]<issue_comment>username_3: you need to have a variable living out side of your function that you can append to every time the loop runs. when the loop finishes than you will have all of the content stored inside of that str: variable ``` int a,b,c,d,e,f,g,h,i,k,A,B,C,D,E,F,G; srand(time(NULL)); int seed = rand(); default_random_engine ran { static_cast ( chrono::high\_resolution\_clock::now().time\_since\_epoch().count())}; default\_random\_engine ran\_2 { static\_cast ( chrono::high\_resolution\_clock::now().time\_since\_epoch().count())}; uniform\_int\_distribution range {1,50}; a=range (ran); b = 2; c = 107; d = 109; e = 113; f = 167; g = 173; h = 587; i = 13; std::string str; for ( k=0; k < 100000; k++) { srand(time(NULL)); int seed = rand(); default\_random\_engine ran { static\_cast ( chrono::high\_resolution\_clock::now().time\_since\_epoch().count())}; default\_random\_engine ran\_2 { static\_cast ( chrono::high\_resolution\_clock::now().time\_since\_epoch().count())}; uniform\_int\_distribution range {1,50}; a=range (ran); b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; b++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; c++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; d++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; e++; f++; f++; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; g--; h--; h--; h--; h--; h--; h--; h--; h--; h--; h--; h--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; i--; A= (a\*b\*c\*f); B= ((A^13)/d\*h-i^a); C= (A\*B^i-b\*h\*g\*e\*a); D= (b+c+d+e+f+g+h+i)\*a; E= ((a\*A\*B\*C\*D)/100000000); F= E % 10; if ( F < 0 ) { G = F\*(-1); } else { G = F; } cout << G; str.append(G) } cout << str; ``` Upvotes: -1 <issue_comment>username_4: I don't know how to do that with strings but hashmap should help here (see below); The cons of this is the mem consumption. With a large number of probes and really random values, you can end up with memory allocation problem. ``` // Example program #include #include #include #include int main() { std::unordered\_map histogram; std::unordered\_map::iterator it; for (int i = 0; i < 1000; i++) { int v = rand(); if (histogram.find(v) == histogram.end()) { histogram[v] = 0; } histogram[v]++; } for (it = histogram.begin(); it != histogram.end(); it++ ) { std::cout << "VALUE:" << it->first // number << "\t FREQ:" << it->second // frequency << std::endl ; } } ``` Upvotes: 0
2018/03/21
1,172
3,888
<issue_start>username_0: I have two Map type columns in a Dataframe. Is there a way I can create a new Map column merging these two columns in spark Sql using .withColumn ? ``` val sampleDF = Seq( ("Jeff", Map("key1" -> "val1"), Map("key2" -> "val2")) ).toDF("name", "mapCol1", "mapCol2") sampleDF.show() +----+-----------------+-----------------+ |name| mapCol1| mapCol2| +----+-----------------+-----------------+ |Jeff|Map(key1 -> val1)|Map(key2 -> val2)| +----+-----------------+-----------------+ ```<issue_comment>username_1: You can write a `udf` function *to merge both column into one* using `withColumn` as below ``` import org.apache.spark.sql.functions._ def mergeUdf = udf((map1: Map[String, String], map2: Map[String, String])=> map1 ++ map2) sampleDF.withColumn("merged", mergeUdf(col("mapCol1"), col("mapCol2"))).show(false) ``` which should give you ``` +----+-----------------+-----------------+-------------------------------+ |name|mapCol1 |mapCol2 |merged | +----+-----------------+-----------------+-------------------------------+ |Jeff|Map(key1 -> val1)|Map(key2 -> val2)|Map(key1 -> val1, key2 -> val2)| +----+-----------------+-----------------+-------------------------------+ ``` I hope the answer is helpful Upvotes: 4 [selected_answer]<issue_comment>username_2: You can use struct to achieve this. ``` val sampleDF = Seq( ("Jeff", Map("key1" -> "val1"), Map("key2" -> "val2")) ).toDF("name", "mapCol1", "mapCol2") sampleDF.show() +----+-----------------+-----------------+ |name| mapCol1| mapCol2| +----+-----------------+-----------------+ |Jeff|Map(key1 -> val1)|Map(key2 -> val2)| +----+-----------------+-----------------+ sampleDF.withColumn("NewColumn",struct(sampleDF("mapCol1"), sampleDF("mapCol2"))).take(2) res17: Array[org.apache.spark.sql.Row] = Array([Jeff,Map(key1 -> val1),Map(key2 -> val2),[Map(key1 -> val1),Map(key2 -> val2)]]) +----+-----------------+-----------------+--------------------+ |name| mapCol1| mapCol2| NewColumn| +----+-----------------+-----------------+--------------------+ |Jeff|Map(key1 -> val1)|Map(key2 -> val2)|[Map(key1 -> val1...| +----+-----------------+-----------------+--------------------+ ``` Reference : [How to merge two columns of a `Dataframe` in Spark into one 2-Tuple?](https://stackoverflow.com/questions/32799595/how-to-merge-two-columns-of-a-dataframe-in-spark-into-one-2-tuple) Upvotes: -1 <issue_comment>username_3: > > Use UDF only if you do not have an inbuilt function for your use case due to performance reasons. > > > Spark version 2.4 and above =========================== ``` import org.apache.spark.sql.functions.{map_concat, col} sampleDF.withColumn("map_concat", map_concat(col("mapCol1"), col("mapCol2"))).show(false) ``` Outputs ``` +----+-----------------+-----------------+-------------------------------+ |name|mapCol1 |mapCol2 |map_concat | +----+-----------------+-----------------+-------------------------------+ |Jeff|Map(key1 -> val1)|Map(key2 -> val2)|Map(key1 -> val1, key2 -> val2)| +----+-----------------+-----------------+-------------------------------+ ``` Spark version 2.4 below ======================= Create a UDF as per *@RameshMaharjan* [answer in this question](https://stackoverflow.com/a/49413838/1592191), but I added with a null check to avoid NPE at runtime which will fail the job eventually if not added. ``` import org.apache.spark.sql.functions.{udf, col} val map_concat = udf((map1: Map[String, String], map2: Map[String, String]) => if (map1 == null) { map2 } else if (map2 == null) { map1 } else { map1 ++ map2 }) sampleDF.withColumn("map_concat", map_concat(col("mapCol1"), col("mapCol2"))) .show(false) ``` Upvotes: 3
2018/03/21
552
1,694
<issue_start>username_0: I am trying to write a SQL like below in DB2. ``` insert into tableA (col1, col2, col3) select max(col1) + 1, '-2', col3 from tableA where col2 = -1 ``` Here the aim is copy all the record of tableA from -1 to -2 and here col1 is primary key and this should be increment by 1. Now the problem is the select query will return more then one row like below ``` 1001 -2 xyz 1001 -2 pqr 1001 -2 xdc ``` And it is not able to insert as the key is same. Is there any way I can write the select sql so that it can return like below ``` 1001 -2 xyz 1002 -2 pqr 1003 -2 xdc ``` and my insert will work, or is there any alternative way to the same with easiest way. Note: The table do not have any trigger or some thing to auto increment the primary key.<issue_comment>username_1: Yes. Use `row_number()`: ``` insert into tableA ( col1, col2, col3) select max(col1) + row_number() over (order by col3), '-2', col3 from tableA where col2 = -1 group by col3; ``` If you don't have a `group by`, then do: ``` insert into tableA ( col1, col2, col3) select maxcol1 + row_number() over (order by col3), '-2', col3 from (select a.*, max(col1) over () as maxcol1 from tableA a ) a where col2 = -1; ``` The right way to do this is to use a generated auto-incrementing value for `col1`. This code all has a problem if multiple threads are trying to do inserts at the same time. Upvotes: 2 [selected_answer]<issue_comment>username_2: Try this query ! ``` insert into tableA (col1, col2, col3) select (max(col1) + 1) as col1, '-2' as col2, col3 from tableA where col2 = -1 ``` Upvotes: 0
2018/03/21
1,053
3,645
<issue_start>username_0: I use the following function to chunk iterable python objects. ``` from itertools import islice def chunked_iterable(iterable, chunk_size): it = iter(iterable) while True: chunk = tuple(islice(it, chunk_size)) if not chunk: break yield chunk ``` I'm looking to do something similar with a basic JSON file. ``` [ {object1: 'object1'}, {object2: 'object2'}, {object3: 'object3'}, {object4: 'object4'}, {object5: 'object5'}, {object6: 'object6'}, etc... ] ``` Like this. ``` from pathlib import Path import json def json_chunk(json_array_of_objects, object_count): # What goes here? if __name__ == '__main__': with open(Path(__file__).parent / 'raw_data.json') as raw_data: json_data = json.load(raw_data) for json_array_with_five_objects in enumerate(json_chunk(json_data, 5)): for object in json_array_with_five_objects: print(object[0]) ``` Is the term I'm looking for "streaming" JSON data? How do you stream JSON data? As a learning exercise I'm trying to stick with base python functionality for now but answers using other packages are helpful too.<issue_comment>username_1: > > JSON is a text format that is completely language independent but uses > conventions that are familiar to programmers of the C-family of > languages, including C, C++, C#, Java, JavaScript, Perl, Python, and > many others. These properties make JSON an ideal data-interchange > language. -<https://www.json.org/> > > > JSON is a string of text. You would need to convert it back to python to be iteratable Upvotes: 0 <issue_comment>username_2: After further thought, using `object_hook` or `object_pairs_hook` arguments would require reading the entire file into memory first—so to avoid doing that, instead here's something that reads the file incrementally, line-by-line. I had to modify your example JSON file to make it valid JSON (what you have in your question is a Python dictionary). Note that this code is format-specific in the sense that it assumes each JSON object in the array lies entirely on a single line—although it could be changed to handle multiline object definitions if necessary. So here's a sample test input file with valid JSON contents: ```none [ {"thing1": "object1"}, {"thing2": "object2"}, {"thing3": "object3"}, {"thing4": "object4"}, {"thing5": "object5"}, {"thing6": "object6"} ] ``` Code: ``` from itertools import zip_longest import json from pathlib import Path def grouper(n, iterable, fillvalue=None): """ s -> (s0, s1...sn-1), (sn, sn+1...s2n-1), (s2n, s2n+1...s3n-1), ... """ return zip_longest(*[iter(iterable)]*n, fillvalue=fillvalue) def read_json_objects(fp): """ Read objects from file containing an array of JSON objects. """ next(fp) # Skip first line. for line in (line.strip() for line in fp): if line[0] == ']': # Last line? break yield json.loads(line.rstrip(',')) def json_chunk(json_file_path, object_count): with open(json_file_path) as fp: for group in grouper(object_count, read_json_objects(fp)): yield(tuple(obj for obj in group if obj is not None)) if __name__ == '__main__': json_file_path = Path(__file__).parent / 'raw_data.json' for array in json_chunk(json_file_path, 5): print(array) ``` Output from processing test file: ```none ({'thing1': 'object1'}, {'thing2': 'object2'}, {'thing3': 'object3'}, {'thing4': 'object4'}, {'thing5': 'object5'}) ({'thing6': 'object6'},) ``` Upvotes: 3 [selected_answer]
2018/03/21
1,057
3,338
<issue_start>username_0: I asked two questions related to my current problem, but the way I asked and the code that I provided wasn't been enough to solve it, so I present the problem (that was raised from the previous solutions attempts) in a more complete way on this code snippet. Basically I want this PHP generated file tree to expand/collapse the way it should. With the JQuery code that some nice people here at SO provided me it's almost solved. The problem is now that when you expand a child the parent collapses, you will see this running the code below. **Notes**: -I'm using Wordpress and for some reason you need to make sure that the tree is collapsed at first, otherwise it's displayed fully expanded. -I have a **related side problem**: When you click to toggle, the scroll goes all the way up. ```js function init_php_file_tree() { $('.pft-directory') .on('click', function() { $(this).children('ul').toggle(); }) .children("ul").hide(); }; jQuery(init_php_file_tree); ``` ```html + [Parent Directory](#) - [Child directory](#) * somefile.pdf * somefile2.doc + [Another parent directory](#) - [Child directory](#) * V1.docx * [Child directory 2](#) + V2.pdf + HH-V1.png * [Child directory](#) - [Child directory 2](#) * HH-V1.pdf * [Child directory 3](#) + HH-V1.pdf * [Child directory 4](#) + HH-V1.pdf ```<issue_comment>username_1: You can stop the bubbling that occurs by using `event.stopPropagation()` (<https://api.jquery.com/event.stoppropagation/>). Regarding your second problem, that the page scrolls up, that is very likely due to your `a href="#"`'s. Replace them with url's or use `a href="javascript:;"`. Example below: ```js function init_php_file_tree() { $('.pft-directory') .on('click', function(e) { e.stopPropagation(); $(this).children('ul').toggle(); }) .children("ul").hide(); }; jQuery(init_php_file_tree); ``` ```html + [Parent Directory](#) - [Child directory](#) * somefile.pdf * somefile2.doc + [Another parent directory](#) - [Child directory](#) * V1.docx * [Child directory 2](#) + V2.pdf + HH-V1.png * [Child directory](#) - [Child directory 2](#) * HH-V1.pdf * [Child directory 3](#) + HH-V1.pdf * [Child directory 4](#) + HH-V1.pdf ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: The reason is when you are clicking on child node it's click event is pass to it's parent node so you have to stop that passing. and for doing so you have to use `stopPropagation()` which will not pass event to it's parent element. For more info on `stopPropagation()` see [this](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation) ```js function init_php_file_tree() { $('.pft-directory') .on('click', function(e) { $(this).children('ul').toggle(); e.stopPropagation(); }) .children("ul").hide();; }; jQuery(init_php_file_tree); ``` ```html + [Parent Directory](#) - [Child directory](#) * somefile.pdf * somefile2.doc + [Another parent directory](#) - [Child directory](#) * V1.docx * [Child directory 2](#) + V2.pdf + HH-V1.png * [Child directory](#) - [Child directory 2](#) * HH-V1.pdf * [Child directory 3](#) + HH-V1.pdf * [Child directory 4](#) + HH-V1.pdf ``` Upvotes: 0
2018/03/21
1,568
3,727
<issue_start>username_0: I know this is a stupid question, but I'm kinda frustrated with my code because it takes so much time. Jere is one part of my code. basically I have a matrix called "distance"... ``` a b c 1 2 5 7 2 6 8 4 3 9 2 3 ``` and then lets say I have a column in a data frame, contains of {a,b,c} ``` c1 c2 c3 c ... ... a a just another column b c ... ... ``` so I want to do a match, I wanna make another matrix with ncol=nrow(distance), and nrow=nrow(c1). where replace the factor value with their distance value. Here's an example of the first column of matrix that I'm going to make ``` a will replaced by 2 b will replaced by 5 c will replaced by 7 ``` and for the second column, i will take row number 2 from distance matrix, and so on... so the result will be like this ``` m1 m2 m3 7 4 3 2 6 9 2 6 9 5 8 2 7 4 3 ``` That is just an easy example, and I'm running this code, but when it deals with large iterations, it's kinda stressful for me. ``` for(l in 1:ncol(d.cat)){ get.unique = sort(unique(d.cat[, l])) for(j in 1:nrow(d.cat)){ value = as.character(d.cat[j, l]) index = which(get.unique == value) d2[j,l] = (d[[l]][i, index]) } } ``` d.cat is categorical data. And d[[...]] is the list of matrix distance for every column in d.cat.<issue_comment>username_1: Try to store the indices and do the updating in one go. Lets say your distance matrix is dmat and data frame is df and you want to create a matrix named newmat ``` a.ind = which(df$c1=="a") b.ind = which(df$c1=="b") c.ind = which(df$c1=="c") newmat = matrix(0,nrow=length(df$c1),ncol=3) newmat[a.ind,] = dmat[,1] newmat[b.ind,] = dmat[,2] newmat[c.ind,] = dmat[,3] ``` Upvotes: 2 <issue_comment>username_2: Your data ``` mat <- matrix(c(2,6,9,5,8,2,7,4,3), nrow=3) rownames(mat) <- 1:3 colnames(mat) <- letters[1:3] library(dplyr) set.seed(1) df <- as.data.frame(matrix(sample(letters[1:3], 12, replace=TRUE), nrow=4)) %>% setNames(paste0("c", 1:3)) # c1 c2 c3 # 1 a a b # 2 b c a # 3 b c a # 4 c b a ``` Using `purrr::map2_df`, iterate through columns of `df` and columns of `tmat` ``` library(purrr) tmat <- t(mat) map2_df(df, seq_len(ncol(tmat)), ~tmat[,.y][.x]) # # A tibble: 4 x 3 # c1 c2 c3 # # 1 2. 6. 2. # 2 5. 4. 9. # 3 5. 4. 9. # 4 7. 8. 9. ``` Upvotes: 1 <issue_comment>username_3: Here is my attempt using the tidyverse : ``` library(tidyverse) # Lets create some example distance <- data_frame(a = sample(1:10, 1000, T), b = sample(1:10, 1000, T), c = sample(1:10, 1000, T)) c1 <- data_frame(c1 = sample(letters[1:3], 1000, T), c2 = sample(letters[1:3], 1000, T)) # First rearrange a little bit your data to make it more tidy distance2 <- distance %>% mutate(i = seq_len(n())) %>% gather(col, value, -i) c2 <- c1 %>% mutate(i = seq_len(n()) %>% gather(col, value, -i) # Now just join the data and spread it again c12 %>% left_join(distance2, by = c("i", "value" = "col")) %>% select(i, col, value.y) %>% spread(col, value.y) ``` Upvotes: 1 <issue_comment>username_4: Here's some data ``` set.seed(123) d = matrix(1:9, 3, dimnames=list(NULL, letters[1:3])) df = data.frame(c1 = sample(letters[1:3], 10, TRUE), stringsAsFactors=FALSE) ``` and a solution ``` t(d[, match(df$c1, colnames(d))]) ``` For example ``` > d a b c [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > df$c1 [1] "a" "c" "b" "c" "c" "a" "b" "c" "b" "b" > t(d[,match(df$c1, colnames(d))]) [,1] [,2] [,3] a 1 2 3 c 7 8 9 b 4 5 6 c 7 8 9 c 7 8 9 a 1 2 3 b 4 5 6 c 7 8 9 b 4 5 6 b 4 5 6 ``` Upvotes: 2 [selected_answer]
2018/03/21
1,241
2,721
<issue_start>username_0: I have a particular date and time with me in shell. Now I need to subtract 7 hours from that particular date and time. eg. 2018-03-20 21:00:00 -> 2018-03-20 14:00:00 2018-03-20 06:00:00 -> 2018-03-19 23:00:00 I have both date and time in different strings as well. How to write this in shell (v4.1)?<issue_comment>username_1: Try to store the indices and do the updating in one go. Lets say your distance matrix is dmat and data frame is df and you want to create a matrix named newmat ``` a.ind = which(df$c1=="a") b.ind = which(df$c1=="b") c.ind = which(df$c1=="c") newmat = matrix(0,nrow=length(df$c1),ncol=3) newmat[a.ind,] = dmat[,1] newmat[b.ind,] = dmat[,2] newmat[c.ind,] = dmat[,3] ``` Upvotes: 2 <issue_comment>username_2: Your data ``` mat <- matrix(c(2,6,9,5,8,2,7,4,3), nrow=3) rownames(mat) <- 1:3 colnames(mat) <- letters[1:3] library(dplyr) set.seed(1) df <- as.data.frame(matrix(sample(letters[1:3], 12, replace=TRUE), nrow=4)) %>% setNames(paste0("c", 1:3)) # c1 c2 c3 # 1 a a b # 2 b c a # 3 b c a # 4 c b a ``` Using `purrr::map2_df`, iterate through columns of `df` and columns of `tmat` ``` library(purrr) tmat <- t(mat) map2_df(df, seq_len(ncol(tmat)), ~tmat[,.y][.x]) # # A tibble: 4 x 3 # c1 c2 c3 # # 1 2. 6. 2. # 2 5. 4. 9. # 3 5. 4. 9. # 4 7. 8. 9. ``` Upvotes: 1 <issue_comment>username_3: Here is my attempt using the tidyverse : ``` library(tidyverse) # Lets create some example distance <- data_frame(a = sample(1:10, 1000, T), b = sample(1:10, 1000, T), c = sample(1:10, 1000, T)) c1 <- data_frame(c1 = sample(letters[1:3], 1000, T), c2 = sample(letters[1:3], 1000, T)) # First rearrange a little bit your data to make it more tidy distance2 <- distance %>% mutate(i = seq_len(n())) %>% gather(col, value, -i) c2 <- c1 %>% mutate(i = seq_len(n()) %>% gather(col, value, -i) # Now just join the data and spread it again c12 %>% left_join(distance2, by = c("i", "value" = "col")) %>% select(i, col, value.y) %>% spread(col, value.y) ``` Upvotes: 1 <issue_comment>username_4: Here's some data ``` set.seed(123) d = matrix(1:9, 3, dimnames=list(NULL, letters[1:3])) df = data.frame(c1 = sample(letters[1:3], 10, TRUE), stringsAsFactors=FALSE) ``` and a solution ``` t(d[, match(df$c1, colnames(d))]) ``` For example ``` > d a b c [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > df$c1 [1] "a" "c" "b" "c" "c" "a" "b" "c" "b" "b" > t(d[,match(df$c1, colnames(d))]) [,1] [,2] [,3] a 1 2 3 c 7 8 9 b 4 5 6 c 7 8 9 c 7 8 9 a 1 2 3 b 4 5 6 c 7 8 9 b 4 5 6 b 4 5 6 ``` Upvotes: 2 [selected_answer]
2018/03/21
630
1,995
<issue_start>username_0: I have this query that works fine on mysql, but I can't get it to work in CodeIngniter's Query Builder Class. It's a search box with multiple inputs. I've tried this, but couldn't make it work. ``` $this->db->like('num_articulo ', $aricle_number, 'after'); $array = array('descripcion1' => $article_description, 'descripcion2' => $article_description) $this->db->or_like($array); $this->db->where('status', 1); return $this->db->get('articulos')->result_array(); ``` Here is my sql ``` SELECT * FROM articulos WHERE num_articulo LIKE 'yyyyy%' AND (descripcion1 LIKE '%xxxx%' OR descripcion2 LIKE '%xxxx%') ```<issue_comment>username_1: might not be the nicest thing to do, but it worked just fine. ``` $this->db->like('num_articulo', $number, 'after'); $this->db->where('status', 1); $this->db->where('(descripcion1 LIKE "%'.$search_data.'%" OR descripcion2 LIKE "%'.$search_data.'%")'); return $this->db->get('articulos')->result_array(); ``` Upvotes: 0 <issue_comment>username_2: CodeIgniter Query Builder has a neat [query grouping](https://www.codeigniter.com/user_guide/database/query_builder.html#query-grouping) feature: ``` $this->db->group_start() $this->db->group_end() ``` Hence, you're query would look like, in a pure QB fashion: ``` $this->db->like('num_articulo ', $aricle_number, 'after'); $this->db->group_start(); $this->db->like('descripcion1', $article_description); $this->db->or_like('descripcion2', $article_description); $this->db->group_end(); $this->db->where('status', 1); // This one doesn't seem to appear in your query example? $this->db->get('articulos')->result_array(); ``` You would get the following query: ``` SELECT * FROM `articulos` WHERE `num_articulo` LIKE 'yyyyy%' ESCAPE '!' AND ( `descripcion1` LIKE '%xxxx%' ESCAPE '!' OR `descripcion2` LIKE '%xxxx%' ESCAPE '!' ) AND `status` = 1 ``` Note: CodeIgniter adds `ESCAPE '!'` internally to identify the escape symbol. Upvotes: 2 [selected_answer]
2018/03/21
638
2,121
<issue_start>username_0: I need the center and size of a box collider in world coordinates. So far I got this: ``` public GameObject Model; BoxCollider m_Collider; Vector3 Center; Vector3 Size; void Start() { m_Collider = Model.GetComponent(); Center = transform.TransformPoint(m\_Collider.center); Size = transform.TransformPoint(m\_Collider.size); print(Center + " " + Size); } ``` Unity prints out this: > > (0.0, 1.0, 4.4) (0.8, 1.6, 5.0) > > > Unfortunately this is not precise enough as I need more decimals. How do I turn this into a longer float?<issue_comment>username_1: Instead of ```cs print(Center + " " + Size); ``` use this: ``` Debug.Log(Center.ToString("F4") + " " + Size.ToString("F4")); ``` You can change `4` to another number, it represents the number of decimal values the method will print in the console. Reference: <https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings> Upvotes: 0 <issue_comment>username_2: > > Unfortunately this is not precise enough as I need more decimals. How > do I turn this into a longer float? > > > It is precise. The problem is the `print(Center + " " + Size);` or `Debug.Log(Center + " " + Size);` functions. They are both made to truncate the `Vector3` values. Just make a simple wrapper to show all the values in the Vector: ``` public class Logger { public static void Log(object message) { if (message.GetType() == typeof(Vector3)) { Vector3 vec = (Vector3)message; string res = String.Format("({0}, {1}, {2})", vec.x, vec.y, vec.z); Debug.Log(res); } else { Debug.Log(message); } } } ``` and to use: ``` Logger.Log(Center); Logger.Log(Size); ``` **Note**: Do **not** try to pass `Center + " " + Size` to the print function including the custom one above. This is because the the overload that combines a `Vector3` with a `string` also truncates it's value. Print them on different lines like I did above and you should get the full values. Upvotes: 2 [selected_answer]
2018/03/21
1,385
5,184
<issue_start>username_0: I am trying to work on the mechanics for a game I want to work on, however I don't have much experience with this area of programming. I have gotten a circle to move smoothly left and right with the A and D keys using requestAnimationFrame(), however I have absolutely no clue what the best approach would be to make the circle "jump" so to speak. I want the ball to be able to move upwards when W is pressed until a certain height is reached, and then begin to fall down to the ground at a certain rate. I also want to retain the ability for the ball to move left and right while jumping. I'm not exactly sure how to go about this as I have little experience with request animation frame(), I've tried cancelling the current animation frame and calling a new one within a jump function but that doesn't seem to work at all. Here is my code so far: ``` var canvas, ctx, westX = 300, westY = 400, velX = 0, velY = 0, speed = 3, jumpSpeed = 2, friction = 0.98, keys = [], jumping = false; window.onload = function(){ canvas = document.getElementById("gameCanvas"); ctx = canvas.getContext("2d"); drawLevel(); //intial level draw } function drawLevel() { move(); ctx.clearRect(0,0,canvas.width, canvas.height); ctx.fillStyle = "#c3c3d5"; ctx.fillRect(0,0,canvas.width,canvas.height); ctx.fillStyle = "black"; ctx.beginPath(); ctx.arc(westX,westY,8,0,Math.PI*2,true); ctx.fill(); if (!keys[87] && !keys[32]) requestAnimationFrame(drawLevel); if (keys[87] || keys[32]) { jump(); } } ``` Character Movement: ``` //moves character function move() { //requestAnimationFrame(move); if (keys[65]) { //if a is pressed if (velX > -speed) { velX--; } } if (keys[68]) { //if d is pressed if (velX < speed) { velX++; } } velX*= friction; westX += velX; //checks if character is at the edge if (westX >= canvas.width-8) { westX = canvas.width-8; } else if (westX <= 8) { westX = 8; } } ``` Attempt at jump function: ``` function jump() { requestAnimationFrame(jump) if (velY > -jumpSpeed) { velY--; } velY*= friction; westY += velY; } document.addEventListener("keydown", function(e) { keys[e.keyCode] = true; }); document.addEventListener("keyup", function(e) { keys[e.keyCode] = false; }); ``` Also, here is a codepen link to show what I have working so far: <https://codepen.io/shanetorres/pen/OvRdjq?editors=1010> Any help or suggestions would be greatly appreciated!<issue_comment>username_1: Do you specifically want to program the physics yourself or is building the game itself your primary goal? If you're not too interested in programming the physics, I'd recommend that you look into [Phaser.io framework](http://phaser.io/) for writing the game. It has physics libraries included, there are tons of tutorials and it's just a good tool to for building HTML games. Upvotes: 0 <issue_comment>username_2: You're on the right track, but the pieces are not arranged correctly. Divide the character control in two phases: movement calculation, and animation. Think in kinematics: The character's next position is driven by its actual position vector and its current velocity vector. In the first phase, movement calculation, you alter only the velocity. Left/right modify the horizontal component of the speed, and the jump and gravity modify the vertical component. You want full air control, so both are independent (otherwise, altering the horizontal velocity manipulation would be conditioned by the vertical position, i.e., not jumping/falling). Ignore inertia for the moment (I think that's a better name than friction IMHO). The horizontal velocity `velX` is either `maxVelX`, `-maxVelX`, or `0`, depending on whether right, left, or none/both are pressed. The vertical velocity `velY` is `0` if y is below or exactly a given value (i.e., the floor); when on the floor, pressing jump will set `velY` to `velJump`, and you decrease this value a certain amount every frame (i.e., gravity. Remember that it's an acceleration, i.e., velocity over time). When the character's `y` is below the floor level, you set `velY` to `0` and `y` to the floor level. Once you have the movement calculated, you apply it to the position (i.e., animate it): `x += velX; y += velY;` This is the second phase of the character control. Once you have this running, you can add inertia. Horizontal velocity is increased/decreased every frame until its "target" velocity is reached. I'd remove the vertical inertia/movement dampening unless you want your player to get stuck on the air or fall like a feather. However, it's usually a good idea to limit the falling speed to a hard limit if there's a lot of verticality in your game. This is, of course, an over-simplistic approach to physics (common in most platforming/arcade games). For realistic or more elaborate approaches, I'd consider a 2D physics engine and using forces instead of just velocities. Upvotes: 2 [selected_answer]
2018/03/21
1,310
5,241
<issue_start>username_0: Background ---------- I have made a PHP script that sends an email to many users by looping through the users' ID via POST. When I try using the script with a lot of users (1000+), the script times out. To resolve this, I decided to use AJAX on the front end that sends each request individually. I have set up a simple sample page to test my code. The PHP script delays for five seconds. I would expect to get a request per five seconds. However, I am getting a delay of five seconds, and then all of the responses at once. With more research, I discovered that my AJAX calls are chaining, which is not what I want. Rather, I would only like to send the next request when the last AJAX call was completed. Code ---- ### HTML ``` 1 2 3 4 5 6 7 8 9 ``` ### Javascript Code ``` $("#btnAjax").click(function() { var options = $("#frmAjax input:checkbox:checked"); $(options).each(function(i) { var postData = {option: $(options[i]).val()}; $.ajax({ type: "POST", data: postData, url: "run_ajax.php", success: function(result) { console.log(result); }, statusCode: { 500: function() { console.log("Error"); } } }); }); }); ``` ### PHP Code ``` echo("Success on ".$_POST["option"]."."); sleep(5); ? ``` Question -------- My question is this, how can I make my AJAX calls recursive, not sending the next request until the previous has finished?<issue_comment>username_1: You can use your `success` function and call the next `ajax` request like something like this: ``` let optionsLength = 0; let optionsCount = 0; $("#btnAjax").click(function() { optionsLength = $("#frmAjax input:checkbox:checked").length; callAjax(); }); function callAjax() { let postData = {option: $(options[optionsLength-optionsCount]).val()}; $.ajax({ type: "POST", data: postData, url: "run_ajax.php", success: function(result) { optionsCount = optionsCount + 1; callAjax(); }, statusCode: { 500: function() { console.log("Error"); } } }); } ``` this is somewhat pseudo code, you will probably have to tweak it but it should give you a good idea I hope.. Upvotes: 1 <issue_comment>username_2: Try with this one, you were not so far anyway ;) ``` function sendMail($options){ if (!$options.length) return; $.ajax({ type: "POST", url: "run_ajax.php", data: {option:$options.eq(0).val()}, success: function(result){ console.log(result) }, statusCode: { 500: function(){ console.log("Error") } } }).always(function(){ sendMail($options.slice(1)) }); } $("#btnAjax").on('click',function(e){ e.preventDefault(); sendMail($("#frmAjax input:checkbox:checked")); }); ``` Upvotes: 4 [selected_answer]<issue_comment>username_3: Some points to help I hope : * For your PHP script timeout, you can venture into `set_time_limit(0)` for endless script running. * For your responses that seems simultaneous. Your PHP is probably multi-threaded, so it will treat each request in parallel and, therefore, you'll receive each response 5s after each request have been sent. The solution is, as you're pointing, to delay each request sending. For your case, simply create a queue but better use complete callback if you don't want the process to stop at the first error : ``` $("#btnAjax").click(function() { function process(i) { $.ajax({ type: "POST", data: queue[i], url: "run_ajax.php", success: function(result) { console.log(result); }, statusCode: { 500: function() { console.log("Error"); } }, complete: { if(i++ < (queue.length - 1) process(i); } }); } var queue = []; var options = $("#frmAjax input:checkbox:checked"); $(options).each(function(i) queue.push({option: $(options[i]).val()}); process(0); }); ``` Upvotes: 0 <issue_comment>username_4: This is what I mean by pass all your data about what is checked in one request. Pass the whole form. The overhead you introduce sending one value at a time makes no sense. ``` $("#btnAjax").click(function() { var myform = document.getElementById("frmAjax"); var fd = new FormData(myform); $.ajax({ type: "POST", data: fd, url: "run_ajax.php", success: function(result) { console.log(result); }, statusCode: { 500: function() { console.log("Error"); } } }); }); ``` Your server side code then of course needs to handle iterating over the set of data. If you need to know the individual outcomes of what transpires on the server then have your `rux_ajax.php` script return JSON with that detail. Upvotes: 0
2018/03/21
1,329
5,193
<issue_start>username_0: I have the following action creator: ``` export function selectBook(ISBN, dispatch) { const url = `${ROOT_ITEMS_URL}/${ISBN}?all=true`; dispatch({ type: 'SELECT_BOOK_LOADING', isLoading:true }); axios.get(url) .then(({ data }) => dispatch({ type: 'SELECT_BOOK_SUCCESS', data})) .catch(( err ) => dispatch({ type: 'SELECT_BOOK_FAILURE', isLoading:false})) } ``` I also have the following in my main index file for my project: ``` import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import LoginLayout from './layouts/LoginLayout'; import reducers from './reducers'; import ReduxPromise from 'redux-promise'; import reduxThunk from 'redux-thunk'; const createStoreWithMiddleware = applyMiddleware(ReduxPromise, reduxThunk)(createStore); //const createStoreWithMiddleware = applyMiddleware()(createStore); ReactDOM.render( , document.querySelector('.root')); ``` I am confused on how to get dispatch called into my project. I am getting the following error: > > bundle.js:5690 Uncaught TypeError: dispatch is not a function > > > When I call this function I am not passing any dispatch. But I am not sure how to call dispatch into it. Is it a redux call I need to make with my function call? ``` this.props.selectBook(params.bookID); ``` Should it be this instead?: ``` this.props.selectBook(params.bookID, dispatch); ``` and what import is dispatch with? import dispatch from 'redux'?<issue_comment>username_1: You can use your `success` function and call the next `ajax` request like something like this: ``` let optionsLength = 0; let optionsCount = 0; $("#btnAjax").click(function() { optionsLength = $("#frmAjax input:checkbox:checked").length; callAjax(); }); function callAjax() { let postData = {option: $(options[optionsLength-optionsCount]).val()}; $.ajax({ type: "POST", data: postData, url: "run_ajax.php", success: function(result) { optionsCount = optionsCount + 1; callAjax(); }, statusCode: { 500: function() { console.log("Error"); } } }); } ``` this is somewhat pseudo code, you will probably have to tweak it but it should give you a good idea I hope.. Upvotes: 1 <issue_comment>username_2: Try with this one, you were not so far anyway ;) ``` function sendMail($options){ if (!$options.length) return; $.ajax({ type: "POST", url: "run_ajax.php", data: {option:$options.eq(0).val()}, success: function(result){ console.log(result) }, statusCode: { 500: function(){ console.log("Error") } } }).always(function(){ sendMail($options.slice(1)) }); } $("#btnAjax").on('click',function(e){ e.preventDefault(); sendMail($("#frmAjax input:checkbox:checked")); }); ``` Upvotes: 4 [selected_answer]<issue_comment>username_3: Some points to help I hope : * For your PHP script timeout, you can venture into `set_time_limit(0)` for endless script running. * For your responses that seems simultaneous. Your PHP is probably multi-threaded, so it will treat each request in parallel and, therefore, you'll receive each response 5s after each request have been sent. The solution is, as you're pointing, to delay each request sending. For your case, simply create a queue but better use complete callback if you don't want the process to stop at the first error : ``` $("#btnAjax").click(function() { function process(i) { $.ajax({ type: "POST", data: queue[i], url: "run_ajax.php", success: function(result) { console.log(result); }, statusCode: { 500: function() { console.log("Error"); } }, complete: { if(i++ < (queue.length - 1) process(i); } }); } var queue = []; var options = $("#frmAjax input:checkbox:checked"); $(options).each(function(i) queue.push({option: $(options[i]).val()}); process(0); }); ``` Upvotes: 0 <issue_comment>username_4: This is what I mean by pass all your data about what is checked in one request. Pass the whole form. The overhead you introduce sending one value at a time makes no sense. ``` $("#btnAjax").click(function() { var myform = document.getElementById("frmAjax"); var fd = new FormData(myform); $.ajax({ type: "POST", data: fd, url: "run_ajax.php", success: function(result) { console.log(result); }, statusCode: { 500: function() { console.log("Error"); } } }); }); ``` Your server side code then of course needs to handle iterating over the set of data. If you need to know the individual outcomes of what transpires on the server then have your `rux_ajax.php` script return JSON with that detail. Upvotes: 0
2018/03/21
1,242
5,141
<issue_start>username_0: in my application, I used place picker.and data that place picker gave is sent to 3 different activities using shared preference.and show this data in TextView.problem is when I closed activity and again open that activity my data still visible in TextView.even when I cleared it in `onDestroy()`. **here is my code for send data from place picker:** ``` SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString("city_address", (String) cityAddress); editor.putString("city_name", (String) city); editor.commit(); Intent intent = new Intent(this, CleanlinessActivity.class); startActivity(intent); ``` **set data using this code in onCreate() of CleanlinessActivity** ``` SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE); String n = settings.getString("city_name", "Enter Location"); String a = settings.getString("city_address", ""); cityname.setText(n); cetlocation.setText(a); ``` **and i cleared data using this code in CleanlinessActivity** ``` @Override protected void onDestroy() { super.onDestroy(); SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.remove("city_address"); editor.clear().commit(); } ```<issue_comment>username_1: You can use your `success` function and call the next `ajax` request like something like this: ``` let optionsLength = 0; let optionsCount = 0; $("#btnAjax").click(function() { optionsLength = $("#frmAjax input:checkbox:checked").length; callAjax(); }); function callAjax() { let postData = {option: $(options[optionsLength-optionsCount]).val()}; $.ajax({ type: "POST", data: postData, url: "run_ajax.php", success: function(result) { optionsCount = optionsCount + 1; callAjax(); }, statusCode: { 500: function() { console.log("Error"); } } }); } ``` this is somewhat pseudo code, you will probably have to tweak it but it should give you a good idea I hope.. Upvotes: 1 <issue_comment>username_2: Try with this one, you were not so far anyway ;) ``` function sendMail($options){ if (!$options.length) return; $.ajax({ type: "POST", url: "run_ajax.php", data: {option:$options.eq(0).val()}, success: function(result){ console.log(result) }, statusCode: { 500: function(){ console.log("Error") } } }).always(function(){ sendMail($options.slice(1)) }); } $("#btnAjax").on('click',function(e){ e.preventDefault(); sendMail($("#frmAjax input:checkbox:checked")); }); ``` Upvotes: 4 [selected_answer]<issue_comment>username_3: Some points to help I hope : * For your PHP script timeout, you can venture into `set_time_limit(0)` for endless script running. * For your responses that seems simultaneous. Your PHP is probably multi-threaded, so it will treat each request in parallel and, therefore, you'll receive each response 5s after each request have been sent. The solution is, as you're pointing, to delay each request sending. For your case, simply create a queue but better use complete callback if you don't want the process to stop at the first error : ``` $("#btnAjax").click(function() { function process(i) { $.ajax({ type: "POST", data: queue[i], url: "run_ajax.php", success: function(result) { console.log(result); }, statusCode: { 500: function() { console.log("Error"); } }, complete: { if(i++ < (queue.length - 1) process(i); } }); } var queue = []; var options = $("#frmAjax input:checkbox:checked"); $(options).each(function(i) queue.push({option: $(options[i]).val()}); process(0); }); ``` Upvotes: 0 <issue_comment>username_4: This is what I mean by pass all your data about what is checked in one request. Pass the whole form. The overhead you introduce sending one value at a time makes no sense. ``` $("#btnAjax").click(function() { var myform = document.getElementById("frmAjax"); var fd = new FormData(myform); $.ajax({ type: "POST", data: fd, url: "run_ajax.php", success: function(result) { console.log(result); }, statusCode: { 500: function() { console.log("Error"); } } }); }); ``` Your server side code then of course needs to handle iterating over the set of data. If you need to know the individual outcomes of what transpires on the server then have your `rux_ajax.php` script return JSON with that detail. Upvotes: 0
2018/03/21
782
2,713
<issue_start>username_0: I would like to have a form that enables a user to choose the vehicles. The user should get the total price of his choice. I wrote this little script, and it works properly. I am just curious is there a better way to do it. For example, there are a lot of IFs in foreach loop. What if I have, for instance, 100 checkboxes. Should I automate that in a way that for every new type of vehicle the script should make new IF statement? That sounds awkward. Is there a way to put a number of prices directly in checkbox form or something? However, what would be the best way to do such a thing. Thanx. ``` if (isset($_POST['submit'])){ $automobils=$_POST['auto']; $set= array(); echo "You ordered: " ; foreach ($automobils as $model){ if ($model == "chevrolet"){ $set[]=20000; } if ($model == "reno"){ $set[]=15000; } if ($model == "punto"){ $set[]=10000; } echo "*$model* "; } $sum = array_sum($set); echo " Whole price is $sum $"; } ?> Chevrolet Reno Punto ```<issue_comment>username_1: If you want to put number in checkbox. You can put it with value by using some special separator. For example ``` Punto ``` Later you can use Explode string and can get value for selected. Upvotes: -1 <issue_comment>username_2: Well without adding a database and a whole another level of fun programming. You can do this with an explode command (And really shrinks your foreach as well) on the input value ``` value="chevrolet" ``` Change to something like ``` value="chevrolet;20000" ``` then in your foreach loop ``` foreach ($automobils as $model){ $eachmodel = explode(";",$model); $set[] = $eachmodel[1]; } ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: Ideally you'd store your possible values, and their corresponding prices, in a database, rather than in your code. But here's a quick solution, involving an associative array acting as a map between each vehicle and its price. ``` $map = [ 'chevrolet' => 20000, 'reno' => 15000, 'punto' => 10000 ]; if (!empty($_POST['auto']) { echo 'You ordered: '; $total = 0; foreach($_POST['auto'] as $model) if (array_key_exists($model, $map)) { echo ' - '.$model.' '; $total += $map[$model]; } echo 'Total price: '.$total.' '; } ``` Then, you just update the map as you add/change vehicles/prices etc. Note it's key to store the allowed values/prices code-side (or in a DB) rather than in your form as the latter is editable via the DOM, so you'd need something server-side to validate it anyway. Upvotes: 1
2018/03/21
773
2,695
<issue_start>username_0: Can anybody tell me why the command ``` find . -type d | wc -l ``` shows one directory more than the actual number of directories? The command is supposed to print number of directories and subdirectories, from the directory I am standing. The command ``` ls -lR | grep ^d | wc -l ``` does the same thing, but in this case I get the correct number. Same case when I use `f` or - (file) instead. It just adds one more directory/file.<issue_comment>username_1: It counts the current directory as well. If you want to eliminate that you can set the mindepth variable to 1. ``` $ find . -mindepth 1 -type d | wc -l ``` will only give the count of child directories... Upvotes: 1 <issue_comment>username_2: There are two possible sources of error: * The current directory itself * Directories with literal newlines in their names --- ### GNU find (with `-printf`) To eliminate both, when using GNU find: ``` find . -mindepth 1 -type d -printf '\n' | wc -l ``` * Putting `-mindepth 1` prevents the named argument (`.`) from matching. * Using `-printf '\n'` instead of the default `-print` action ensures that the name itself can't change how a file is counted. --- ### GNU *or* BSD find (with `-print0`) With modern BSD `find` (as on MacOS), you may not have `-printf` but still will have `-print0`. Thus, for code compatible with both major implementations: ``` find . -mindepth 1 -type d -print0 | tr -cd '\0' | wc -c ``` `tr -cd '\0'` removes all characters other than NULs; `wc -c` counts characters remaining in the stream -- thus, counting the remaining NUL delimiters, thus counting files. (A NUL is the only character safe for this use, as it isn't permitted to exist in a path). --- ### POSIX find (with `-exec`) If you don't have `-printf` or `-print0`, you can still delegate the job of printing something safe (like the number of arguments) to a shell: ``` find . -mindepth 1 -type d -exec sh -c 'echo "$#"' _ {} + | paste -sd+ - | bc ``` Upvotes: 2 <issue_comment>username_3: Don't print the dirname, but a dot. If you don't collect dirs with linebreaks, like most of us, piping to wc -l is of course the easy solution - you just need to know when to abstain from it. ``` concat=$(find . -mindepth 1 -type d -printf ".") echo ${#concat} 66 ``` Upvotes: -1 <issue_comment>username_4: `find` also finds the current directory `.`. You may also have other directories beginning with `.`, e.g. `.config`. To recursively count all directories, including those beginning with `.`: ``` find * .* -type d | wc -l ``` To recursively count all directories, but exclude those beginning with `.`: ``` find * -type d | wc -l ``` Upvotes: -1
2018/03/21
1,242
4,105
<issue_start>username_0: From [Catch2's example](https://github.com/catchorg/Catch2/blob/master/docs/tutorial.md#writing-tests), I tried to run this example with `cmake` where structure of my project is like this: ``` /factorial +-- CMakeLists.txt +-- /bin +-- /include | +-- catch.hpp | +-- fact.hpp +-- /src | +-- CMakeLists.txt | +-- fact.cpp +-- /test +-- CMakeLists.txt +-- test_fact.cpp ``` `fact.cpp`: ``` unsigned int factorial( unsigned int number ) { return number <= 1 ? number : factorial(number-1)*number; } ``` `fact.hpp`: ``` #ifndef FACT_H #define FACT_H unsigned int factorial(unsigned int); #endif ``` `test_fact.cpp`: ``` #define CATCH_CONFIG_MAIN #include "catch.hpp" #include "fact.hpp" TEST_CASE( "factorials are computed", "[factorial]" ) { REQUIRE( factorial(1) == 1 ); REQUIRE( factorial(2) == 2 ); REQUIRE( factorial(3) == 6 ); REQUIRE( factorial(10) == 3628800 ); } ``` I tried several ways already to build this project with `cmake` but it's failed. Sometimes I got an error: ``` cpp:X:XX: fatal error: 'fact.hpp' file not found ... ``` and sometimes I got: ``` Undefined symbols for architecture x86_64: "_main", referenced from: ... ``` when I run `make`. What should I have in `factorial/CMakeLists.txt`,`factorial/src/CMakeLists.txt` and `factorial/test/CMakeLists.txt`, if I want to have my execution files in `factorial/bin`? Additional: This is my CMakeLists.txts (I think they are completely wrong). `factorial/CMakeLists.txt`: ``` project(factorial) cmake_minimum_required(VERSION 2.8.12) add_definitions("-std=c++11") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin) add_subdirectory(src) add_subdirectory(test) ``` `factorial/src/CMakeLists.txt`: ``` project(factorial) cmake_minimum_required(VERSION 2.8.12) add_executable(fact fact.cpp) ``` `factorial/test/CMakeLists.txt`: ``` project(factorial) cmake_minimum_required(VERSION 2.8.12) add_executable(test_fact test_fact.cpp) target_include_directories(test_fact PRIVATE ${CMAKE_SOURCE_DIR}/include) ```<issue_comment>username_1: If you look at the CMake documentation, the `PROJECT_SOURCE_DIR` variable is define as that: > > Top level source directory for the current project. > > > This is the source directory of the most recent project() command. > > > Since you called `project` many times, that variable will constantly change. I would suggest you to remove your project directive, or to use `CMAKE_SOURCE_DIR`, which always point to the source directory of the whole project. --- As a side note, I suggest to use `set(CMAKE_CXX_STANDARD 11)` instead of `add_definition` Upvotes: 3 <issue_comment>username_2: Many problems here: ``` add_executable(fact fact.cpp) ``` The call should be using `add_library` (You could also specify `STATIC` or `SHARED`), since you are only defining a factorial function, not an executable *with a `main` function*. ``` add_executable(fact fact.cpp) ``` The file should be `test_fact.cpp` and the target should have a different name to avoid conflict with the previous library you created. Also, your `fact.cpp` doesn't include `fact.hpp`. Last but not least, instead of doing `target_include_directories`, just write the following in your top-level `CMakeLists.txt`: ``` include_directories(include) ``` Now, all subdirectories should be able to access the header files. Beware that this removes control of the scoping of the header files (`PRIVATE` vs `PUBLIC` vs `INTERFACE`) and allows *all* subdirectories to access the header files. If you want to restrict this behavior, then use `target_include_direcories` for all targets (Your library and the test executable). For this example, since everything needs to access the header files, there is no problem with the statement above. More problems: ``` project(factorial) cmake_minimum_required(VERSION 2.8.12) ``` Either switch the order of these statements, or remove both of them. (You only need them in your top level CMake file) Upvotes: 4 [selected_answer]