date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/18
283
893
<issue_start>username_0: Is there a simple regular expression that would insert a character, say a colon :, every n characters, say 2, from right to left in a string? For example... 059 -> 0:59 14598 -> 1:45:98 340001 -> 34:00:01<issue_comment>username_1: If your environment is supporting [lookarounds](https://www.regular-expressions.info/lookaround.html), you can use a lookahead to check for one or more of any two characters ahead until `$` end of line at any place between character (use `\B` a non [word boundary](https://www.regular-expressions.info/wordboundaries.html) to trigger the lookahead only between word characters) and replace with colon. ``` \B(?=(?:..)+$) ``` [See demo at regex101](https://regex101.com/r/jf2zDT/1) Upvotes: 2 [selected_answer]<issue_comment>username_2: Simply use a "2\*N arbitrary characters" lookahead: ``` s/(?=(?:.{2})+$)/:/g ``` Upvotes: 0
2018/03/18
1,063
4,366
<issue_start>username_0: I am trying to determine what the difference is between a changestream: <https://docs.mongodb.com/manual/changeStreams> <https://docs.mongodb.com/manual/reference/method/db.collection.watch/> which looks like so: ``` const changeStream = collection.watch(); changeStream.next(function(err, next) { expect(err).to.equal(null); client.close(); done(); }); ``` and a tailable cursor: <https://docs.mongodb.com/manual/core/tailable-cursors/> which looks like so: ``` const cursor = coll.find(self.query || query) .addCursorFlag('tailable', true) .addCursorFlag('awaitData', true) // true or false? .addCursorFlag('noCursorTimeout', true) .addCursorFlag('oplogReplay', true) .setCursorOption('numberOfRetries', Number.MAX_VALUE) .setCursorOption('tailableRetryInterval', 200); const strm = cursor.stream(); // Node.js transform stream ``` do they have a different use case? when would it be good to use one over the other?<issue_comment>username_1: With tailable cursor, you follow ALL changes to all collections. With changeStream, you see only changes to the selected collection. Much less traffic and more reliable. Upvotes: 2 <issue_comment>username_2: [Change Streams](https://docs.mongodb.com/manual/changeStreams) (available in MongoDB v3.6+) is a feature that allows you to access real-time data changes without the complexity and risk of tailing the [oplog](https://docs.mongodb.com/manual/reference/glossary/#term-oplog). Key benefits of change streams *over* tailing the oplog are: 1. Utilise the built-in [MongoDB Role-Based Access Control](https://docs.mongodb.com/manual/core/authorization/). Applications can only open change streams against collections they have *read* access to. Refined and specific authorisation. 2. Provide a well defined API that are reliable. The [change events](https://docs.mongodb.com/manual/reference/change-events/) output that are returned by change streams are well documented. Also, all of the [official MongoDB drivers](https://docs.mongodb.com/ecosystem/drivers/) follow the same [specifications](https://github.com/mongodb/specifications/blob/master/source/change-streams.rst) when implementing change streams interface. 3. Change events that are returned as part of change streams are at least committed to the majority of the replica set. This means the change events that are sent to the client are durable. Applications don't need to handle data rollback in the event of failover. 4. Provide a total ordering of changes across shards by utilising a global logical clock. MongoDB guarantees the order of changes are preserved and change events can be safely interpreted in the order received. For example, a change stream cursor opened against a 3-shard sharded cluster returns change events respecting the total order of those changes across all three shards. 5. Due to the ordering characteristic, change streams are also inherently resumable. The `_id` of [change event output](https://docs.mongodb.com/manual/reference/change-events/#change-stream-output) is a resume token. MongoDB official drivers automatically cache this resume token, and in the case of network transient error the driver will retry once. Additionally, applications can also resume manually by utilising parameter `resume_after`. See also [Resume a Change Stream](https://docs.mongodb.com/manual/changeStreams/#resume-a-change-stream). 6. Utilise [MongoDB aggregation pipeline](https://docs.mongodb.com/manual/core/aggregation-pipeline/). Applications can modify the change events output. Currently there are five pipeline stages available to modify the event output. For example, change event outputs can be filtered out (server side) before being sent out using [$match stage](https://docs.mongodb.com/manual/reference/operator/aggregation/match/#pipe._S_match). See [Modify Change Stream Output](https://docs.mongodb.com/manual/changeStreams/#modify-change-stream-output) for more information. > > when would it be good to use one over the other? > > > If your MongoDB deployment is version 3.6+, I would recommend to utilise MongoDB Change Streams over tailing the oplog. You may also find [Change Streams Production Recommendations](https://docs.mongodb.com/manual/administration/change-streams-production-recommendations/) a useful resource. Upvotes: 5 [selected_answer]
2018/03/18
562
2,008
<issue_start>username_0: ``` function addProperty(object, property) { // add the property to the object with a value of null // return the object // note: the property name is NOT 'property'. The name is the value of the argument called property (a string) } ``` I got a little stuck on an only home work question. I think I understand what its asking me to do. I want to pass in an object and add a new property and set its default value to null. Here is what I have tried doing ``` function addProperty(object, property) { // add the property to the object with a value of null // return the object // note: the property name is NOT 'property'. The name is the value object.property = property; object[property] = null; return object; } ``` This does not seem to be working the way I need it to as I believe I the object should produce something like ``` const object = { propertyPassedIn: null, }; ``` can anyone help or point me in the right direction?<issue_comment>username_1: This works for me ``` function addProperty(object, property) { // add the property to the object with a value of null // return the object // note: the property name is NOT 'property'. The name is the value // object.property = property; object[property] = null; return object; } var obj = {x:1,y:null}; // undefined obj // {x: 1, y: null} addProperty(obj, 'z'); // {x: 1, y: null, z: null} ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Just remove ``` object.property = property; ``` from your sample. This line would create a **ReferenceError** if the property is not already in the object. Other than that, I can't see a reason why it wouldn't do what you say you expect. Upvotes: 1 <issue_comment>username_3: ``` function addProperty(object, property) { object[property] = null; return object; } var obj = { key1:1, key2:2 }; addProperty(obj, 'value'); this will give below result {key1:1, key2:2, value:null} ``` Upvotes: 0
2018/03/18
440
1,520
<issue_start>username_0: I'm reading lines from a file and I might have a comment anywhere throughout it of any size. ``` while (fgets(line, 100, myFile)) { // skip and print comment if (line[0] == '#') printf("Comment is = %s", line); else {...} } ``` The code is doing what is supposed to until it gets a comment which is over 100 characters. In that case it will not detect the `#` anymore and it won't skip it. How can I solve this?<issue_comment>username_1: This works for me ``` function addProperty(object, property) { // add the property to the object with a value of null // return the object // note: the property name is NOT 'property'. The name is the value // object.property = property; object[property] = null; return object; } var obj = {x:1,y:null}; // undefined obj // {x: 1, y: null} addProperty(obj, 'z'); // {x: 1, y: null, z: null} ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Just remove ``` object.property = property; ``` from your sample. This line would create a **ReferenceError** if the property is not already in the object. Other than that, I can't see a reason why it wouldn't do what you say you expect. Upvotes: 1 <issue_comment>username_3: ``` function addProperty(object, property) { object[property] = null; return object; } var obj = { key1:1, key2:2 }; addProperty(obj, 'value'); this will give below result {key1:1, key2:2, value:null} ``` Upvotes: 0
2018/03/18
788
3,150
<issue_start>username_0: I've been running through a few tutorials for Java, they all say to make a new variable when calling classes. Why is this? I've tested some code and it works without doing this. I've been using python for quite a while now so I'm used to using a dynamic language. Please see some code I've been playing around with below: ``` import java.util.Scanner; class MyClass { static String myName(String name) { return ("Your name is: "+name); } static String myAge(Integer age){ return ("Your age is: "+age); } static String myGender(String gender){ return ("You are: "+gender); } } class Test{ public static void main(String [ ] args){ Scanner ui = new Scanner(System.in); MyClass user = new MyClass(); //Output with new variable of class - user String input = ui.next(); String newname = user.myName(input); System.out.println(newname); //Output calling class directly Integer input1 = ui.nextInt(); String newage = MyClass.myAge(input1); System.out.println(newage); //Output with new variable of class - user String input2 = ui.next(); String newgender = MyClass.myGender(input2); System.out.println(newgender); } } ``` Thanks for your time.<issue_comment>username_1: If everything in the class is `static` (as in the code you posted), then there's no need to create instances of the class. However, if the class were to have instance fields and/or methods, then the story is different. For instance, consider a class like this: ``` class Person { private String name; private int age; private String gender; public Person(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } String myName() { return "Your name is: " + name; } String myAge() { return "Your age is: " + age; } String myGender() { return "You are: " + gender; } } ``` Then you could create several `Person` instances with different internal state and use them interchangeably in your code: ``` public static void main(String[] args) { Person jim = new Person("Jim", 40, "male"); Person sally = new Person("Sally", 12, "female"); report(jim); report(sally); } private static report(Person person) { System.out.println(person.myName()); System.out.println(person.myAge()); System.out.println(person.myGender()); } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: If we create any member with static keyword it get memory at once to all objects, static keyword we used when we have common properties in class and we don't want to create separate memory to all instances objects ... it doesn't need to create instance variable to call it and this static block is shareable to to all objects.... for example if we have Animal class and we want to describe 5 different type of dog's ... than we don't define color, size like properties as static ... because they all have their own different size and color.... I hope you get it Upvotes: 0
2018/03/18
829
3,054
<issue_start>username_0: Let's say I have 4 apps, "Uber Clone" for iOS and Android and "Uber Driver Clone" for iOS and Android. I am using the same Firebase project for all 4 since they share the same database. When it comes to Facebook Auth though, I can only add a single Facebook app to Firebase. And for every Facebook App I can only add a single iOS and a single Android app. Therefore how can I make this work? Firebasers, any recommendation/solution in mind?<issue_comment>username_1: A single Facebook App is allowed to connect to multiple iOS apps and multiple Android apps. For iOS apps, you can specify multiple `Bundle ID` at Facebook App settings page. Upvotes: 2 <issue_comment>username_2: Taken you're using Firebase for authentication, I presume you're using either Real Time Database or Cloud Firestore to store user data as well. In your user data model, you can add user types. For example, ``` user_type : "driver" ``` Then query users like so: ``` DBreference.collection("users").whereField("user_type", isEqualTo: "driver").getDocuments() {(querySnapshot, error) in if error != nil { print(error.debugDescription) return } else if let users = querySnapshot.documents { for user in users { guard let userType = user.data()["user_type"] as? String else { return } print(userType) } } } ``` This way you don't have to create multiple Facebook apps. Just use the one you have and segment users and their priviliges accordingly. For example, upon login on both apps, do a check, whether the is user trying to log in as a driver or a passenger. ``` if currentUser.userType != "passenger" { print("You can't log into the passanger app with your driver's account.") } ``` Hope this helps. Upvotes: 2 <issue_comment>username_3: Multiple apps on a single Facebook app ====================================== 1. Go to your Facebook developer console 2. Go to your app's page 3. Go to the basic settings [![enter image description here](https://i.stack.imgur.com/ziArB.png)](https://i.stack.imgur.com/ziArB.png) 4. Add all relevant bundle IDs 5. ***Here's the key: Add a different URL Scheme suffix for each app. This differentiates each iOS app under your single Facebook App.*** [![enter image description here](https://i.stack.imgur.com/o5EBz.png)](https://i.stack.imgur.com/o5EBz.png) 6. In each of your apps info.plist add the suffix information (Make sure both the URL scheme is updated and the "FacebookURLSchemeSuffix" is added!) [![enter image description here](https://i.stack.imgur.com/fP0k0.png)](https://i.stack.imgur.com/fP0k0.png) 7. Now each of your apps is under the same Facebook App, and thus can register under the same Firebase Realtime Database. Check this out for more info: [Two iOS apps using the same Facebook app ID - is it possible?](https://stackoverflow.com/questions/5993996/two-ios-apps-using-the-same-facebook-app-id-is-it-possible) At this point in time, it does not seem possible to have multiple FB apps under a single Firebase Realtime Database. Upvotes: 4 [selected_answer]
2018/03/18
835
3,094
<issue_start>username_0: ``` int filter(int m, int readfd, int writefd) ``` I have a function named filter that takes three arguments: the filter value m, a file descriptor readfd from which integers are received, and a file descriptor writefd to which integers are written. Its purpose is to remove (filter) any integers from the data stream that are multiples of m. The function returns 0 if it completes without encountering an error and 1 otherwise. How do I make a file descriptor for input `readfd`?<issue_comment>username_1: A single Facebook App is allowed to connect to multiple iOS apps and multiple Android apps. For iOS apps, you can specify multiple `Bundle ID` at Facebook App settings page. Upvotes: 2 <issue_comment>username_2: Taken you're using Firebase for authentication, I presume you're using either Real Time Database or Cloud Firestore to store user data as well. In your user data model, you can add user types. For example, ``` user_type : "driver" ``` Then query users like so: ``` DBreference.collection("users").whereField("user_type", isEqualTo: "driver").getDocuments() {(querySnapshot, error) in if error != nil { print(error.debugDescription) return } else if let users = querySnapshot.documents { for user in users { guard let userType = user.data()["user_type"] as? String else { return } print(userType) } } } ``` This way you don't have to create multiple Facebook apps. Just use the one you have and segment users and their priviliges accordingly. For example, upon login on both apps, do a check, whether the is user trying to log in as a driver or a passenger. ``` if currentUser.userType != "passenger" { print("You can't log into the passanger app with your driver's account.") } ``` Hope this helps. Upvotes: 2 <issue_comment>username_3: Multiple apps on a single Facebook app ====================================== 1. Go to your Facebook developer console 2. Go to your app's page 3. Go to the basic settings [![enter image description here](https://i.stack.imgur.com/ziArB.png)](https://i.stack.imgur.com/ziArB.png) 4. Add all relevant bundle IDs 5. ***Here's the key: Add a different URL Scheme suffix for each app. This differentiates each iOS app under your single Facebook App.*** [![enter image description here](https://i.stack.imgur.com/o5EBz.png)](https://i.stack.imgur.com/o5EBz.png) 6. In each of your apps info.plist add the suffix information (Make sure both the URL scheme is updated and the "FacebookURLSchemeSuffix" is added!) [![enter image description here](https://i.stack.imgur.com/fP0k0.png)](https://i.stack.imgur.com/fP0k0.png) 7. Now each of your apps is under the same Facebook App, and thus can register under the same Firebase Realtime Database. Check this out for more info: [Two iOS apps using the same Facebook app ID - is it possible?](https://stackoverflow.com/questions/5993996/two-ios-apps-using-the-same-facebook-app-id-is-it-possible) At this point in time, it does not seem possible to have multiple FB apps under a single Firebase Realtime Database. Upvotes: 4 [selected_answer]
2018/03/18
959
3,550
<issue_start>username_0: Some websites detect my operating system architecture automatically and I don't know how they get the value (eg. 32-bit / 64-bit OS). So they can use the value for the following case: Example of the case: If I want to download something for Example 'Google Chrome', the Google Chrome Download Page thinks that I'm using 64bit operating system and thus it downloads 'ChromeStandalone64.exe for me. If I want to download the 32bit, I need to be on the 32bit OS OR I need to click on the other platform. This is just a use case example. So in general, my question is how do I trick the browser (using any scripting language) that I use 32bit OS ? I know there is a chrome plugin that disguises the Chrome browser as different browser like Safari, Internet explorer. it works. but what about tricking the browser as 64bit or 32bit? Edit: Please do not give me the answer how to download a Google Chrome. I just gave an example of the case.<issue_comment>username_1: A single Facebook App is allowed to connect to multiple iOS apps and multiple Android apps. For iOS apps, you can specify multiple `Bundle ID` at Facebook App settings page. Upvotes: 2 <issue_comment>username_2: Taken you're using Firebase for authentication, I presume you're using either Real Time Database or Cloud Firestore to store user data as well. In your user data model, you can add user types. For example, ``` user_type : "driver" ``` Then query users like so: ``` DBreference.collection("users").whereField("user_type", isEqualTo: "driver").getDocuments() {(querySnapshot, error) in if error != nil { print(error.debugDescription) return } else if let users = querySnapshot.documents { for user in users { guard let userType = user.data()["user_type"] as? String else { return } print(userType) } } } ``` This way you don't have to create multiple Facebook apps. Just use the one you have and segment users and their priviliges accordingly. For example, upon login on both apps, do a check, whether the is user trying to log in as a driver or a passenger. ``` if currentUser.userType != "passenger" { print("You can't log into the passanger app with your driver's account.") } ``` Hope this helps. Upvotes: 2 <issue_comment>username_3: Multiple apps on a single Facebook app ====================================== 1. Go to your Facebook developer console 2. Go to your app's page 3. Go to the basic settings [![enter image description here](https://i.stack.imgur.com/ziArB.png)](https://i.stack.imgur.com/ziArB.png) 4. Add all relevant bundle IDs 5. ***Here's the key: Add a different URL Scheme suffix for each app. This differentiates each iOS app under your single Facebook App.*** [![enter image description here](https://i.stack.imgur.com/o5EBz.png)](https://i.stack.imgur.com/o5EBz.png) 6. In each of your apps info.plist add the suffix information (Make sure both the URL scheme is updated and the "FacebookURLSchemeSuffix" is added!) [![enter image description here](https://i.stack.imgur.com/fP0k0.png)](https://i.stack.imgur.com/fP0k0.png) 7. Now each of your apps is under the same Facebook App, and thus can register under the same Firebase Realtime Database. Check this out for more info: [Two iOS apps using the same Facebook app ID - is it possible?](https://stackoverflow.com/questions/5993996/two-ios-apps-using-the-same-facebook-app-id-is-it-possible) At this point in time, it does not seem possible to have multiple FB apps under a single Firebase Realtime Database. Upvotes: 4 [selected_answer]
2018/03/18
1,013
3,637
<issue_start>username_0: I have nodejs code running inside a pod. From inside the pod I want to find the zone of the node where this pod is running. What is the best way do do that? Do I need extra permissions?<issue_comment>username_1: You can use `failure-domain.beta.kubernetes.io/region` and `failure-domain.beta.kubernetes.io/zone` labels of the pod to getting its region and AZ. But, please keep in mind, that: > > Only GCE and AWS are currently supported automatically (though it is easy to add similar support for other clouds or even bare metal, by simply arranging for the appropriate labels to be added to nodes and volumes). > > > To get access to labels, you can use `DownwardAPI` for attaching a `Volume` with your current labels and annotations of the pod. You don't need any extra permissions for use it, just mount them as a volume. Here is an example from a [documentation](https://kubernetes.io/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/): `apiVersion: v1 kind: Pod metadata: name: kubernetes-downwardapi-volume-example labels: zone: us-est-coast cluster: test-cluster1 rack: rack-22 annotations: build: two builder: john-doe spec: containers: - name: client-container image: k8s.gcr.io/busybox command: ["sh", "-c"] args: - while true; do if [[ -e /etc/podinfo/labels ]]; then echo -en '\n\n'; cat /etc/podinfo/labels; fi; if [[ -e /etc/podinfo/annotations ]]; then echo -en '\n\n'; cat /etc/podinfo/annotations; fi; sleep 5; done; volumeMounts: - name: podinfo mountPath: /etc/podinfo readOnly: false volumes: - name: podinfo downwardAPI: items: - path: "labels" fieldRef: fieldPath: metadata.labels - path: "annotations" fieldRef: fieldPath: metadata.annotations` When you have a mounted volume with labels, you can read a file `/etc/labels` which will contain information about AZ and Region as a Key-Pairs, like this:`failure-domain.beta.kubernetes.io/region=us-east-1 failure-domain.beta.kubernetes.io/zone=us-east-1c` Upvotes: 0 <issue_comment>username_2: I have not been able to find a library but I post the code that does it below. The getContent function was slightly adapted from this [post](https://www.tomas-dvorak.cz/posts/nodejs-request-without-dependencies/) This code should work inside a GKE pod or and GCE host. Use it as following: ``` const gcp = require('./gcp.js') gcp.zone().then(z => console.log('Zone is: ' + z)) ``` Module: gcp.js ``` const getContent = function(lib, options) { // return new pending promise return new Promise((resolve, reject) => { // select http or https module, depending on reqested url const request = lib.get(options, (response) => { // handle http errors if (response.statusCode < 200 || response.statusCode > 299) { reject(new Error('Failed to load page, status code: ' + response.statusCode)); } // temporary data holder const body = []; // on every content chunk, push it to the data array response.on('data', (chunk) => body.push(chunk)); // we are done, resolve promise with those joined chunks response.on('end', () => resolve(body.join(''))); }); // handle connection errors of the request request.on('error', (err) => reject(err)) }) }; exports.zone = () => { return getContent( require('http'), { hostname: 'metadata.google.internal', path: '/computeMetadata/v1/instance/zone', headers: { 'Metadata-Flavor': 'Google' }, method: 'GET' }) } ``` Upvotes: 2 [selected_answer]
2018/03/18
1,315
4,620
<issue_start>username_0: Can someone help me figure out the problem i'm new on JSF. I have built a Spring WebMVC App with Primefaces. This app contains a list of nodes which can be dragged into the spreadSheet (I m working with SpreadJS). Behind each node there is a model and a bean. Evey node has a name and an input type. I need to do the synchronization between the node value and its value in the spreadSheet and aim-versa. So in every changeEvent i call a remoteCommand and i pass five parameters to my managedBean. The problem is whenever i load my page and i get this error : here is my code : ``` @ManagedBean @SessionScoped public class HelloBean implements Serializable { private static final long serialVersionUID = 1L; @ManagedProperty("#{param.nodeId}") private String nodeId; @ManagedProperty("#{param.paramId}") private String paramId; @ManagedProperty("#{param.row}") private int row; @ManagedProperty("#{param.cel}") private int cel; @ManagedProperty("#{param.value}") private String value; public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public String getParamId() { return paramId; } public void setParamId(String paramId) { this.paramId = paramId; } public int getRow() { return row; } public void setRow(int row) { this.row = row; } public int getCel() { return cel; } public void setCel(int cel) { this.cel = cel; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public void execCmd() { Map params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap(); String nodeId = params.get("nodeId"); } ``` and my xhtml file look like : ``` Test Submit Value var nodeId = null; var paramId = null; var row = null; var cell= null; var value = null; var spread; window.onload = function() { spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss")); var sheet = spread.getActiveSheet(); sheet.setValue(0, 1, 123, GC.Spread.Sheets.SheetArea.viewport); sheet.bind(GC.Spread.Sheets.Events.CellChanged , function (e, args) { if (args.propertyName === "value") { if(sheet.getTag(0,1) != null){ var obj = JSON.parse(sheet.getTag(0,1)); nodeId = obj.nodeId; paramId = obj.paramId; row = args.row; cell = args.col; callRemoteMethod({name: 'nodeId', value: ""}, {name: 'paramId', value: ""}, {name: 'row', value: 1}, {name: 'cel', value: 1}, {name: 'value', value: "Test"}]); } } }); }; ``` and this is the Stack Trace : ``` Caused by: java.lang.IllegalArgumentException: can't parse argument number: param.nodeId at java.text.MessageFormat.makeFormat(MessageFormat.java:1420) at java.text.MessageFormat.applyPattern(MessageFormat.java:479) at java.text.MessageFormat.(MessageFormat.java:363) at java.text.MessageFormat.format(MessageFormat.java:835) at com.sun.faces.util.MessageUtils.getExceptionMessageString(MessageUtils.java:396) at com.sun.faces.mgbean.BeanBuilder$Expression.validateLifespan(BeanBuilder.java:604) at com.sun.faces.mgbean.BeanBuilder$Expression.(BeanBuilder.java:553) at com.sun.faces.mgbean.ManagedBeanBuilder.bakeBeanProperty(ManagedBeanBuilder.java:363) at com.sun.faces.mgbean.ManagedBeanBuilder.bake(ManagedBeanBuilder.java:107) ... 49 more Caused by: java.lang.NumberFormatException: For input string: "param.nodeId" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:492) at java.lang.Integer.parseInt(Integer.java:527) at java.text.MessageFormat.makeFormat(MessageFormat.java:1418) ... 57 more ``` any help ??<issue_comment>username_1: You are setting a value of an `Integer` to a `String` variable as the exception says > > java.lang.NumberFormatException: For input string: "param.nodeId" > > > The `nodeId` variable should be an `Integer` variable . **OR** You can parse the `Integer` value using `toString()` method Upvotes: 0 <issue_comment>username_2: Instead of @ManagedProperty ("# {param.nodeId}"), I made @ManagedProperty ("# {nodeId}") and it works: ``` @ManagedProperty("#{nodeId}") private String nodeId; @ManagedProperty("#{paramId}") private String paramId; @ManagedProperty("#{row}") private int row; @ManagedProperty("#{cel}") private int cel; @ManagedProperty("#{value}") private String value; ``` Upvotes: -1 [selected_answer]
2018/03/18
290
1,100
<issue_start>username_0: When I add a foreign key to a table that already has data, what does each of these database management systems do? Do they analyze each value of the column to confirm it is a value from the referenced table primary key ? Or do they have some other optimized mechanism ? And if that's the case, what is that mechanism ?<issue_comment>username_1: You are setting a value of an `Integer` to a `String` variable as the exception says > > java.lang.NumberFormatException: For input string: "param.nodeId" > > > The `nodeId` variable should be an `Integer` variable . **OR** You can parse the `Integer` value using `toString()` method Upvotes: 0 <issue_comment>username_2: Instead of @ManagedProperty ("# {param.nodeId}"), I made @ManagedProperty ("# {nodeId}") and it works: ``` @ManagedProperty("#{nodeId}") private String nodeId; @ManagedProperty("#{paramId}") private String paramId; @ManagedProperty("#{row}") private int row; @ManagedProperty("#{cel}") private int cel; @ManagedProperty("#{value}") private String value; ``` Upvotes: -1 [selected_answer]
2018/03/18
575
1,972
<issue_start>username_0: I want to compare the interval of two datetimes to see if the interval is in the past, in the future or now. ``` $current_time = new DateTime(); $datetime1 = new DateTime('2018-03-17 18:25:00'); $datetime2 = new DateTime('2018-03-17 20:00:00'); if($current_time >= $datetime1 && $current_time <= $datetime2){ // now } elseif($current_time >= $datetime1){ // past } elseif($current_time <= $datetime1){ // future } ``` EDIT: Sorry, just realised posting my whole real code would make it easier for everyone. The example above does work but it doesnt work when I loop thru the db using more than one interval from there ``` function interval(){ .... while($row = $result->fetch_assoc()){ $start_time = $row['start_time']; $end_time = $row['end_time']; $now = new DateTime(); $datetime1 = new DateTime($start_time); $datetime2 = new DateTime($end_time); if($now >= $datetime1 && $now <= $datetime2){ // now }elseif($now < $datetime1 && $now < $datetime2){ // past }elseif($now > $datetime1 && $now > $datetime2){ // future }else{ // fail? } } } ```<issue_comment>username_1: You are setting a value of an `Integer` to a `String` variable as the exception says > > java.lang.NumberFormatException: For input string: "param.nodeId" > > > The `nodeId` variable should be an `Integer` variable . **OR** You can parse the `Integer` value using `toString()` method Upvotes: 0 <issue_comment>username_2: Instead of @ManagedProperty ("# {param.nodeId}"), I made @ManagedProperty ("# {nodeId}") and it works: ``` @ManagedProperty("#{nodeId}") private String nodeId; @ManagedProperty("#{paramId}") private String paramId; @ManagedProperty("#{row}") private int row; @ManagedProperty("#{cel}") private int cel; @ManagedProperty("#{value}") private String value; ``` Upvotes: -1 [selected_answer]
2018/03/18
817
3,206
<issue_start>username_0: I try to install Hybris on ubuntu. But I get the following error : ``` [java] WARNING: Starting Solr as the root user is a security risk and not considered best practice. Exiting. [java] Please consult the Reference Guide. To override this check, start with argument '-force' ``` when I type : > > sudo ant updatesystem > > > there is any solution to solve this problem without creating a new user ? I try : > > sudo ant updatesystem -force > > > but it didn't work Any help please and thank you.<issue_comment>username_1: There is no way to force start solr. Because solr started by bean in hybris. You can try extend buildCommonSolrCommandParams metod in AbstractSolrServerController class which is setting solr parameters. You need "-force" as first command in this metod. Upvotes: 1 <issue_comment>username_2: Why you should avoid running applications as root ------------------------------------------------- I've often come across posts on forums or other websites where you see people joking in such a manner about running/logging in as root as if it's something awful and everyone ought to know about it. However, there isn't much that a search reveals on the matter. It may be widely known to Linux experts, but I really don't know why. I remember always running as root when I first tried Linux years ago (Redhat and Mandrake) and don't remember running into any problems because of that. There are actually some distros that have a bright red background with alert signs all over it as wallpaper for the root user (SuSe?). I still use the "Administrator" account for regular use on my Windows installation and haven't ever run into any problems there either.[[source]](https://askubuntu.com/q/16178/679136) --- How to create a User Account on Linux systems for Hybris Setup? --------------------------------------------------------------- 1. Open a shell prompt. 2. If you are not logged in as root, type the command su - and enter the root password. 3. Type useradd followed by a space and the username for the new account you are creating at the command line (for example, useradd jsmith). Press [Enter]. Often, usernames are variations on the user's name, such as jsmith for <NAME>. User account names can be anything from the user's name, initials, or birthplace to something more creative. 4. Type passwd followed by a space and the username again (for example, passwd jsmith). 5. At the New password: prompt enter a password for the new user and press [Enter]. 6. At the Retype new password: prompt, enter the same password to confirm your selection. --- You can find [detail post here](https://hybrisdeveloper.blogspot.in/2018/03/how-to-setup-user-account-on-linux.html) -------------------------------------------------------------------------------------------------------------------- Upvotes: 2 <issue_comment>username_3: How-to: Hack up Hybris 6.4+ to run Solr as root. This can be done by simply editing: hybris/bin/ext-commerce/solrserver/resources/solr/bin/solr Replace: FORCE=false With: FORCE=true Once done, restart Hybris. You'll see that Solr will now start up, even though Hybris is now running as root. Upvotes: 0
2018/03/18
1,331
4,631
<issue_start>username_0: I am trying to toggle a font awesome icon based on a boolean value but it seems that the font-awesome icon remains on the screen after it is drawn: <https://jsfiddle.net/50wL7mdz/200312/> HTML: ```  ``` JS: ``` new Vue({ el: '#app', data: { marked: false } }) ``` Am I doing something wrong or is there a bug in font-awesome or vue.js?<issue_comment>username_1: "i" tag comments out after fire turning to svg, use some wrap Upvotes: 5 [selected_answer]<issue_comment>username_2: **This answer applies to using Font Awesome with SVG.** ------------------------------------------------------- For some reason, you need to wrap the `i` tag twice. For example, instead of this: ``` ``` do this: ``` ``` Not entirely sure why you need to wrap it twice since I'd think you decouple the `i` tag enough by wrapping it once, but it worked for me this way so there's apparently something else going on. Also, keep in mind that the inner `div` can't be replaced with `template` for obvious reasons (template tags do not get rendered). Upvotes: 3 <issue_comment>username_3: I ran into this issue recently when using Vue.js 2.5.x with FontAwesome 5.5.x — the icon classes were not being updated as expected. *After switching from the FontAwesome Web Fonts + CSS implementation to SVG + JS*, the following code no longer worked: ``` ``` What would happen is that FontAwesome JavaScript would fire and wrap the tag and replace it with an SVG element, as in the following simplified example: ``` ... ``` Unfortunately, the active class was being toggled on the inner, hidden tag and not the outer, visible SVG element. The workaround that restored the [dynamic active class toggling](https://v2.vuejs.org/v2/guide/class-and-style.html#Binding-HTML-Classes) was to wrap the FontAwesome icons in a span and use the [`v-show` directive](https://v2.vuejs.org/v2/guide/conditional.html#v-show), as illustrated in the following code snippet: ``` ``` --- The FontAwesome documentation [now recommends](https://fontawesome.com/how-to-use/on-the-web/using-with/vuejs) using their Vue component to avoid conflicts in the DOM: > > **Compatibility Heads Up!** > If you are using Vue you need the [vue-fontawesome](https://github.com/FortAwesome/vue-fontawesome) package or Web Fonts with CSS. > > > The SVG core package is helpful and recommended in the following cases: * to subset a large number of icons into only the icons that you are using * as base libraries for larger integrations with tools like React, Angular, Vue, or Ember (in fact our own components use these packages) * as CommonJS/ES6 Modules bundling tool like Webpack, Rollup, or Parcel * as UMD-style loader library like RequireJS * directly on the server with CommonJS (see our Server Side Rendering docs Upvotes: 4 <issue_comment>username_4: I fixed this by creating a template for each icon, then loading either template conditionally based on a boolean. Here's my main template: ```html ``` Then just create the icons like so: ```js FontAwesomeConfig = { autoReplaceSvg: 'nest' }//important addition! Vue.component('minimise-icon', { template: ` ` }) Vue.component('maximise-icon', { template: ` ` }) ``` If there's a more elegant way I'm all ears! Upvotes: 0 <issue_comment>username_5: The Font Awesome library you used doesn't know about Vue. It takes the that you wrote and turns it into an , and at that point, it's been stolen from Vue. Vue no longer controls it. The [answer that username_1 gave](https://stackoverflow.com/a/49343449/135101) was a good one: wrap it with a . But then you pointed out another scenario it doesn't work for. To solve your scenario where wrapping with a still doesn't work, use `key="fa-sort-up"`. This will force Vue to re-render the wrapper, at which point Font Awesome will update the icon. Here's the [updated jsFiddle](https://jsfiddle.net/r0pxbq13/) for your example: ```js ``` You can use anything you want for the key, as long as it's unique. Upvotes: 2 <issue_comment>username_6: Toggle a checkbox in vue with FontAwesome ``` .fa-check-square::before { color: green; } Vue.component('some', { data: function() { return{ isclick: false } }, methods: { isClicked: function() { this.isclick = !this.isclick; } }, template: '<div id="test" v-on:click="isClicked">' + '<i v-if="isclick" class="fa fa-check-square" style="font-size: 40px;"></i>' + '<i v-if="!isclick" class="far fa-square" style="font-size: 40px;"></i>' + '</div>' }); new Vue({ el: '#componentsDemo' }); ``` Upvotes: 1
2018/03/18
1,602
5,408
<issue_start>username_0: I have this hash that contains some information: ``` my %hash = ( key_1 => { year => 2000, month => 02, }, key_2 => { year => 2000, month => 02, }, key_3 => { year => 2000, month => 03, }, key_4 => { year => 2000, month => 05, }, key_5 => { year => 2000, month => 01, } ); ``` I wan't to create an array of hashes in which each of the array elements, lists every single hash key/value pairs that has the same year and month. So basically I want to create something like this: ``` $VAR1 = [ 'key_1' => { 'month' => 2, 'year' => 2000 }, 'key_2' => { 'month' => 2, 'year' => 2000 } ], [ 'key_3' => { 'month' => 3, 'year' => 2000 } ], [ 'key_4' => { 'month' => 3, 'year' => 2000 } ], [ 'key_5' => { 'year' => 2000, 'month' => 1 } ]; ``` The real question here is: How can I compare a hash key key value's to other key key value's and make a map out of it. Thank you for your time! =)<issue_comment>username_1: "i" tag comments out after fire turning to svg, use some wrap Upvotes: 5 [selected_answer]<issue_comment>username_2: **This answer applies to using Font Awesome with SVG.** ------------------------------------------------------- For some reason, you need to wrap the `i` tag twice. For example, instead of this: ``` ``` do this: ``` ``` Not entirely sure why you need to wrap it twice since I'd think you decouple the `i` tag enough by wrapping it once, but it worked for me this way so there's apparently something else going on. Also, keep in mind that the inner `div` can't be replaced with `template` for obvious reasons (template tags do not get rendered). Upvotes: 3 <issue_comment>username_3: I ran into this issue recently when using Vue.js 2.5.x with FontAwesome 5.5.x — the icon classes were not being updated as expected. *After switching from the FontAwesome Web Fonts + CSS implementation to SVG + JS*, the following code no longer worked: ``` ``` What would happen is that FontAwesome JavaScript would fire and wrap the tag and replace it with an SVG element, as in the following simplified example: ``` ... ``` Unfortunately, the active class was being toggled on the inner, hidden tag and not the outer, visible SVG element. The workaround that restored the [dynamic active class toggling](https://v2.vuejs.org/v2/guide/class-and-style.html#Binding-HTML-Classes) was to wrap the FontAwesome icons in a span and use the [`v-show` directive](https://v2.vuejs.org/v2/guide/conditional.html#v-show), as illustrated in the following code snippet: ``` ``` --- The FontAwesome documentation [now recommends](https://fontawesome.com/how-to-use/on-the-web/using-with/vuejs) using their Vue component to avoid conflicts in the DOM: > > **Compatibility Heads Up!** > If you are using Vue you need the [vue-fontawesome](https://github.com/FortAwesome/vue-fontawesome) package or Web Fonts with CSS. > > > The SVG core package is helpful and recommended in the following cases: * to subset a large number of icons into only the icons that you are using * as base libraries for larger integrations with tools like React, Angular, Vue, or Ember (in fact our own components use these packages) * as CommonJS/ES6 Modules bundling tool like Webpack, Rollup, or Parcel * as UMD-style loader library like RequireJS * directly on the server with CommonJS (see our Server Side Rendering docs Upvotes: 4 <issue_comment>username_4: I fixed this by creating a template for each icon, then loading either template conditionally based on a boolean. Here's my main template: ```html ``` Then just create the icons like so: ```js FontAwesomeConfig = { autoReplaceSvg: 'nest' }//important addition! Vue.component('minimise-icon', { template: ` ` }) Vue.component('maximise-icon', { template: ` ` }) ``` If there's a more elegant way I'm all ears! Upvotes: 0 <issue_comment>username_5: The Font Awesome library you used doesn't know about Vue. It takes the that you wrote and turns it into an , and at that point, it's been stolen from Vue. Vue no longer controls it. The [answer that username_1 gave](https://stackoverflow.com/a/49343449/135101) was a good one: wrap it with a . But then you pointed out another scenario it doesn't work for. To solve your scenario where wrapping with a still doesn't work, use `key="fa-sort-up"`. This will force Vue to re-render the wrapper, at which point Font Awesome will update the icon. Here's the [updated jsFiddle](https://jsfiddle.net/r0pxbq13/) for your example: ```js ``` You can use anything you want for the key, as long as it's unique. Upvotes: 2 <issue_comment>username_6: Toggle a checkbox in vue with FontAwesome ``` .fa-check-square::before { color: green; } Vue.component('some', { data: function() { return{ isclick: false } }, methods: { isClicked: function() { this.isclick = !this.isclick; } }, template: '<div id="test" v-on:click="isClicked">' + '<i v-if="isclick" class="fa fa-check-square" style="font-size: 40px;"></i>' + '<i v-if="!isclick" class="far fa-square" style="font-size: 40px;"></i>' + '</div>' }); new Vue({ el: '#componentsDemo' }); ``` Upvotes: 1
2018/03/18
1,795
6,283
<issue_start>username_0: so this is a tag on from my previous stackoverflow post: [Django updateView saving another instance instead of updating](https://stackoverflow.com/questions/49341267/django-updateview-saving-another-instance-instead-of-updating?noredirect=1#comment85682686_49341267) and i think i've narrowed it down. Whats happening is that when i click on the link to update my view, it sends me to the "create new" page. my problem is that I cant figure out why its doing that. Any and all help is appreciated. here is the code: **question\_form.html** ``` {% extends "base.html" %} {% load bootstrap3 %} {% block content %} #### Create New Question {% csrf\_token %} {% bootstrap\_form form %} {% endblock %} ``` **question\_update.html** ``` {% extends "base.html" %} {% load bootstrap3 %} {% block content %} #### Update Question {% csrf\_token %} {% bootstrap\_form form %} {% endblock %} ``` **question\_detail.html** ``` {% block content %} this is the question detail view ### {{ question.question\_html|safe }} ### {{ question.answer\_html|safe }} [Update Question]({% url 'questions:update' pk=question.pk %}) {% endblock %} ``` **urls.py** ``` url(r'new/$', views.CreateQuestion.as_view(), name='create'), url(r'questionupdate/(?P\d+)/$', views.QuestionUpdate.as\_view(), name='update'), url(r'questiondetail/(?P\d+)/$', views.QuestionDetail.as\_view(), name='single'), ``` **views.py** ``` class CreateQuestion(generic.CreateView): model = models.Question form = QuestionForm fields = ('question', 'answer') success_url = reverse_lazy('questions:all') def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class QuestionDetail(generic.DetailView): model = models.Question class QuestionUpdate(generic.UpdateView): model = models.Question form_class = QuestionForm context_object_name = 'question' ```<issue_comment>username_1: "i" tag comments out after fire turning to svg, use some wrap Upvotes: 5 [selected_answer]<issue_comment>username_2: **This answer applies to using Font Awesome with SVG.** ------------------------------------------------------- For some reason, you need to wrap the `i` tag twice. For example, instead of this: ``` ``` do this: ``` ``` Not entirely sure why you need to wrap it twice since I'd think you decouple the `i` tag enough by wrapping it once, but it worked for me this way so there's apparently something else going on. Also, keep in mind that the inner `div` can't be replaced with `template` for obvious reasons (template tags do not get rendered). Upvotes: 3 <issue_comment>username_3: I ran into this issue recently when using Vue.js 2.5.x with FontAwesome 5.5.x — the icon classes were not being updated as expected. *After switching from the FontAwesome Web Fonts + CSS implementation to SVG + JS*, the following code no longer worked: ``` ``` What would happen is that FontAwesome JavaScript would fire and wrap the tag and replace it with an SVG element, as in the following simplified example: ``` ... ``` Unfortunately, the active class was being toggled on the inner, hidden tag and not the outer, visible SVG element. The workaround that restored the [dynamic active class toggling](https://v2.vuejs.org/v2/guide/class-and-style.html#Binding-HTML-Classes) was to wrap the FontAwesome icons in a span and use the [`v-show` directive](https://v2.vuejs.org/v2/guide/conditional.html#v-show), as illustrated in the following code snippet: ``` ``` --- The FontAwesome documentation [now recommends](https://fontawesome.com/how-to-use/on-the-web/using-with/vuejs) using their Vue component to avoid conflicts in the DOM: > > **Compatibility Heads Up!** > If you are using Vue you need the [vue-fontawesome](https://github.com/FortAwesome/vue-fontawesome) package or Web Fonts with CSS. > > > The SVG core package is helpful and recommended in the following cases: * to subset a large number of icons into only the icons that you are using * as base libraries for larger integrations with tools like React, Angular, Vue, or Ember (in fact our own components use these packages) * as CommonJS/ES6 Modules bundling tool like Webpack, Rollup, or Parcel * as UMD-style loader library like RequireJS * directly on the server with CommonJS (see our Server Side Rendering docs Upvotes: 4 <issue_comment>username_4: I fixed this by creating a template for each icon, then loading either template conditionally based on a boolean. Here's my main template: ```html ``` Then just create the icons like so: ```js FontAwesomeConfig = { autoReplaceSvg: 'nest' }//important addition! Vue.component('minimise-icon', { template: ` ` }) Vue.component('maximise-icon', { template: ` ` }) ``` If there's a more elegant way I'm all ears! Upvotes: 0 <issue_comment>username_5: The Font Awesome library you used doesn't know about Vue. It takes the that you wrote and turns it into an , and at that point, it's been stolen from Vue. Vue no longer controls it. The [answer that username_1 gave](https://stackoverflow.com/a/49343449/135101) was a good one: wrap it with a . But then you pointed out another scenario it doesn't work for. To solve your scenario where wrapping with a still doesn't work, use `key="fa-sort-up"`. This will force Vue to re-render the wrapper, at which point Font Awesome will update the icon. Here's the [updated jsFiddle](https://jsfiddle.net/r0pxbq13/) for your example: ```js ``` You can use anything you want for the key, as long as it's unique. Upvotes: 2 <issue_comment>username_6: Toggle a checkbox in vue with FontAwesome ``` .fa-check-square::before { color: green; } Vue.component('some', { data: function() { return{ isclick: false } }, methods: { isClicked: function() { this.isclick = !this.isclick; } }, template: '<div id="test" v-on:click="isClicked">' + '<i v-if="isclick" class="fa fa-check-square" style="font-size: 40px;"></i>' + '<i v-if="!isclick" class="far fa-square" style="font-size: 40px;"></i>' + '</div>' }); new Vue({ el: '#componentsDemo' }); ``` Upvotes: 1
2018/03/18
1,507
5,761
<issue_start>username_0: I am trying to relate my Picture Model to the User Model by `belongsTo` and `hasMany` methods. --- Heres the code written in `Picture.php` model file: ``` php namespace App; use Illuminate\Database\Eloquent\Model; class Picture extends Model{ public function user() { return $this-belongsTo('App\User'); } } ``` --- Here's the code of my `User.php` model file: ``` php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function pictures() { return $this-hasMany('App\Picture'); } } ``` --- I want to show the pictures uploaded by the user itself in the `manage` view which is demonstrated in my `RouteController` file: ``` php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Picture; use App\User; use DB; class RouteController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this-middleware('auth', ['except' => ['welcome', 'auth.login', 'auth.register']]); } public function welcome() { $pictures = Picture::all(); return view('welcome')->with('pictures', $pictures); } public function login() { return view('auth.login'); } public function register() { return view('auth.register'); } public function manage() { $user_id = auth()->user('id'); $user = User::find($user_id); $pictures = Picture::all(); return view('pictures.manage')->with('pictures', $pictures->user); } } ``` --- And in the `manage.blade.php` I have to output the pictures. For that, I written this code: ``` @foreach ($pictures as $picture) ### {{ $picture->hash }} @endforeach ``` --- **And after all this hustle and bustle, it gives me an error which says:** `Property [user] does not exist on this collection instance.` I want the pictures owned by the user to output in `manage` view. If you want to see all the files in the project, visit this [GitHub commit](https://github.com/KumarAbhirup/myTaswir/tree/58daca1a12f3b6d522f38b330d5fa229caeae408). **Thanks for help in advance**<issue_comment>username_1: This happens because you're calling `$pictures->user`. `$pictures` holds a [collection](https://laravel.com/docs/5.6/collections) (enhanced array) of all pictures from this statement: `$pictures = Picture::all();`. A collection is not an object and doesn't have properties. Also, you're not scoping your pictures to user's only anywhere. You're calling `Picture::all()` which will return all pictures from all users. Assuming your relationships work as intended you could get currently logged in user's picture with `$user->pictures` method. This is all you need: ``` $pictures = auth()->user()->pictures; return view('pictures.manage')->with('pictures', $pictures); ``` And also remove the `->user` part from `->with('pictures', $pictures)`. Upvotes: 1 <issue_comment>username_2: I think tour problem is into `manage` method. Try to do that ``` public function manage() { $user = auth()->user(); $pictures = $user->pictures; return view('pictures.manage')->with(['pictures' => $pictures]); } ``` Upvotes: 1 <issue_comment>username_3: In your pictures migration you need to add `user_id` foreign key to be able having relation between users and pictures as you have in your models. Something like this: ``` use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePicturesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('pictures', function (Blueprint $table) { $table->increments('id'); // $table->string('storage_url'); // $table->string('preview_url'); $table->string('hash'); $table->unsignedInteger('user_id');// or $table->integer('user_id')->unsigned(); $table->timestamps(); }); Schema::table('pictures', function (Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); // also you can put some triggered actions ->onUpdate('cascade')->onDelete('cascade') }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('pictures', function (Blueprint $table) { $table->dropForeign(['user_id']); }); Schema::dropIfExists('pictures'); } } ``` Just be certain that `users.id` and `pictures.user_id` have to be same type fields. Check various options in [docs](https://laravel.com/docs/5.6/migrations#foreign-key-constraints). And then, what other said in answers. Upvotes: 1 <issue_comment>username_4: Please add relationship between user and pictures. Make new migration for add foreign key in pictures model . Please refer below link. <https://laravel.com/docs/5.6/migrations> Also add foreign key column name in pictures model in fillable part. Then after change your mange method code like... $user = User::with(['pictures'])->where('id', Auth::id())->first(); return view('pictures.manage')->with(['pictures' => $user['pictures']); Upvotes: 0
2018/03/18
2,665
8,300
<issue_start>username_0: I'm currently trying to learn Swift and haven't gotten very far yet, so forgive me if this is an easy problem; I've been working on it for hours now and haven't been able to figure it out. I have a `Codable` class called `Person`. On this class I have a `Date` property called `birthdate`. So it looks like this: ``` class Person : Codable { var birthdate: Date = Date() var firstName: String = "" var lastName: String = "" enum CodingKeys : String, CodingKey { case birthdate case firstName = "first_name" case lastName = "last_name" } } ``` And I'm trying to decode my JSON: ``` [ { "address": "302 N. 5th St.", "base_64_image": null, "birthdate": "2009-05-06T18:56:38.367", "created": "2017-11-21T16:21:13", "emergency_contact": "", "emergency_contact_number": null, "father_cell_number": null, "father_home_number": null, "father_name": null, "first_name": "John", "gender": 1, "id": "d92fac59-66b9-49a5-9446-005babed617a", "image_uri": null, "is_inactive": false, "last_name": "Smith", "mother_cell_number": "1234567890", "mother_home_number": "", "mother_name": "<NAME>", "nickname": null, "tenant_id": "9518352f-4855-4699-b0da-ecdc06470342", "updated": "2018-01-20T02:11:45.9025023" } ] ``` like this: ``` // Fetch the data from the URL. let headers: HTTPHeaders = [ "Accept": "application/json" ] Alamofire.request(url, headers: headers).responseJSON { response in if let data = response.data { let decoder = JSONDecoder() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" decoder.dateDecodingStrategy = .formatted(dateFormatter) let people = try! decoder.decode(Array.self, from: data) } } ``` However, I always get the same error: > > Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [Foundation.(\_JSONKey in \_12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 47", intValue: Optional(47)), App.Person.CodingKeys.birthdate], debugDescription: "Date string does not match format expected by formatter.", underlyingError: nil)) > > > (The "Index 47" obviously isn't accurate, since that's for my live [and private] data). If I take the `birthdate` property off the `Person` class everything works as expected. I've been Googling and trying new things for several hours, and still can't get it to work no matter what I try. Can anyone here help me out?<issue_comment>username_1: It looks like one of your birthdates: ``` "birthdate": "2009-05-06T18:56:38.367", ``` contains milliseconds. Your date format string: ``` dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" ``` Isn't able to handle this. You can either change the `birthdate` field in the incoming JSON, or change your `dateFormat` string to this: ``` dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS" ``` Note that adding `.SSS` appears to break the formatter for non-millisecond dates. I'd recommend cutting out the milliseconds server-side. --- Original answer below: I've just tried this in a Playground, and it appears to work as expected: ``` class Person : Codable { var birthdate: Date = Date() var firstName: String = "" var lastName: String = "" enum CodingKeys : String, CodingKey { case birthdate case firstName = "first_name" case lastName = "last_name" } } var json: String = """ [ { "birthdate": "2009-05-06T18:56:38", "first_name": "John", "last_name": "Smith" } ] """ let decoder = JSONDecoder() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" decoder.dateDecodingStrategy = .formatted(dateFormatter) let people = try! decoder.decode(Array.self, from: json.data(using: .utf8, allowLossyConversion: false)!) ``` Where `people` is now this: ``` {birthdate "May 6, 2009 at 6:56 PM", firstName "John", lastName "Smith"} ``` Either there's something subtly different between my code and yours, or there may be a different set of example data needed. Upvotes: 5 [selected_answer]<issue_comment>username_2: You just forgot to add milliseconds to your date format. Change this line: `dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"`. With this: `dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"` Upvotes: 2 <issue_comment>username_3: If you decode JSON with dates in multiple parts of your code I recommend doing a custom class to adapt the decoding to what you need in this case: decoding **Date**. --- ### The implementation will be something like this: ``` /**Custom decoder for dates*/ class DecoderDates: JSONDecoder { override func decode(\_ type: T.Type, from data: Data) throws -> T where T : Decodable { let decoder = JSONDecoder() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS" decoder.dateDecodingStrategy = .formatted(dateFormatter) return try decoder.decode(T.self, from: data) } } ``` --- ### Example use: ``` DecoderDates().decode(Codable.self, from: data) ``` Hope this helps someone. Upvotes: 2 <issue_comment>username_4: Details ------- * Xcode Version 12.3 (12C33) * Swift 5.3 Solution -------- ``` import Foundation protocol StaticDateFormatterInterface { static var value: DateFormatter { get } } enum DecodableDate where Formatter: StaticDateFormatterInterface { case value(Date) case error(DecodingError) var value: Date? { switch self { case .value(let value): return value case .error: return nil } } var error: DecodingError? { switch self { case .value: return nil case .error(let error): return error } } enum DecodingError: Error { case wrongFormat(source: String, dateFormatter: DateFormatter) case decoding(error: Error) } } extension DecodableDate: Decodable { func createDateFormatter() -> DateFormatter { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" return dateFormatter } init(from decoder: Decoder) throws { do { let dateString = try decoder.singleValueContainer().decode(String.self) guard let date = Formatter.value.date(from: dateString) else { self = .error(DecodingError.wrongFormat(source: dateString, dateFormatter: Formatter.value)) return } self = .value(date) } catch let err { self = .error(.decoding(error: err)) } } } ``` Usage ----- ``` class DefaultDateFormatter: StaticDateFormatterInterface { static var value: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" return dateFormatter }() } struct Dates: Decodable { let date1: DecodableDate let date2: DecodableDate let date3: DecodableDate let date4: DecodableDate let date5: DecodableDate } var text = [ "date1": "2020-06-03T01:43:44.888Z", "date2": "2020-06-03\_01:43:44.888Z", "date3": "blabla", "date4": ["blabla"], "date5": 22, ] as [String: Any] let data = try! JSONSerialization.data(withJSONObject: text) let object = try JSONDecoder().decode(Dates.self, from: data) print(object.date1) print(object.date2) print(object.date3) print(object.date4) print(object.date5) func print(\_ obj: DecodableDate) { switch obj { case .error(let error): print("Error: \(error)") case .value(let date): print("Value: \(date)") } } ``` Log --- ``` // Value: 2020-06-03 01:43:44 +0000 // Error: wrongFormat(source: "2020-06-03_01:43:44.888Z", dateFormatter: ) // Error: wrongFormat(source: "blabla", dateFormatter: ) // Error: decoding(error: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "date4", intValue: nil)], debugDescription: "Expected to decode String but found an array instead.", underlyingError: nil))) // Error: decoding(error: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "date5", intValue: nil)], debugDescription: "Expected to decode String but found a number instead.", underlyingError: nil))) ``` Upvotes: 2
2018/03/18
920
3,044
<issue_start>username_0: Let's figure a simple sum app. two inputs, `a` and `b` and a `c` result. we have this markup ``` {{v3}} ``` and this Vue script ``` var vm = new Vue ({ el: "#app", data: { a:0, b:0, }, computed: { c:function(){ return this.a + this.b; } } }) ``` this works great except that I'm working with localized numbers. that means. using comma "," instead of dot "." and dot instead of comma . entering number with decimal places confuses vue, and it are not able to make a correct sum. What can I do in order to make VueJS understand localized number input and them make the correct sum? for instance in pt-BR locale: `1.000,30` + `100,30` = `1.100,60`<issue_comment>username_1: Well, first of all, a number is just a number. Internally, the `.` will always be the decimal separator. So a number like `1.100,60` is the number `1100.60` just *printed* in a different locale. To print it, just use **[JavaScript's `Number#toStringLocale()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString)**: ```js var vm = new Vue({ el: "#app", data: { a: 1110.12, b: 10000.11, }, computed: { c: function() { return this.a + this.b; } } }) ``` ```html --- Browser's locale: {{c.toLocaleString()}} en-US locale: {{c.toLocaleString('en-US')}} pt-BR locale: {{c.toLocaleString('pt-BR')}} ``` Using a formatted ================= Now, if you want the to take localized numbers, that is not a problem specific to Vue, but to JavaScript and the browser in general. This means that you'll have to find a custom component that implements the behavior you want (formatting in the ). Luckily, a quick search [brings one that seems to to the job](https://github.com/kevinongko/vue-numeric): ```js Vue.use(VueNumeric.default) var vm = new Vue({ el: "#app", data: { a: 1110.12, b: 10000.11, }, computed: { c: function() { return this.a + this.b; } } }) ``` ```html Formatted inputs: --- Browser's locale: {{c.toLocaleString()}} en-US locale: {{c.toLocaleString('en-US')}} pt-BR locale: {{c.toLocaleString('pt-BR')}} ``` Again, the component just changes the input field. The number will still be just a number and the "printing" will still have to be done using `.toLocaleString()`. Upvotes: 3 [selected_answer]<issue_comment>username_2: Using vuex as store my approach on doing this was to use [two-way-computed-property](https://vuex.vuejs.org/guide/forms.html#two-way-computed-property) with a getter and a setter. The getter takes the data (in float) out of the store and shows it in the input-field formated with .toLocalString(). The setter takes the input as a local-formatted string and replaces ( .replace() ) the dots with "" and the commas with "."- after doing this string needs to be parsed as float ( parseFloat(string) ) and then the action for updating the store will be dispatched. Upvotes: -1
2018/03/18
2,199
9,673
<issue_start>username_0: I am trying to follow a YouTube tutorial and learn Swift by making a simple card game. After completing the tutorial I wanted to add some features of my own such as resetting the score and cards once the app is opened. When I say opened I mean either entering the foreground or launching the app. I am currently attempting this by creating a method called `reset` in `ViewController.swift` and calling the method in `AppDelegate.swift` when the function `applicationWillEnterForeground` is called. I am able to build the code successfully and run it however when the app comes to foreground I get an error which states "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value". AppDelegate.swift: ``` // // AppDelegate.swift // War // // Created by Rafael on 3/17/18. // Copyright © 2018 Rafael. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate{ var window: UIWindow? var ViewControl: ViewController = ViewController() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. print("Launching app!") return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. print("Going inactive!") } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. print("Entering background!") } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. print("Entering Foreground!") ViewControl.reset() } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. print("Going active!") } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. print("Going to terminate!") } } enter code here ``` ViewController.swift: ``` // // ViewController.swift // War // // Created by Rafael on 3/17/18. // Copyright © 2018 Rafael. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var rightImageView: UIImageView! @IBOutlet weak var leftImageView: UIImageView! @IBOutlet weak var leftScoreLabel: UILabel! var leftScore = 0 @IBOutlet weak var rightScoreLabel: UILabel! var rightScore = 0 let cardNames = ["card2", "card3", "card4", "card5", "card6", "card7", "card8", "card9", "card10", "card11", "card12", "card13", "card14"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. print("loading view!") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func dealTapped(_ sender: Any) { let leftNumber = Int(arc4random_uniform(13)) let rightNumber = Int(arc4random_uniform(13)) if leftNumber > rightNumber { leftScore += 1 leftScoreLabel.text = String(leftScore) } else if(rightNumber == leftNumber){ // Do nothing - TIE } else{ rightScore += 1 rightScoreLabel.text = String(rightScore) } leftImageView.image = UIImage(named: cardNames[leftNumber]) rightImageView.image = UIImage(named: cardNames[rightNumber]) } func reset() { print("resetting!") leftImageView.image = UIImage(named: "back") rightImageView.image = UIImage(named: "back") rightScoreLabel.text = "0" leftScoreLabel.text = "0" rightScore = 0 leftScore = 0 } } ``` All outlets are working fine and the app works fine. The only issue is when the function `reset` is called. How can I make my app reset the cards when the app is going to be in view? I am still learning the language.<issue_comment>username_1: You're doing a few things wrong. First of all, you don't appear to be persisting any of the data to disk, so everything will reset everytime you start anyway. But here's a couple of things. 1: You should be doing resetting of your ViewController's properties / state, inside the view controller itself; not from AppDelegate. 2: you named your view controller variable like this. `var ViewController: ViewController = ViewController()`. The proper way to name your variables in Swift / Objective-C is camel cased `var viewController = ViewController()` or better yet something like `var myViewController = ViewController()`. Because when you typed in ViewController, it had the same name as the class itself, it wasn't trying to access your instance. It's really confusing to yourself (and the compiler) to name your ivars exactly the same as the class name. 3: You initialized an instance of ViewController, but it's not the same one that you're seeing on the screen. What you see on the screen is owned and created by the Storyboard. That ViewController you created in AppDelegate wasn't actually doing anything. That's why the IBOutlets were nil, because the labels on the screen were inside of the instance the Storyboard made on it's own. So all you have to do is put your logic in your ViewController.swift file; you won't have to create your own instance. That being said, if you want something to happen after a view controller appears on the screen, you either need to write a function inside of it called `override func viewWillAppear (animated: Bool) {}` or put it in viewDidLoad(). In iOS, the Model View Controller pattern is used. Each screen is controlled by a UIViewController. So any kind of logic for manipulating the screen and it's views should done inside of the View Controller subclass. The way the view controllers work is, first `viewDidLoad()` is called, then `viewWillAppear()`, finally `viewDidAppear()`. Upvotes: 1 <issue_comment>username_1: Here's a couple of things to think about. First of all, trying to reset your view's state, every time they leave the app and come back is almost certainly not what users would expect. Can you imagine what it would be like to be playing a game, an email comes in and you switch over to look, then go back and your game is back to the beginning of the level? Also, unless you are doing something that is View Controller independent, such as fetching cloud records from the background, you probably need to just stay out of AppDelegate. The paradigm Apple has set up (Model View Controller) for it's platforms is to control what you see on the screen from inside of the View Controller. You are trying to control the View Controller from AppDelegate in order to manipulate the content on screen. I would suggest rethinking how you're going about controlling the screen contents. Also, once the app has been in the background for a certain amount of time (you're in the home screen or another app), it will eventually reset it's state anyway and then viewWillAppear will be called again. That's why each ViewController has methods for saving and restoring state, when this happens. Despite all of this, there is a way of accessing your ViewController's instance from AppDelegate. You can get to the root view controller like this `let rootVC = UIApplication.shared.keyWindow?.rootViewController`. Remember though, what you think of as your main screen, may not be the root view controller. The root controller could be the tab bar, or a navigation controller. If so, you'll have to keep on going down the chain until you find it. Another way to get messages across to a ViewController, without having direct access to it's instance, is to send a message with foundation's NotificationCenter. Like this: `NotificationCenter.default.post(name: NSNotification.Name(rawValue: "app has returned from background"), object: nil)`. And then in the view controller you would put something like this: `NotificationCenter.default.addObserver(self, selector: #selector(screenRefreshedFunction), name: NSNotification.Name(rawValue: "app has returned from background"), object: nil)`, then create that function. I think iOS has built-in notifications for when the app goes into the background, that you can set up to observe. I'm not sure what they are without looking through the documentation. Upvotes: 3 [selected_answer]
2018/03/18
510
2,221
<issue_start>username_0: I have a web service that I want to send some information but I don't care about the response from that server. I just want to give the server the information and it does whatever it wants with it. How could I do that in iOS with objective-C? I'm using at the moment a background thread web call but it gets a response which I'm worried that if the user closes the app or navigates between scenes, that the response coming back may crash the app with a null reference.<issue_comment>username_1: If you're really worried about this, and truly don't care about whether the request succeeds or fails, you could put wrap the request in a `try` block, then background it to another thread. That should completely insulate it from the rest of your app. Upvotes: -1 <issue_comment>username_2: I assume that you have an **HTTP** web service. In the usual HTTP there's almost no such thing as "fire and forget". The closest thing is to send a HEAD request, because the convention about it is that a response to a HEAD method should not have a body. But it is still just a convention. If you control the web service yourself, and for example, you are using a POST which returns an empty response, then due to HTTP logic you still have to: 1. establish a TCP/TLS connection (for https) 2. send an HTTP request 3. receive an HTTP response with 200 OK status Each of these can fail, and if it does, you can't be sure that your call has reached the server. For example your server might return 500 Server Error, and it is up to you if you want to ignore it or not, but you have to wait for it. If you don't receive it, it might just time out (for example if you have sent a request and there is not response for a long time). Also note that sending the app to background and resource pressure might be another reason why the request is not delivered. In many cases when you want to be sure that your request is delivered, then you have to inspect the response code, and probably retry your request a few times. If you truly don't care that your request was delivered, you could just ignore NSURLResponse and NSError inside the completionHandler for your NSURLSessionDataTask. Upvotes: 1 [selected_answer]
2018/03/18
559
2,325
<issue_start>username_0: So I am trying to make a quote system for a chat bot, and I'm having trouble with storing them. I have decided to move away from using a database because of how small scale it is, but I want to be able to constantly add to the file, is there any way I am able to find how many "variables" already in the file? My current file would be setup like this: ``` { "quote1":"texthere", "quote2":"texthere", "quote3":"texthere", "quote4":"texthere" } ``` Is there a possible way I am able to figure out how many quotes there are in the file? I am programming in javascript.<issue_comment>username_1: If you're really worried about this, and truly don't care about whether the request succeeds or fails, you could put wrap the request in a `try` block, then background it to another thread. That should completely insulate it from the rest of your app. Upvotes: -1 <issue_comment>username_2: I assume that you have an **HTTP** web service. In the usual HTTP there's almost no such thing as "fire and forget". The closest thing is to send a HEAD request, because the convention about it is that a response to a HEAD method should not have a body. But it is still just a convention. If you control the web service yourself, and for example, you are using a POST which returns an empty response, then due to HTTP logic you still have to: 1. establish a TCP/TLS connection (for https) 2. send an HTTP request 3. receive an HTTP response with 200 OK status Each of these can fail, and if it does, you can't be sure that your call has reached the server. For example your server might return 500 Server Error, and it is up to you if you want to ignore it or not, but you have to wait for it. If you don't receive it, it might just time out (for example if you have sent a request and there is not response for a long time). Also note that sending the app to background and resource pressure might be another reason why the request is not delivered. In many cases when you want to be sure that your request is delivered, then you have to inspect the response code, and probably retry your request a few times. If you truly don't care that your request was delivered, you could just ignore NSURLResponse and NSError inside the completionHandler for your NSURLSessionDataTask. Upvotes: 1 [selected_answer]
2018/03/18
5,696
15,919
<issue_start>username_0: How I can know what is the problem when there is no stack trace? Can I enable some option? I just created small project with spring initializer and this is what I'm getting Updated log(With debug flag) ``` . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.0.RELEASE) 2018-03-18 02:40:52.246 INFO 16664 --- [ restartedMain] c.o.b.BigDataProjectApplication : Starting BigDataProjectApplication on oscar-Inspiron-5735 with PID 16664 (/home/oscar/IdeaProjects/big-data-project/out/production/classes started by oscar in /home/oscar/IdeaProjects/big-data-project) 2018-03-18 02:40:52.253 INFO 16664 --- [ restartedMain] c.o.b.BigDataProjectApplication : No active profile set, falling back to default profiles: default 2018-03-18 02:40:52.254 DEBUG 16664 --- [ restartedMain] o.s.boot.SpringApplication : Loading source class com.owozniak.bigdataproject.BigDataProjectApplication 2018-03-18 02:40:52.476 DEBUG 16664 --- [ restartedMain] o.s.b.c.c.ConfigFileApplicationListener : Loaded config file 'file:/home/oscar/IdeaProjects/big-data-project/out/production/resources/application.properties' (classpath:/application.properties) 2018-03-18 02:40:52.512 INFO 16664 --- [ restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@c156816: startup date [Sun Mar 18 02:40:52 CET 2018]; root of context hierarchy 2018-03-18 02:40:52.516 DEBUG 16664 --- [ restartedMain] ConfigServletWebServerApplicationContext : Bean factory for org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@c156816: org.springframework.beans.factory.support.DefaultListableBeanFactory@5f820b6d: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,bigDataProjectApplication]; root of factory hierarchy 2018-03-18 02:40:55.008 DEBUG 16664 --- [ restartedMain] o.s.b.a.AutoConfigurationPackages : @EnableAutoConfiguration was declared on a class in the package 'com.owozniak.bigdataproject'. Automatic @Repository and @Entity scanning is enabled. 2018-03-18 02:40:55.882 INFO 16664 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$54765f50] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2018-03-18 02:40:55.959 DEBUG 16664 --- [ restartedMain] ConfigServletWebServerApplicationContext : Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@1214c019] 2018-03-18 02:40:55.959 DEBUG 16664 --- [ restartedMain] ConfigServletWebServerApplicationContext : Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@41ee5a59] 2018-03-18 02:40:56.386 DEBUG 16664 --- [ restartedMain] .s.b.w.e.t.TomcatServletWebServerFactory : Code archive: /home/oscar/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot/2.0.0.RELEASE/771da2071ff14a47f108642a641c204ae4ef7b15/spring-boot-2.0.0.RELEASE.jar 2018-03-18 02:40:56.387 DEBUG 16664 --- [ restartedMain] .s.b.w.e.t.TomcatServletWebServerFactory : Code archive: /home/oscar/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot/2.0.0.RELEASE/771da2071ff14a47f108642a641c204ae4ef7b15/spring-boot-2.0.0.RELEASE.jar 2018-03-18 02:40:56.388 DEBUG 16664 --- [ restartedMain] .s.b.w.e.t.TomcatServletWebServerFactory : None of the document roots [src/main/webapp, public, static] point to a directory and will be ignored. 2018-03-18 02:40:56.551 INFO 16664 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2018-03-18 02:40:56.604 INFO 16664 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2018-03-18 02:40:56.605 INFO 16664 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28 2018-03-18 02:40:56.616 INFO 16664 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib] 2018-03-18 02:40:56.838 INFO 16664 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2018-03-18 02:40:56.838 INFO 16664 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4361 ms 2018-03-18 02:40:57.959 DEBUG 16664 --- [ost-startStop-1] o.s.b.w.s.ServletContextInitializerBeans : Added existing Servlet initializer bean 'dispatcherServletRegistration'; order=2147483647, resource=class path resource [org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration.class] 2018-03-18 02:40:57.959 DEBUG 16664 --- [ost-startStop-1] o.s.b.w.s.ServletContextInitializerBeans : Added existing Filter initializer bean 'webMvcMetricsFilter'; order=2147483647, resource=class path resource [org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfiguration.class] 2018-03-18 02:40:57.961 DEBUG 16664 --- [ost-startStop-1] o.s.b.w.s.ServletContextInitializerBeans : Added existing ServletContextInitializer initializer bean 'servletEndpointRegistrar'; order=2147483647, resource=class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration.class] 2018-03-18 02:40:58.051 DEBUG 16664 --- [ost-startStop-1] o.s.b.w.s.ServletContextInitializerBeans : Created Filter initializer for bean 'characterEncodingFilter'; order=-2147483648, resource=class path resource [org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfiguration.class] 2018-03-18 02:40:58.051 DEBUG 16664 --- [ost-startStop-1] o.s.b.w.s.ServletContextInitializerBeans : Created Filter initializer for bean 'hiddenHttpMethodFilter'; order=-10000, resource=class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.class] 2018-03-18 02:40:58.052 DEBUG 16664 --- [ost-startStop-1] o.s.b.w.s.ServletContextInitializerBeans : Created Filter initializer for bean 'httpPutFormContentFilter'; order=-9900, resource=class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.class] 2018-03-18 02:40:58.052 DEBUG 16664 --- [ost-startStop-1] o.s.b.w.s.ServletContextInitializerBeans : Created Filter initializer for bean 'requestContextFilter'; order=-105, resource=class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class] 2018-03-18 02:40:58.052 DEBUG 16664 --- [ost-startStop-1] o.s.b.w.s.ServletContextInitializerBeans : Created Filter initializer for bean 'httpTraceFilter'; order=2147483637, resource=class path resource [org/springframework/boot/actuate/autoconfigure/trace/http/HttpTraceAutoConfiguration$ServletTraceFilterConfiguration.class] 2018-03-18 02:40:58.065 INFO 16664 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/] 2018-03-18 02:40:58.070 INFO 16664 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2018-03-18 02:40:58.071 INFO 16664 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2018-03-18 02:40:58.072 INFO 16664 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2018-03-18 02:40:58.072 INFO 16664 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2018-03-18 02:40:58.072 INFO 16664 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpTraceFilter' to: [/*] 2018-03-18 02:40:58.073 INFO 16664 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'webMvcMetricsFilter' to: [/*] 2018-03-18 02:40:58.090 DEBUG 16664 --- [ost-startStop-1] o.s.b.w.s.f.OrderedRequestContextFilter : Initializing filter 'requestContextFilter' 2018-03-18 02:40:58.092 DEBUG 16664 --- [ost-startStop-1] o.s.b.w.s.f.OrderedRequestContextFilter : Filter 'requestContextFilter' configured successfully 2018-03-18 02:40:58.095 DEBUG 16664 --- [ost-startStop-1] o.s.b.a.m.w.servlet.WebMvcMetricsFilter : Initializing filter 'webMvcMetricsFilter' 2018-03-18 02:40:58.096 DEBUG 16664 --- [ost-startStop-1] o.s.b.a.m.w.servlet.WebMvcMetricsFilter : Filter 'webMvcMetricsFilter' configured successfully 2018-03-18 02:40:58.097 DEBUG 16664 --- [ost-startStop-1] .b.w.s.f.OrderedHttpPutFormContentFilter : Initializing filter 'httpPutFormContentFilter' 2018-03-18 02:40:58.097 DEBUG 16664 --- [ost-startStop-1] .b.w.s.f.OrderedHttpPutFormContentFilter : Filter 'httpPutFormContentFilter' configured successfully 2018-03-18 02:40:58.097 DEBUG 16664 --- [ost-startStop-1] .s.b.w.s.f.OrderedHiddenHttpMethodFilter : Initializing filter 'hiddenHttpMethodFilter' 2018-03-18 02:40:58.098 DEBUG 16664 --- [ost-startStop-1] .s.b.w.s.f.OrderedHiddenHttpMethodFilter : Filter 'hiddenHttpMethodFilter' configured successfully 2018-03-18 02:40:58.098 DEBUG 16664 --- [ost-startStop-1] s.b.w.s.f.OrderedCharacterEncodingFilter : Initializing filter 'characterEncodingFilter' 2018-03-18 02:40:58.099 DEBUG 16664 --- [ost-startStop-1] s.b.w.s.f.OrderedCharacterEncodingFilter : Filter 'characterEncodingFilter' configured successfully 2018-03-18 02:40:58.099 DEBUG 16664 --- [ost-startStop-1] o.s.b.a.w.trace.servlet.HttpTraceFilter : Initializing filter 'httpTraceFilter' 2018-03-18 02:40:58.099 DEBUG 16664 --- [ost-startStop-1] o.s.b.a.w.trace.servlet.HttpTraceFilter : Filter 'httpTraceFilter' configured successfully 2018-03-18 02:40:58.265 INFO 16664 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... 2018-03-18 02:40:58.836 INFO 16664 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. 2018-03-18 02:40:58.917 INFO 16664 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default' 2018-03-18 02:40:58.937 INFO 16664 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [ name: default ...] 2018-03-18 02:40:59.046 INFO 16664 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.2.14.Final} 2018-03-18 02:40:59.048 INFO 16664 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found 2018-03-18 02:40:59.100 INFO 16664 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final} 2018-03-18 02:40:59.251 INFO 16664 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect 2018-03-18 02:41:00.092 WARN 16664 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory 2018-03-18 02:41:00.094 INFO 16664 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated... 2018-03-18 02:41:00.106 INFO 16664 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed. 2018-03-18 02:41:00.111 INFO 16664 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2018-03-18 02:41:00.135 DEBUG 16664 --- [ restartedMain] o.s.boot.devtools.restart.Restarter : Creating new Restarter for thread Thread[main,5,main] 2018-03-18 02:41:00.135 DEBUG 16664 --- [ restartedMain] o.s.boot.devtools.restart.Restarter : Immediately restarting application 2018-03-18 02:41:00.136 DEBUG 16664 --- [ restartedMain] o.s.boot.devtools.restart.Restarter : Created RestartClassLoader org.springframework.boot.devtools.restart.classloader.RestartClassLoader@20f4e97e 2018-03-18 02:41:00.136 DEBUG 16664 --- [ restartedMain] o.s.boot.devtools.restart.Restarter : Starting application com.owozniak.bigdataproject.BigDataProjectApplication with URLs [file:/home/oscar/IdeaProjects/big-data-project/out/production/classes/, file:/home/oscar/IdeaProjects/big-data-project/out/production/resources/] Process finished with exit code 0 ``` Server is working when I remove all of annotations acording spring data jpa (@Entity, @OneToMay etc)<issue_comment>username_1: If you are using MySQL database, you might be facing the following problem: <https://hibernate.atlassian.net/browse/HHH-10490> Change the following line: ``` properties.setProperty("hibernate.default_schema", defaultSchema); ``` to: ``` properties.setProperty("hibernate.default_catalog", defaultSchema); ``` Note that you might want to change the attribute name from "defaultSchema" to "defaultCatalog" as well. Upvotes: 0 <issue_comment>username_2: I "solved" it by changing gradle to maven Upvotes: 1 <issue_comment>username_3: this can be related to your issue: [spring boot discussion](https://github.com/spring-projects/spring-boot/issues/14187) [spring boot github issue](https://github.com/spring-projects/spring-boot/issues/12457) You can also debug SpringApplication#reportFailure in the end (after catch (throwable)) it has generic logging of any error: ``` logger.error("Application run failed", ex) ``` In my case I had the logger from commons-logging which prevented logging to happen. Upvotes: -1 <issue_comment>username_4: APPLICATION FAILED TO START --- Description: ``` Field studentServiceImpl in com.edubridge.springbootpostman.controller.HomeController required a bean of type 'com.edubridge.springbootpostman.serviceimpl.StudentServiceImpl' that could not be found. The injection point has the following annotations: - @org.springframework.beans.factory.annotation.Autowired(required=true) Action: Consider defining a bean of type 'com.edubridge.springbootpostman.serviceimpl.StudentServiceImpl' in your configuration. ``` Either you are missing `@Component/@Service` on your `StudentServiceImpl/interface` respectively or missing to define a `bean` in your `Configuration` file Upvotes: -1
2018/03/18
969
3,964
<issue_start>username_0: I want to save my data in table order by time that they insert, but in SQL Server they will order by primary key. What can I do ?<issue_comment>username_1: You would have to make the date/time the primary key then, which is a bad idea. If the table has an auto-incrementing primary key then it will always be in that order when you view the table. But in the end, it really doesn't matter how it is stored, because when you query the table you can order it any way you wish. Just add a ORDER BY ASC/DESC Upvotes: 1 <issue_comment>username_2: I recommend making the primary key an identity column: ``` create table t ( t_id int identity(1, 1) primary key, . . . ); ``` This will do exactly what you want. By default, SQL Server clusters tables on the primary key, and an identity column increments with each update. Note that although the data pages are sorted, the results of a query are still in arbitrary order, unless you use an `order by` clause in the query. Such an identity column is much more efficient for inserts than an arbitrary key. You can make the key you have now `unique` and `not null` -- all the good benefits of a primary key, without the bad effects of having to re-arrange the data pages on each insert (the unique index is a different matter). The *default* behavior of SQL Server is to cluster the data using the primary key. You can override this. For example, this makes `not_pk` the clustered index: ``` create table t ( id uniqueidentifier primary key default newid(), created_at datetime default getdate(), not_pk int identity(1, 1) unique clustered ); ``` I would not use just the `created_at` value as the clustered index -- you might insert more than one row at a given point in time. Or, you can remove the clustering from the primary key explicitly: ``` create table t ( id uniqueidentifier primary key nonclustered default newid(), created_at datetime default getdate() ); ``` Upvotes: 1 <issue_comment>username_3: So there are two factors here which you may be confounding; the *physical* ordering of the data (i.e how your computer literally prints the bits onto your hard drive) and the *logical* ordering. The physical ordering is always defined by your *clustered index*. 9 times out of 10, this also happens to be your primary key, but it doesn't have to be. Think of "Clustered Index" as "How it's physically sorted on my disk". You want it stored a different way, change how you "cluster" it (by the way, if you don't have a clustered index, that's called a "heap", and it doesn't guarantee the physical order of the data). The *logical* ordering however, does not exist. SQL is based on relational algebra, and relational algebra operates on mathematical sets. The definition of a set contains *no information* about the inherent ordering of the set, only it's constituents. Now when you query data out, you can specify an `order by` which will return the data to you in the order you asked for. However by default, there is no guarantee or assumption of any ordering (even that of how it's physically stored on disk; even if it happens to return in that order from time to time). Upvotes: 3 [selected_answer]<issue_comment>username_4: **Please use ORDER BY to on your selects if you want a specific ordering.** By database theory definition the rows in a table are not sorted. You need to specify the sort order using ORDER BY when retrieving thw rows (using a SELECT). Now, if you don't specify the ORDER BY and just trust that SQL Server returns them by PK you can be for a big surprise, since this is not safe. By default SQL Server does this since the tables are clustered. But... if later on someone changes the clustering of the table or removes it, all your queries without ORDER BY are going to be wrong, right away. Yep, you could be in trouble. **So again, please use ORDER BY to on your selects if you want a specific ordering.** Upvotes: 0
2018/03/18
418
1,297
<issue_start>username_0: I'm studying how to use mongoDB. I want to update a certain field of a document but it overwrites the whole document. How can I update only the field in a document I want to modify? ``` db.products.find({_id: 1}) { "_id" : 1.0, "name" : "aaa", "category" : "toy", "price" : 100.0 } ``` For example, I have a document like this. ``` db.products.update({_id: 1}, {price:999}) db.products.find({_id: 1}) { "_id" : 1.0, "price" : 999.0 } ``` When I update like this, I get this result. I lost name field and category field after executing update command.<issue_comment>username_1: Use the operator [$set](https://docs.mongodb.com/manual/reference/operator/update/set/) ``` $ db.products.update({_id: 1}, {$set: {price:999}}) ``` This operator allows you update the specified field(s). Upvotes: 4 [selected_answer]<issue_comment>username_2: Using the `$set` operator, you should be able to update only the column that you want to modify or else it will overwrite the whole document. You can follow more about the usage of `$set` operator [here](http://www.mongodb.org/display/DOCS/Updating#Updating-%24set) Finally your update query should be something as like this: ``` db.products.update({_id: 1}, {$set: {price:999}}) ``` Upvotes: 2
2018/03/18
740
2,445
<issue_start>username_0: I have spent hours trying to figure this out, so I apologize if it's an easy fix. I would like to make this program more user-friendly. Everything works currently, but the sentinel requires I enter "0" for both miles drive and gas used. I would like the sentinel to end the program after I enter the "0" for miles only. Is this possible? ``` import java.util.Scanner; public class Mileage ``` { ``` public static void main(String[] args) { //initialization Scanner sc = new Scanner(System.in); int miles = -1, gallons = -1, totalMiles = 0, totalGallons = 0; double average, runningAverage; //while loop with sentinel controlled repetition while (miles != 0 && gallons != 0) { //get miles System.out.println("Enter the amount of miles driven. (0 to exit)"); miles = sc.nextInt(); //get gallons System.out.println("Enter the amount of gallons used. (0 to exit)"); gallons = sc.nextInt(); //calc average average = (double) miles / gallons; //calc running average totalMiles += miles; totalGallons += gallons; runningAverage = (double) totalMiles / totalGallons; //output average only if values were entered, by using if statement if (miles != 0 && gallons != 0) { System.out.printf("Miles per gallon for this trip is %.1f%n", average); System.out.printf("Running average miles per gallon is %.1f%n", runningAverage); } } } ``` }<issue_comment>username_1: *I would like the sentinel to end the program after I enter the "0" for miles only.* If I understand what you're asking for, just change ``` while (miles != 0 && gallons != 0) ``` to ``` while (miles != 0) ``` **and** ``` System.out.println("Enter the amount of gallons used. (0 to exit)"); ``` to ``` System.out.println("Enter the amount of gallons used."); ``` You may find it more convenient to terminate the loop on `0` miles. Like, ``` miles = sc.nextInt(); if (miles == 0) { break; } ``` Otherwise, it's going to prompt for `gallons` again. Upvotes: 0 <issue_comment>username_2: When you do: ``` miles = sc.nextInt(); ``` you can make a check for exit the program like: ``` if(miles==0){ System.exit(0); } ``` just before: ``` System.out.println("Enter the amount of gallons used. (0 to exit)"); ``` Upvotes: 2 [selected_answer]
2018/03/18
600
2,171
<issue_start>username_0: My assignment is essentially to ask the user "how many numbers do you want to enter" then if the user, for example, enters 2 number it says which is the highest number. What I'm having trouble with is comparing those numbers since they are in a loop. ``` cout<<"how many #s do you want to enter?" cin>>number; for(int i=1; i<=number; i++){ cout<<"Input number: "; } if ( **first number** > **second number**) cout<<"First number is bigger"; else cout<<"Second number is bigger"; ``` Is it possible to compare the numbers that result in the loop? If not, is there a simple way to do a process similar to this?<issue_comment>username_1: Your question wasn't very clear, but I'll guess you want a code that returns the greatest number that the user entered. As someone suggested in the comments, you can keep track of the greatest in each iteration: ``` #include using namespace std; int main() { int how\_many; cout << "How many #s do you want to enter?" << endl; cin >> how\_many; int max\_so\_far = 42; // Ha for (int i = 0; i < how\_many; i++) { int input; cout<<"Input number: "; cin >> input; if (i == 0 || input>max\_so\_far) { // if it's the first number or it's greater than max\_so\_far max\_so\_far = input; } } cout << "The biggest number was " << max\_so\_far << endl; return 0; } ``` Note that the variable 'max\_so\_far' holds nothing important in the first iteration (no number was yet seen). You can check if it's the first iteration, as I did, or you can initialize 'max\_so\_far' a minus infinity (lowest number you can represent on that type, an 'int' in this case). Upvotes: 1 <issue_comment>username_2: Firstly, your comparison occurs outside the for-loop; you should move it inside the loop to compare all the numbers. Secondly, you are not even saving the user input. You want to create a variable `max`, for example, and set it to zero. Then, in the for-loop, compare every input value to the value in `max`, and if it is bigger, then set `max` to that value. And to answer your question, yes, you can compare numbers that result in a loop or nest of loops *inside* the loop. Upvotes: 0
2018/03/18
394
1,125
<issue_start>username_0: Using xpath, how can I get all anchor tags except the ones in italics from the second paragraph? (Question and example has been simplified. Imagine a regular HTML page with multiple and ). ``` [A](a.html) **[B](b.html)** *[C](c.html)* **[E](e.html)** [F](f.html) *[G](g.html)* ``` Should get: What I have: ``` root.xpath('//body//p')[1].xpath('a[not(self::i)]') ``` I am only getting: ``` `[`](f.html) ```<issue_comment>username_1: As [@username_2 commented](https://stackoverflow.com/users/4549554/andersson), it's unclear where your `a` elements are supposed to end. Assuming that your `a` elements are meant to be self-closing, ``` ``` Then this XPath, ``` /html/body/p[2]//a[not(parent::i)] ``` selects all of the `a` descendents of the second paragraph whose parent is not an `i` element: ``` ``` Credit: Thanks to @username_2 for a correction. Please upvote [his answer](https://stackoverflow.com/a/49346236/290085). Thanks. Upvotes: 1 <issue_comment>username_2: Try below XPath to get required output: ``` //p[2]//a[not(parent::i)] ``` Upvotes: 3 [selected_answer]
2018/03/18
684
2,236
<issue_start>username_0: I would like to find all subsets of a sorted string, disregarding order and which characters are next to each other. I think the best way for this to be explained is though an example. The results should also be from longest to shortest. These are the results for `bell`. ``` bell bel bll ell be bl el ll b e l ``` I have thought of ways to do this, but none for any length of input. Thank you!<issue_comment>username_1: Here is one way using `itertools.combinations`. If the order for strings of same length is important, see [@TimPeters' answer](https://stackoverflow.com/a/49343794/9209546). ``` from itertools import combinations mystr = 'bell' res = sorted({''.join(sorted(x, key=lambda j: mystr.index(j))) for i in range(1, len(mystr)+1) for x in combinations(mystr, i)}, key=lambda k: -len(k)) # ['bell', 'ell', 'bel', 'bll', 'be', 'll', 'bl', 'el', 'l', 'e', 'b'] ``` **Explanation** * Find all combinations of length in `range(1, len(mystr)+1)`. * Sort by original string via `key` argument of `sorted`. *This step may be omitted if not required.* * Use set of `''.join` on elements for unique strings. * Outer `sorted` call to go from largest to smallest. Upvotes: 2 <issue_comment>username_2: There are generally two ways to approach such things: generate "everything" and weed out duplicates later, or create custom algorithms to avoid generating duplicates to begin with. The former is almost always easier, so that's what I'll show here: ``` def gensubsets(s): import itertools for n in reversed(range(1, len(s)+1)): seen = set() for x in itertools.combinations(s, n): if x not in seen: seen.add(x) yield "".join(x) for x in gensubsets("bell"): print(x) ``` That prints precisely what you said you wanted, and how it does so should be more-than-less obvious. Upvotes: 4 [selected_answer]<issue_comment>username_3: You can try in one line: ``` import itertools data='bell' print(set(["".join(i) for t in range(len(data)) for i in itertools.combinations(data,r=t) if "".join(i)!=''])) ``` output: ``` {'bel', 'bll', 'ell', 'el', 'be', 'bl', 'e', 'b', 'l', 'll'} ``` Upvotes: -1
2018/03/18
1,472
3,932
<issue_start>username_0: I am trying to write C code that will have an effect equivalent to the following assembly code: ``` addq %rsi, %rdi imulq %rdx, %rdi movq %rdi, %rax sarq $15, %rax salq $31, %rax andq %rdi, %rax ret ``` With a function prototype long decode(long x, long y, long z) Parameters x, y, and z are passed in registers %rdi, %rsi, and %rdx. The code stores the return value in register %rax. So far I have the following C code: ``` long decode(long x, long y, long z) { long w; x = x+y; x = x*z; w = x; w = ((x>>15)<<31); return x&w } ``` Which, when compiled with the gcc -O2 -S -c filename.c produces the following: ``` addq %rdi, %rsi imulq %rdx, %rsi movq %rsi, %rax sarq $15, %rax salq $31, %rax andq %rsi, %rax ret ``` Apparently, the registers %rdi and %rsi are swapped. So, if I change the function by swapping x and y, it looks like this: ``` long decode4(long x, long y, long z) { long w; y = x + y; y = y * z; w = y; w = ((y>>15)<<31); return y&w } ``` And, again the assembly looks like this: ``` addq %rdi, %rsi imulq %rdx, %rsi movq %rsi, %rax sarq $15, %rax salq $31, %rax andq %rsi, %rax ret ``` The swapping of y and x, did not change a thing in the assembly code produced. Any ideas of how to fix that issue? Thanks!<issue_comment>username_1: The compiler has optimized your code so you don't see any difference in assembly code after swapping x and y. Your code is treated as below by the compiler, ``` long decode4(long x, long y, long z) { long w; // y = x + y; // y = y * z; // w = y; // The above three lines are combined as x = (x + y)*z; // result of addition and multiplication in rsi w = x; // move the above result to rax //w = ((y>>15)<<31); //return y&w //The above two lines are treated as w = ((w>>15)<<31); // shift operations on rax return x&w // rax and rsi } ``` Change in x or y is not going to affect the intended behaviour of this function so the compiler has optimized it. Hope this helps you. You can also try compiling your code with optimization O0 (no optimization) then you can see change in assembly code as you expected. Upvotes: 1 <issue_comment>username_2: There really isn't anything wrong with your interpretation of the code: ``` long decode(long x, long y, long z) { long w; x = x+y; x = x*z; w = x; w = ((x>>15)<<31); return x&w } ``` It could be simplified a bit, but there isn't anything wrong with it given that the output is different only in the reversal of the registers used. The observable result would be the same. You state this requirement: > > I am trying to write C code that will have an effect **equivalent** to the following assembly > > > The two are **equivalent** so I believe the assignment has been satisfied by your solution. --- Some times this type of thing can come down to the compiler used. I noticed that I can get the exact output you are looking for with GCC 4.6.4 and `-O2` optimization level. You can play with this code on [godbolt](http://long%20decode(long%20x,%20long%20y,%20long%20z)%20%7B%20%20%20long%20w;%20%20%20%20x%20=%20x+y;%20%20%20x%20=%20x*z;%20%20%20%20w%20=%20x;%20%20%20w%20=%20((x%3E%3E15)%3C%3C31);%20%20%20%20return%20x&w;%20%20%7D%20%20long%20decode2(long%20x,%20long%20y,%20long%20z)%20%7B%20%20%20x%20=%20(x%20+%20y)%20*%20z;%20%20%20return%20x%20&%20((x%20%3E%3E%2015)%20%3C%3C%2031);%20%7D) where the output is: ``` decode: addq %rsi, %rdi imulq %rdx, %rdi movq %rdi, %rax sarq $15, %rax salq $31, %rax andq %rdi, %rax ret ``` This seems to be an exact match with your course's output. Using the same version of GCC (4.6.4) you can get the same output with: ``` long decode(long x, long y, long z) { x = (x + y) * z; return x & ((x >> 15) << 31); } ``` Upvotes: 3 [selected_answer]
2018/03/18
552
1,955
<issue_start>username_0: CustomerID, is unique. What result is given with this question? ``` SELECT personalnumber, Amount = Count(CustomerID), FROM Customer GROUP BY personalnumber HAVING Count(CustomerID) > 100 ``` What does it mean that having count(CustomerID) > 100?? Is it that the CustomerID has to be above 100?<issue_comment>username_1: It means that the `personalnumber` has more than 100 associated `CustomerID`'s Upvotes: 1 <issue_comment>username_2: It means that the `personalnumber`s returned by the query are on more than 100 rows where `CustomerId` is not null. If the code just wanted to count rows, I would recommend: ``` having count(*) > 100 ``` This doesn't depend on the nullability of a column. If `customerid` could be duplicated and you wanted to check for 100 *different* values, then you would use: ``` having count(distinct CustomerId) > 100 ``` If you were filtering on `CustomerId`, you would use a `where` clause before the `group by`. Upvotes: 1 <issue_comment>username_3: You have been given two answers, but now you've edited your request without accepting one of them. So I guess you haven't understood the answers given so far. ``` GROUP BY personalnumber ``` means that you want one result row per `personalnumber`. All records for one `personalnumber` get aggregated to a single row. ``` Count(CustomerID) ``` counts all occurrences where `CustomerID` is not null. ``` HAVING Count(CustomerID) > 100 ``` limits your result to those `personalnumber` that have more than 100 records with a `CustomerID`. As this is the `Customer` table, we must assume that `CustomerID` is the table's ID, uniquely identifying a record, and it can't be null. So this should better be written as ``` HAVING Count(*) > 100 ``` meaning just the same: limit the result to those `personalnumber` that occur in more than 100 records. (`Count(*)` means: count rows.) Upvotes: 3 [selected_answer]
2018/03/18
775
2,758
<issue_start>username_0: I have created a network using high level tf APIs such as tf.estimator. Training and evaluating work fine and produce an output. However when predicting on new data, `get_inputs()` requires `label_data` and `batch_size`. The error is: `TypeError: get_inputs() missing 2 required positional arguments: 'label_data' and 'batch_size'` How can I resolve this so I can make a prediction? Here is my code: ``` predictTest = [0.34, 0.65, 0.88] ``` predictTest is just a test and won't be my real prediction data. get\_inputs(), this is where the error is thrown. ``` def get_inputs(feature_data, label_data, batch_size, n_epochs=None, shuffle=True): dataset = tf.data.Dataset.from_tensor_slices( (feature_data, label_data)) dataset = dataset.repeat(n_epochs) if shuffle: dataset = dataset.shuffle(len(feature_data)) dataset = dataset.batch(batch_size) features, labels = dataset.make_one_shot_iterator().get_next() return features, labels ``` Prediction inputs: ``` def predict_input_fn(): return get_inputs( predictTest, n_epochs=1, shuffle=False ) ``` Predicting: ``` predict = estimator.predict(predict_input_fn) print("Prediction: {}".format(list(predict))) ```<issue_comment>username_1: The testing of any model has two types. 1) you want accuracy, recall etc. you need to provide a label for the test data. if you don't provide label it will give you an error. 2) you just want to test your model without calculating the accuracy than you don't need a label but here the prediction will be different. Upvotes: 0 <issue_comment>username_2: I worked out that I must create a new `get_inputs()` function for the prediction. If I use the `get_inputs()` that train and evaluate use, it is expecting data it won't get. `get_inputs`: ``` def get_inputs(feature_data, label_data, batch_size, n_epochs=None, shuffle=True): dataset = tf.data.Dataset.from_tensor_slices( #from_tensor_slices (feature_data, label_data)) dataset = dataset.repeat(n_epochs) if shuffle: dataset = dataset.shuffle(len(feature_data)) dataset = dataset.batch(batch_size) features, labels = dataset.make_one_shot_iterator().get_next() return features, labels ``` Make a new function called pred\_get\_inputs that doesn't require `label_data` or `batch_size`: ``` def get_pred_inputs(feature_data,n_epochs=None, shuffle=False): dataset = tf.data.Dataset.from_tensor_slices( #from_tensor_slices (feature_data)) dataset = dataset.repeat(n_epochs) if shuffle: dataset = dataset.shuffle(len(feature_data)) dataset = dataset.batch(1) features = dataset return features ``` Upvotes: 2 [selected_answer]
2018/03/18
1,264
3,383
<issue_start>username_0: I am using MPLAB to perform an operation on PIC kit 14f458. Now I want to create a code to pass the different amount of voltage supply LED through the Microcontroller using a button. When button pressed the first time I should get waveform with 10% DC, for second and third time, 50% and 95% respectively. I have worked on this But still getting Values OF RE2 PORT as 0 rather than 1. And I also don't know how to stop timer while I release the button. My code is as follow: ``` #include //Standard I/O Library #include //for TRISA,E and PORTA,E declaration #pragma config WDT = OFF //watchdog counter #pragma config OSC = HS, OSCS = OFF #pragma config PWRT = OFF, BOR = ON, BORV = 45 #pragma config DEBUG = OFF, LVP = OFF, STVR = OFF void timer\_10() { CCP1CON = 0; PR2 = 249; CCPR1L = 24; TRISCbits.TRISC2 = 0; T2CON = 0x00; CCP1CON = 0x3c; TMR2 = 0; T2CONbits.TMR2ON = 1; while(1) { PIR1bits.TMR2IF = 0; while(PIR1bits.TMR2IF == 0); } } void timer\_50() { CCP1CON = 0; PR2 = 249; CCPR1L = 124; TRISCbits.TRISC2 = 0; T2CON = 0x00; CCP1CON = 0x2c; TMR2 = 0; T2CONbits.TMR2ON = 1; while(1) { PIR1bits.TMR2IF = 0; while(PIR1bits.TMR2IF == 0); } } void timer\_95() { CCP1CON = 0; PR2 = 249; CCPR1L = 236; TRISCbits.TRISC2 = 0; T2CON = 0x00; CCP1CON = 0x2c; TMR2 = 0; T2CONbits.TMR2ON = 1; while(1) { PIR1bits.TMR2IF = 0; while(PIR1bits.TMR2IF == 0); } } void main() { int i = 1; ADCON1 = 0x06; //Sets RA0 to digital mode CMCON = 0x07; TRISEbits.TRISE2 = 1; //set E2 PORTE pins as input PORTEbits.RE2 = 1; //Here I am not able to SET Value 1 while(1) { while(PORTEbits.RE2 == 0) { switch(i) { case 1: timer\_10(); break; case 2: timer\_50(); break; case 3: timer\_95(); break; } if(i<4) { i++; if(i>=4) { i=1; } } } } } ``` And My compiler Get Stuck in function timer\_10(). Please help me.<issue_comment>username_1: The testing of any model has two types. 1) you want accuracy, recall etc. you need to provide a label for the test data. if you don't provide label it will give you an error. 2) you just want to test your model without calculating the accuracy than you don't need a label but here the prediction will be different. Upvotes: 0 <issue_comment>username_2: I worked out that I must create a new `get_inputs()` function for the prediction. If I use the `get_inputs()` that train and evaluate use, it is expecting data it won't get. `get_inputs`: ``` def get_inputs(feature_data, label_data, batch_size, n_epochs=None, shuffle=True): dataset = tf.data.Dataset.from_tensor_slices( #from_tensor_slices (feature_data, label_data)) dataset = dataset.repeat(n_epochs) if shuffle: dataset = dataset.shuffle(len(feature_data)) dataset = dataset.batch(batch_size) features, labels = dataset.make_one_shot_iterator().get_next() return features, labels ``` Make a new function called pred\_get\_inputs that doesn't require `label_data` or `batch_size`: ``` def get_pred_inputs(feature_data,n_epochs=None, shuffle=False): dataset = tf.data.Dataset.from_tensor_slices( #from_tensor_slices (feature_data)) dataset = dataset.repeat(n_epochs) if shuffle: dataset = dataset.shuffle(len(feature_data)) dataset = dataset.batch(1) features = dataset return features ``` Upvotes: 2 [selected_answer]
2018/03/18
634
2,551
<issue_start>username_0: I would like to generate random terms based on some sort of "context" and I was wondering if this is possible using quickcheck. Basically I would like to have an additional data type passed around so that the arbitrary function can generate terms based on the additional parameter... Is this possible with quickcheck or should I just write my own definition of Gen?<issue_comment>username_1: It's possible, though not really sane, to do this from within `arbitrary`. But if you step out of `arbitrary`, you can *literally* just pass an extra parameter around. ``` -- do whatever you want inside the implementation of these two chooseIntRange :: Context -> Int updateContext :: Int -> Context -> Context arbitraryIntWithContext :: Context -> Gen (Context, Int) arbitraryIntWithContext ctx = do n <- choose (0, chooseIntRange ctx) return (n, updateContext n ctx) ``` The plumbing of the context can be relieved somewhat with `StateT`, e.g. ``` -- do whatever you want inside the implementation of this chooseIntRangeAndUpdate :: MonadState Context m => m Int arbitraryIntStateT :: StateT Context Gen Int arbitraryIntStateT = do hi <- chooseIntRangeAndUpdate lift (choose (0, hi)) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: While username_1 has supplied a fine answer for QuickCheck (+1), it also highlights one of QuickCheck's weaknesses. In QuickCheck, one writes properties using instances of `Arbitrary`, but due to its design, `Arbitrary` isn't monadic. The workaround that username_1 shares is that `Gen`, on the other hand, *is* monadic, so that you can write context-dependent code using `do` notation. The disadvantage is that while you can convert a `Gen a` to an `Arbitrary a`, you'll either have to provide a custom `shrink` implementation, or forgo shrinking. An alternative library for property-based testing, [Hedgehog](https://hackage.haskell.org/package/hedgehog), is designed in such a way that properties themselves are monadic, which means you'd be able to write an entire property and simply embed ad-hoc context-specific value generation (including shrinking) in the test code itself: ``` propWithContext :: Property propWithContext = property $ do ctx <- forAll genContext n <- forAll $ Gen.integral $ Range.linear 0 $ chooseIntRange ctx let ctx' = updateContext n ctx -- Exercise SUT and verify result here... ``` Here, `genContext` is a custom generator for the `Context` type, with the type ``` genContext :: MonadGen m => m Context ``` Upvotes: 1
2018/03/18
329
798
<issue_start>username_0: I need to get the following equation echoed to the command line, and also saved into a variable. So far I have failed to do either. 5^0.16 What I have tried. ``` echo 'e(l(5)*.16)' | bc -l ``` as well as ``` echo 'e(l(5)*.16)' | bc -l | read wcEXP ```<issue_comment>username_1: How about ```sh wcExp=$(echo 'e(l(5)*.16)' | bc -l) echo "$wcExp" ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: If you use Bash, you can use `tee` to copy the output to standard error: ``` res=$(bc -l <<< 'e(l(5)*.16)' | tee /dev/stderr) ``` This will print the output of the `bc` command, and also store it in `res`: ``` $ res=$(bc -l <<< 'e(l(5)*.16)' | tee /dev/stderr) 1.29370483333398597850 $ declare -p res declare -- res="1.29370483333398597850" ``` Upvotes: 2
2018/03/18
743
1,945
<issue_start>username_0: how to fix padding behavior for element with more than 100% width? indent on the right side of table collapses ```css * { box-sizing: border-box; margin: 0; padding: 0; } body { padding: 30px; } table { border-collapse: collapse; width: 150%; } th, td { border: 1px solid #000; } ``` ```html | sdsfd | sdsfd | sdsfd | sdsfd | | --- | --- | --- | --- | | sdsdf | sdsdf | sdsdf | sdsdf | ```<issue_comment>username_1: the `150%` width is always gonna be relative to the `parent`'s width, so if the `parent` grows ( adding padding ) the `child` will grow accordingly and will end up outside because `50%` of the parent's width is bigger than the `padding` , you could do this by putting the `table` in a wrapper like : ```css * { box-sizing: border-box; margin: 0; padding: 0; } body { } #wrapper{ padding: 30px; width: 150%; } table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #000; } ``` ```html | sdsfd | sdsfd | sdsfd | sdsfd | | --- | --- | --- | --- | | sdsdf | sdsdf | sdsdf | sdsdf | ``` i don't know if this is what you're looking for but i hope it'll help :) Upvotes: 0 <issue_comment>username_2: Here is an idea using border instead of padding: ```css * { box-sizing: border-box; margin: 0; padding: 0; } body { padding: 30px 0; } table { border-collapse: collapse; width: 150%; border-right:30px solid #fff; border-left:30px solid #fff; position:relative; } table:before { content:""; position:absolute; top:0; bottom:0; left:15px; width:1px; background:#000; } table:after { content:""; position:absolute; top:0; bottom:0; right:15px; width:1px; background:#000; } th, td { border: 1px solid #000; } ``` ```html | sdsfd | sdsfd | sdsfd | sdsfd | | --- | --- | --- | --- | | sdsdf | sdsdf | sdsdf | sdsdf | ``` Upvotes: 2
2018/03/18
2,197
3,376
<issue_start>username_0: I have the following script: ``` curl -s -S 'https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=BTC-NBT&tickInterval=thirtyMin&_=1521347400000' | jq -r '.result|.[] |[.T,.O,.H,.L,.C,.V,.BV] | @tsv | tostring | gsub("\t";",") | "(\(.))"' ``` This is the output: ``` (2018-03-17T18:30:00,0.00012575,0.00012643,0.00012563,0.00012643,383839.45768188,48.465051) (2018-03-17T19:00:00,0.00012643,0.00012726,0.00012642,0.00012722,207757.18765437,26.30099514) (2018-03-17T19:30:00,0.00012726,0.00012779,0.00012698,0.00012779,97387.01596624,12.4229077) (2018-03-17T20:00:00,0.0001276,0.0001278,0.00012705,0.0001275,96850.15260027,12.33316229) ``` I want to replace the date with timestamp. I can make this conversion with date in the shell ``` date -d '2018-03-17T18:30:00' +%s%3N 1521325800000 ``` I want this result: ``` (1521325800000,0.00012575,0.00012643,0.00012563,0.00012643,383839.45768188,48.465051) (1521327600000,0.00012643,0.00012726,0.00012642,0.00012722,207757.18765437,26.30099514) (1521329400000,0.00012726,0.00012779,0.00012698,0.00012779,97387.01596624,12.4229077) (1521331200000,0.0001276,0.0001278,0.00012705,0.0001275,96850.15260027,12.33316229) ``` This data is stored in MySQL. Is it possible to execute the date conversion with jq or another command like awk, sed, perl in a single command line?<issue_comment>username_1: Here is an all-jq solution that assumes the "Z" (UTC+0) timezone. In brief, simply replace `.T` by: ``` ((.T + "Z") | fromdate | tostring + "000") ``` To verify this, consider: ### timestamp.jq ``` [splits("[(),]")] | .[1] |= ((. + "Z")|fromdate|tostring + "000") # milliseconds | .[1:length-1] | "(" + join(",") + ")" ``` ### Invocation ``` jq -rR -f timestamp.jq input.txt ``` ### Output ``` (1521311400000,0.00012575,0.00012643,0.00012563,0.00012643,383839.45768188,48.465051) (1521313200000,0.00012643,0.00012726,0.00012642,0.00012722,207757.18765437,26.30099514) (1521315000000,0.00012726,0.00012779,0.00012698,0.00012779,97387.01596624,12.4229077) (1521316800000,0.0001276,0.0001278,0.00012705,0.0001275,96850.15260027,12.33316229) ``` Upvotes: 3 [selected_answer]<issue_comment>username_1: Here is an unportable awk solution. It is not portable because it relies on the system `date` command; on the system I'm using, the relevant invocation looks like: `date -j -f "%Y-%m-%eT%T" STRING "+%s"` ``` awk -F, 'BEGIN{OFS=FS} NF==0 { next } { sub(/\(/,"",$1); cmd="date -j -f \"%Y-%m-%eT%T\" " $1 " +%s"; cmd | getline $1; $1=$1 "000"; # milliseconds printf "%s", "("; print; }' input.txt ``` ### Output ``` (1521325800000,0.00012575,0.00012643,0.00012563,0.00012643,383839.45768188,48.465051) (1521327600000,0.00012643,0.00012726,0.00012642,0.00012722,207757.18765437,26.30099514) (1521329400000,0.00012726,0.00012779,0.00012698,0.00012779,97387.01596624,12.4229077) (1521331200000,0.0001276,0.0001278,0.00012705,0.0001275,96850.15260027,12.33316229) ``` Upvotes: 0 <issue_comment>username_2: Solution with sed : ``` sed -e 's/(\([^,]\+\)\(,.*\)/echo "(\$(date -d \1 +%s%3N),\2"/g' | ksh ``` test : ``` | sed -e 's/(\([^,]\+\)\(,.\*\)/echo "(\$(date -d \1 +%s%3N),\2"/g' | ksh ``` or : ``` > results\_curl.txt cat results\_curl.txt | sed -e 's/(\([^,]\+\)\(,.\*\)/echo "(\$(date -d \1 +%s%3N),\2"/g' | ksh ``` Upvotes: 0
2018/03/18
1,762
3,649
<issue_start>username_0: If you just use something like this: ``` \( \left[ \begin{matrix} 0 & 1 & 5 & 2 \\ 1 & -7 & 1 & 0 \\ 0 & 0 & 1 & 3 \end{matrix} \right] \) ``` the negative signs don't line up. [![enter image description here](https://i.stack.imgur.com/TvE9r.png)](https://i.stack.imgur.com/TvE9r.png) so what I've been doing is going through and adding in a `\phantom{-}` to offset the difference: ``` \( \left[ \begin{matrix} 0 & \phantom{-}1 & 5 & 2 \\ 1 & -7 & 1 & 0 \\ 0 & \phantom{-}0 & 1 & 3 \end{matrix} \right] \) ``` [![enter image description here](https://i.stack.imgur.com/nP5UG.png)](https://i.stack.imgur.com/nP5UG.png) That works for that one column but now the widths between the columns is different unless every column after the first one has at least one number with a negative sign. So I'm fixing that by giving them all a `\phantom{-}`: ``` \( \left[ \begin{matrix} 0 & \phantom{-}1 & \phantom{-}5 & \phantom{-}2 \\ 1 & -7 & \phantom{-}1 & \phantom{-}0 \\ 0 & \phantom{-}0 & \phantom{-}1 & \phantom{-}3 \end{matrix} \right] \) ``` [![enter image description here](https://i.stack.imgur.com/GLVbg.png)](https://i.stack.imgur.com/GLVbg.png) And that looks right to me but the way I'm doing it is extremely tedious. Is there a better way of doing this? Maybe I should write my own script to automate doing all that. This seems ideal to me: ``` 0 1 5 2; 1 -7 1 0; 0 0 1 3 ```<issue_comment>username_1: Here is an all-jq solution that assumes the "Z" (UTC+0) timezone. In brief, simply replace `.T` by: ``` ((.T + "Z") | fromdate | tostring + "000") ``` To verify this, consider: ### timestamp.jq ``` [splits("[(),]")] | .[1] |= ((. + "Z")|fromdate|tostring + "000") # milliseconds | .[1:length-1] | "(" + join(",") + ")" ``` ### Invocation ``` jq -rR -f timestamp.jq input.txt ``` ### Output ``` (1521311400000,0.00012575,0.00012643,0.00012563,0.00012643,383839.45768188,48.465051) (1521313200000,0.00012643,0.00012726,0.00012642,0.00012722,207757.18765437,26.30099514) (1521315000000,0.00012726,0.00012779,0.00012698,0.00012779,97387.01596624,12.4229077) (1521316800000,0.0001276,0.0001278,0.00012705,0.0001275,96850.15260027,12.33316229) ``` Upvotes: 3 [selected_answer]<issue_comment>username_1: Here is an unportable awk solution. It is not portable because it relies on the system `date` command; on the system I'm using, the relevant invocation looks like: `date -j -f "%Y-%m-%eT%T" STRING "+%s"` ``` awk -F, 'BEGIN{OFS=FS} NF==0 { next } { sub(/\(/,"",$1); cmd="date -j -f \"%Y-%m-%eT%T\" " $1 " +%s"; cmd | getline $1; $1=$1 "000"; # milliseconds printf "%s", "("; print; }' input.txt ``` ### Output ``` (1521325800000,0.00012575,0.00012643,0.00012563,0.00012643,383839.45768188,48.465051) (1521327600000,0.00012643,0.00012726,0.00012642,0.00012722,207757.18765437,26.30099514) (1521329400000,0.00012726,0.00012779,0.00012698,0.00012779,97387.01596624,12.4229077) (1521331200000,0.0001276,0.0001278,0.00012705,0.0001275,96850.15260027,12.33316229) ``` Upvotes: 0 <issue_comment>username_2: Solution with sed : ``` sed -e 's/(\([^,]\+\)\(,.*\)/echo "(\$(date -d \1 +%s%3N),\2"/g' | ksh ``` test : ``` | sed -e 's/(\([^,]\+\)\(,.\*\)/echo "(\$(date -d \1 +%s%3N),\2"/g' | ksh ``` or : ``` > results\_curl.txt cat results\_curl.txt | sed -e 's/(\([^,]\+\)\(,.\*\)/echo "(\$(date -d \1 +%s%3N),\2"/g' | ksh ``` Upvotes: 0
2018/03/18
536
1,676
<issue_start>username_0: Is theme a component in React Material UI which behaves like Bootstrap's ? I want it to have breakpoints (or at least a reasonable `max-width`). I'm pretty sure it doesn't matter, but I want to use it with an `AppBar` and a `Drawer`.<issue_comment>username_1: This is the css for bootstrap container. You can create one yourself and use it. ``` .container { padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; } @media (min-width: 768px) { .container { width: 750px; } } @media (min-width: 992px) { .container { width: 970px; } } @media (min-width: 1200px) { .container { width: 1170px; } } ``` referenced from <https://github.com/twbs/bootstrap/blob/master/dist/css/bootstrap.css> Upvotes: 2 <issue_comment>username_2: I personally have this implementation: ``` import { withStyles } from '@material-ui/core/styles'; const styles = theme => ({ container: { paddingRight: 15, paddingLeft: 15, marginRight: 'auto', marginLeft: 'auto', // Full width for (xs, extra-small: 0px or larger) and (sm, small: 600px or larger) [theme.breakpoints.up('md')]: { // medium: 960px or larger width: 920, }, [theme.breakpoints.up('lg')]: { // large: 1280px or larger width: 1170, }, [theme.breakpoints.up('xl')]: { // extra-large: 1920px or larger width: 1366, }, }, }); const MyContainer = () => ( {/\* Other stuff here \*/} ); export default withStyles(styles)(MyContainer); ``` You can change width for each breakpoint according to your wish. Upvotes: 2
2018/03/18
5,892
17,709
<issue_start>username_0: I'm trying to get a countdown timer to work on my web page, but its not working, and I can't figure out why. I don't know if its because I linked it wrong in my HTML or if its because I missed something in my code. Any help would be appreciate. ```js "use strict"; setInterval(function() { ... }, 1000); // 1000 milliseconds = 1 second // Function to display current date / time on the site setInterval(function displayTimeAndDate() { var today = new Date(); var hours = today.getHours(); var minutes = today.getMinutes(); var seconds = today.getSeconds(); var date = today.getDate(); var month = today.getMonth(); var year = today.getFullYear(); var amOrPm; // Check if it's a.m or p.m if (hours < 12) { amOrPm = "a.m"; } else { amOrPm = "p.m"; } document.getElementById('date').innerText = date + ":" + month + ":" + year; document.getElementById('time').innerText = hours + ":" + minutes + ":" + seconds + " " + amOrPm; }, 1000); setInterval(function countdown() { // Set the desired date (American date format: Month/Day/Year) to countdown to and the current date var endDate = new Date('07/04/2018 09:00 PM'); var currentDate = new Date(); // Get the "distance" between the dates var distance = endDate - currentDate; // Initialize days, hours, minutes and seconds var oneSecond = 1000; // 1000 milliseconds = 1 second var oneMinute = oneSecond * 60; var oneHour = oneMinute * 60; var oneDay = oneHour * 24; // Get distance in days, hours, minutes and seconds var days = Math.floor(distance / oneDay); var hours = Math.floor((distance % oneDay) / oneHour); var minutes = Math.floor((distance % oneHour) / oneMinute); var seconds = Math.floor((distance % oneMinute) / oneSecond); // Place 0 before the numbers if the are lower than 10 hours = (hours < 10 ? "0" : "") + hours; minutes = (minutes < 10 ? "0" : "") + minutes; seconds = (seconds < 10 ? "0" : "") + seconds; document.getElementById('dLeft').innerText = days; document.getElmentById('hLeft').innerText = hours; document.getElementById('mLeft').innerText = minutes; document.getElementById('sLeft').innerText = seconds; }, 1000); ``` ```html Tulsa's Summer Party * [News](#) * [Night Beat](#) * [Tulsa Times](#) * [Calendar](#) * [City Links](#) ![](tny_banner2.png) Tulsa'sSummer Party =================== Welcome to Tulsa ---------------- 11/3/20172:45:12 p.m. Countdown to the Fireworks ========================== 58 Days 10 Hrs 14 Mins 48 Secs Celebrate the nation's birthday at *Tulsa's Summer Party*, a daylong extravaganza in downtown Tulsa on the 4th of July. The festivities start at 9 a.m. with a 5K and 10K walk or race. A great event for the whole family. Sign up as an individual or part of a team. The *Farmer's Market* is also back with farm-fresh produce, meats, and dairy. There's something for every pallet. Live music starts at 11 a.m. and continues through the day with special appearances from *Falstaff Ergo*, *Crop Circles*, *Prairie Wind* and *James Po*. At 9 p.m. enjoy the *fireworks* that have won awards as the best in the Midwest, designed and presented by *Wizard Works*. Arrive early for the best seats! After the show, dance the night away to the music of the *Chromotones*. See you on the 4th! Party Links =========== * [5K and 10K Run](#) * [Famer's Market](#) * [Wizard Works](#) * [Falstaff Ergo](#) * [Crop Circles](#) * [James Po](#) * [Tulsa Fireworks](#) * [Prairie Wind](#) Tulsa Summer Party · 340 Main Street, Tulsa, OK 74102 · (918) 555-3481 ``` Screenshot of my page: <http://prntscr.com/isp2hu> Ive been googling and looking at possible issues and nothing has solved my problem so far. EDIT: Added my CSS ```html @charset "utf-8"; @font-face { font-family: Segment14; src: url('segment14.woff') format('woff'), url('segment14.ttf') format('truetype'); } /* New Perspectives on HTML5 and CSS3, 7th Edition Tutorial 9 Review Assignment Tulsa's Summer Party Layout Style Sheet Filename: tny_layout.css Segment14 font designed by <NAME>. Download at: http://www.1001fonts.com/segment14-font.html#styles */ /* HTML and Body styles */ html { background: linear-gradient(to bottom, rgb(120, 84, 23), rgb(51, 51, 51)); font-family: Verdana, Geneva, sans-serif; min-height: 100%; } body { margin: 0px auto; min-width: 340px; max-width: 1020px; width: 100%; min-height: 100%; } /* Header styles */ header img#logoImg { display: block; width: 100%; } header { background: linear-gradient(to bottom, black 70%, rgb(185, 0, 102)); border-bottom: 1px solid rgb(0, 0, 0); color: white; position: relative; width: 100%; } header > h1 { position: absolute; top: 15px; right: 10px; text-align: right; font-size: 1.3em; letter-spacing: 0.05em; line-height: 1em; font-family: 'Times New Roman', serif; font-weight: normal; color: rgba(255, 0, 192, 0.7); } header > h2 { position: absolute; top: 15px; left: 10px; font-size: 0.9em; font-weight: normal; color: rgba(255, 82, 192, 0.8); } /* Navigation list styles */ header nav.horizontal { position: absolute; bottom: 0px; left: 0px; width: 100%; -webkit-flex: 0 1; flex: 0 1; } body header nav ul { display: -webkit-flex; display: flex; -webkit-flex-flow: row nowrap; flex-flow: row nowrap; } nav.horizontal ul li { -webkit-flex: 1 1; flex: 1 1; font-size: 0.8em; line-height: 1.5em; height: 1.5em; font-family: 'Trebuchet MS', Helvetica, sans-serif; text-shadow: black 2px 1px 0px, black 4px 2px 5px; } nav.horizontal ul li a { background-color: rgba(255, 255, 255, 0.2); display: block; color: rgba(255, 255, 255, 0.8); text-align: center; } nav.horizontal ul li a:hover { background-color: rgba(255, 88, 192, 0.5); } /* Time Clock Styles */ div#currentTime { display: block; position: absolute; top: 35px; left: 10px; background-color: transparent; border: hidden; color: rgba(255, 82, 192, 0.8); width: 140px; font-size: 0.6em; line-height: 1.1em; font-family: 'Trebuchet MS', Helvetica, sans-serif; font-weight: normal; } div#currentTime span { display: block; width: 100%; } /* Styles for the Countdown Clock */ div#countdown { width: 100%; display: -webkit-flex; display: flex; -webkit-flex-flow: row nowrap; flex-flow: row nowrap; margin-top: 10px; } div#countdown div { display: block; text-align: center; width: 100%; line-height: 1.5em; font-size: 0.5em; font-family: segment14, sans-serif; color: white; background: rgba(51, 51, 51, 0.7); margin: 0px 1px; padding: 5px; color: white; } div#countdown div span { font-size: 2em; } /* Article Styles */ article { background: white; display: -webkit-flex; display: flex; -webkit-flex-flow: row wrap; flex-flow: row wrap; } article section, article nav.vertical { -webkit-flex: 1 1 300px; flex: 1 1 300px; } section h1 { font-size: 1.2em; text-align: center; margin: 10px; } section p { margin: 20px; } /*Section 1 styles */ article section:nth-of-type(1) { background-color: rgba(255, 0, 192, 0.6); } /* Section 2 styles */ article section:nth-of-type(2) { background-color: rgba(255, 0, 192, 0.5); } /* Vertical navigation list styles */ nav.vertical { background-color: rgba(255, 0, 192, 0.7); } nav.vertical h1 { color: rgba(255, 255, 255, 0.7); text-shadow: rgba(192, 0, 145, 0.8) 2px 2px 5px; font-size: 1.35em; letter-spacing: 3px; text-align: center; padding: 10px; margin: 0px 0px 15px 0px; background-color: rgba(233, 0, 177, 0.5); } nav.vertical ul li { font-size: 0.82em; letter-spacing: 3px; text-align: center; } nav.vertical ul li a { display: block; padding-left: 30px; height: 32px; line-height: 32px; width: auto; color: rgb(51, 51, 51); } nav.vertical ul li a:hover { background-color: rgba(255, 192, 0, 0.45); } /* Page footer styles */ footer { clear: left; display: block; } footer address { display: block; font-style: normal; text-align: center; font-size: 0.5em; line-height: 20px; height: 20px; background-color: rgb(215, 0, 152); color: white; } /* ============================================= Tablet and Desktop Styles: greater than 510px ============================================= */ @media only screen and (min-width:511px) { header > h1 { font-size: 1.9em; } header > h2 { font-size: 1.1em; } div#currentTime { font-size: 0.9em; line-height: 1em; } div#countdown { font-size: 1.3em; } footer address { font-size: 0.6em; } } /* ============================================= Tablet and Desktop Styles: greater than 640px ============================================= */ @media only screen and (min-width:641px) { header > h1 { font-size: 2.4em; } header > h2 { font-size: 1.3em; } nav.horizontal ul li { font-size: 1em; } div#currentTime { font-size: 1em; line-height: 1.1em; top: 40px; } div#countdown { font-size: 1.5em; } footer address { font-size: 0.8em; } } /* ============================================= Tablet and Desktop Styles: greater than 720px ============================================= */ @media only screen and (min-width: 721px) { header > h1 { font-size: 3.3em; } header > h2 { font-size: 1.5em; } div#currentTime { font-size: 1.1em; line-height: 1.2em; top: 40px; } div#countdown { font-size: 1.7em; } } /* ============================================= Tablet and Desktop Styles: greater than 1020px ============================================= */ @media only screen and (min-width: 1021px) { body { margin: 40px auto; } } ```<issue_comment>username_1: Take a look at [FlipClock.js](http://flipclockjs.com) **The html...** ``` ``` **Instantiating in JQuery...** ``` var clock = $('.your-clock').FlipClock({ // ... your options here }); ``` **Instantiating in JavaScript...** ``` var clock = new FlipClock($('.your-clock'), { // ... your options here }); ``` Upvotes: -1 <issue_comment>username_2: You could do something as simple as this: **HTML:** ``` ``` **JavaScript:** ``` // set minutes var mins = 5; // calculate the seconds (don't change this! unless time progresses at a different speed for you...) var secs = mins * 60; function countdown() { setTimeout('Decrement()',1000); } function Decrement() { if (document.getElementById) { minutes = document.getElementById("minutes"); seconds = document.getElementById("seconds"); // if less than a minute remaining if (seconds < 59) { seconds.value = secs; } else { minutes.innerHTML = getminutes(); seconds.innerHTML = getseconds(); } secs--; setTimeout('Decrement()',1000); } } function getminutes() { // minutes is seconds divided by 60, rounded down mins = Math.floor(secs / 60); return mins; } function getseconds() { // take mins remaining (as seconds) away from total seconds remaining return secs-Math.round(mins *60); } countdown(); ``` Upvotes: 1 <issue_comment>username_3: I replaced your functions with my own functions. To update the countdown / current time/date every seconds, I set an interval that executes the function every second: ``` setInterval(function() { ... }, 1000); // 1000 milliseconds = 1 second ``` Your way of gettings the date's hours, minutes, etc. is ```js // Function to display current date / time on the site setInterval(function displayTimeAndDate() { var today = new Date(); var hours = today.getHours(); var minutes = today.getMinutes(); var seconds = today.getSeconds(); var date = today.getDate(); var month = today.getMonth(); var year = today.getFullYear(); // Place 0 before the numbers if the are lower than 10 hours = (hours < 10 ? "0" : "") + hours; minutes = (minutes < 10 ? "0" : "") + minutes; seconds = (seconds < 10 ? "0" : "") + seconds; var amOrPm; // Check if it's a.m or p.m if (hours < 12) { amOrPm = "a.m"; } else { amOrPm = "p.m"; } document.getElementById('currentTime').innerText = month + "/" + date + "/" + year + " " + hours + ":" + minutes + ":" + seconds + " " + amOrPm; }, 1000); setInterval(function countdown() { // Set the desired date (American date format: Month/Day/Year) to countdown to and the current date var endDate = new Date('07/04/2018 09:00 PM'); var currentDate = new Date(); // Get the "distance" between the dates var distance = endDate - currentDate; // Initialize days, hours, minutes and seconds var oneSecond = 1000; // 1000 milliseconds = 1 second var oneMinute = oneSecond * 60; var oneHour = oneMinute * 60; var oneDay = oneHour * 24; // Get distance in days, hours, minutes and seconds var days = Math.floor(distance / oneDay); var hours = Math.floor((distance % oneDay) / oneHour); var minutes = Math.floor((distance % oneHour) / oneMinute); var seconds = Math.floor((distance % oneMinute) / oneSecond); // Place 0 before the numbers if the are lower than 10 hours = (hours < 10 ? "0" : "") + hours; minutes = (minutes < 10 ? "0" : "") + minutes; seconds = (seconds < 10 ? "0" : "") + seconds; document.getElementById('countdown').innerText = days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds" }, 1000); ``` ```html Tulsa's Summer Party * [News](#) * [Night Beat](#) * [Tulsa Times](#) * [Calendar](#) * [City Links](#) ![](tny_banner2.png) Tulsa'sSummer Party =================== Welcome to Tulsa ---------------- Countdown to the Fireworks ========================== Celebrate the nation's birthday at *Tulsa's Summer Party*, a daylong extravaganza in downtown Tulsa on the 4th of July. The festivities start at 9 a.m. with a 5K and 10K walk or race. A great event for the whole family. Sign up as an individual or part of a team. The *Farmer's Market* is also back with farm-fresh produce, meats, and dairy. There's something for every pallet. Live music starts at 11 a.m. and continues through the day with special appearances from *Falstaff Ergo*, *Crop Circles*, *Prairie Wind* and *James Po*. At 9 p.m. enjoy the *fireworks* that have won awards as the best in the Midwest, designed and presented by *Wizard Works*. Arrive early for the best seats! After the show, dance the night away to the music of the *Chromotones*. See you on the 4th! Party Links =========== * [5K and 10K Run](#) * [Famer's Market](#) * [Wizard Works](#) * [Falstaff Ergo](#) * [Crop Circles](#) * [James Po](#) * [Tulsa Fireworks](#) * [Prairie Wind](#) Tulsa Summer Party · 340 Main Street, Tulsa, OK 74102 · (918) 555-3481 ``` Edit: ----- This time I didn't modify the HTML: (I put it in a executable code snippet, otherwise I wouldn't be able to format it properly.) ```js // Function to display current date / time on the site setInterval(function displayTimeAndDate() { var today = new Date(); var hours = today.getHours(); var minutes = today.getMinutes(); var seconds = today.getSeconds(); var date = today.getDate(); var month = today.getMonth(); var year = today.getFullYear(); var amOrPm; // Check if it's a.m or p.m if (hours < 12) { amOrPm = "a.m"; } else { amOrPm = "p.m"; } document.getElementById('date').innerText = date + ":" + month + ":" + year; document.getElementById('time').innerText = hours + ":" + minutes + ":" + seconds + " " + amOrPm; }, 1000); setInterval(function countdown() { // Set the desired date (American date format: Month/Day/Year) to countdown to and the current date var endDate = new Date('07/04/2018 09:00 PM'); var currentDate = new Date(); // Get the "distance" between the dates var distance = endDate - currentDate; // Initialize days, hours, minutes and seconds var oneSecond = 1000; // 1000 milliseconds = 1 second var oneMinute = oneSecond * 60; var oneHour = oneMinute * 60; var oneDay = oneHour * 24; // Get distance in days, hours, minutes and seconds var days = Math.floor(distance / oneDay); var hours = Math.floor((distance % oneDay) / oneHour); var minutes = Math.floor((distance % oneHour) / oneMinute); var seconds = Math.floor((distance % oneMinute) / oneSecond); // Place 0 before the numbers if the are lower than 10 hours = (hours < 10 ? "0" : "") + hours; minutes = (minutes < 10 ? "0" : "") + minutes; seconds = (seconds < 10 ? "0" : "") + seconds; document.getElementById('dLeft').innerText = days; document.getElmentById('hLeft').innerText = hours; document.getElementById('mLeft').innerText = minutes; document.getElementById('sLeft').innerText = seconds; }, 1000); ``` Upvotes: 1 [selected_answer]
2018/03/18
1,051
3,906
<issue_start>username_0: I have 2 components and a service. BehaviorSubject in the service class has default values and also it pulls in data from an API. The first component gets the latest data which is pulled from the API, but the second component only displays the default values. What could be wrong in my code. Plz advise! ``` export class WebService { public btnsOnResponse; //activates buttons when server responds positive BASE_URL = 'http://localhost:3000/api'; private stats = new BehaviorSubject({ date: this.datePipe.transform(new Date(), 'dd-MM-yyyy'), answeringMachine:0, hangUp:0, conversations:0 }); public stats$ = this.stats.asObservable(); constructor(private http: HttpClient) { this.getStatsbyDate('04-03-2018'); } ``` Components: 1st Component ``` export class StatsComponent { public stats: IStats; constructor(private webService: WebService, private datePipe: DatePipe) { this.webService.stats$.subscribe((data) => { if (data !== null) { this.stats = data; } // else { this.webService.stats.next(this.stats); } console.log(data); }) } ``` [![Console.log](https://i.stack.imgur.com/aRok6.jpg)](https://i.stack.imgur.com/aRok6.jpg) 2nd Component ``` export class ChartsComponent { private stats: IStats; constructor(private webService: WebService) { this.webService.stats$.subscribe((data: IStats) => { this.stats = data; }) console.log(this.stats); } ```<issue_comment>username_1: The problem that you're having is that you are defining a BehaviorSubject and the initial values that are sent through the Observables pipeline, but you are not actually pushing the next set of values through that pipeline whenever you receive the data back from the API ([more reading from RxJS](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/behaviorsubject.md)). Here is your updated code example: ```js export class WebService { public btnsOnResponse; //activates buttons when server responds positive BASE_URL = 'http://localhost:3000/api'; private stats = new BehaviorSubject({ date: this.datePipe.transform(new Date(), 'dd-MM-yyyy'), answeringMachine:0, hangUp:0, conversations:0 }); public stats$ = this.stats.asObservable(); constructor(private http: HttpClient) { // I am going to assume that the this.getStatsByDate() returns an Observable of some kind. this.getStatsbyDate('04-03-2018') .subscribe( // You needed to subscribe to this function call and then call the .onNext() function in order to pass in the next set of data to your this.stats$ Observable. (val: any) => this.stats$.onNext(val) ); } // I am guessing that you have an implementation of the this.getStatsByDate() function somewhere here, since you didn't include it in your original post. } ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: That happens because you run another `async` operation, as you wrote in your comment - `this.http.get`. That async function has a callback - `subscribe()` with functions in it. Because it is `async` and JavaScript is single-threated, Angular continues building your application (components etc.) while that callback is being placed in so called "Callback Queue". It fires only after Call stack (normal Javascript functions) is empty - so when Angular finishes building your app (in general). So that means that `this.stats.next(data)` is being fired **after** you subscribe your BehaviourSubject, so you get one initial value and later comes another. You can remove that `async` and `next` other object: ``` constructor(private http: HttpClient) { // this.getStatsbyDate('04-03-2018'); this.stats.next({ date: this.datePipe.transform(new Date(), 'dd-MM-yyyy'), answeringMachine:100, hangUp:100, conversations:100 });) } ``` You should get only the last value. Upvotes: 1
2018/03/18
504
1,478
<issue_start>username_0: ``` A B C D E F G H 1 Y Y Y X 2 X X 3 Y Y 4 X X 5 Y Y Y X Count the number of empty rows (from Columns A to E) and put result here. Answer should be 2 from example above. ``` Hi Folks, I'm struggling to find the correct Excel formula to count the number of rows with no data from columns A through E, and putting that answer in a cell. These 'empty rows' may have data in later columns (like F, G, H), but I just want to count the rows with no data from columns A to E. Any help would be appreciated.<issue_comment>username_1: Try this array formula, ``` =SUM(IF(ROW(1:5), IF(A1:A5&B1:B5&C1:C5&D1:D5&E1:E5="", 1))) ``` Remember to finalize with ctrl+shift+enter, not just enter. Upvotes: 2 [selected_answer]<issue_comment>username_2: Since array formulas tend to confuse people, here's a non-Array formula approach: Place `=IF(COUNTA(A1:E1)=0,1,0)` into row 1 of (for example) column I and drag down to row 5. Then place a sum formula below that to get the answer, for example: `=SUM(I1:I5)` Upvotes: 2 <issue_comment>username_3: You could also use a variation on the standard formula for getting row sums of a 2d array ``` =SUM(N(MMULT(N(A1:E5=""),TRANSPOSE(COLUMN(A1:E5)^0))=COLUMNS(A1:E5))) ``` or ``` =SUM(N(MMULT(N(A1:E5="Y"),TRANSPOSE(COLUMN(A1:E5)^0))=0)) ``` Again they are array formulas and have to be entered with `Ctrl``Shift``Enter` Upvotes: 0
2018/03/18
615
2,291
<issue_start>username_0: Do you have any idea how to fix this? The Windows Power Shell returns the following when I type in "flutter doctor": > > `The term 'flutter' is not recognized as the name of a cmdlet, > function, script file, or operable program. > > > Check the spelling of the > name, or if a path was included, verify that the path is correct and > try again. At line:1 char:1 + flutter doctor + ~~~~~~~ + > CategoryInfo : ObjectNotFound: (flutter:String) [], > > > CommandNotFoundException + FullyQualifiedErrorId : > CommandNotFoundException` > > ><issue_comment>username_1: Have you added the path to the `flutter` command to your path and logged out / restarted? You should have the following entries: `FLUTTER_ROOT: PATH: + %FLUTTER\_ROOT%\bin` Upvotes: 2 <issue_comment>username_2: The easiest possible way if you are using windows 10 is to go to > > my computer > > > right click and choose > > properties > > > after that from the left side you choose > > Advanced System settings > from there you choose the advanced tab you'll find at the bottom > Environment Variables > Click on it and find > PATH > If it doesn't exist create one if it does click on it and edit and keep the original path and add to it ; then the full directory of your flutter bin. > > > Upvotes: 1 <issue_comment>username_3: Follow below steps and restart your system once it worked for me 1. Search -> ‘env’ and select Edit environment variables for your account. 2. Under User variables check if there is an entry called Path: If the entry exists, append the full path to flutter\bin using ; as a separator from existing values. If the entry doesn’t exist, create a new user variable named Path with the full path to flutter\bin as its value 3. Restart System 4. After that run this command : C:\src\flutter flutter doctor Upvotes: 2 <issue_comment>username_4: Add flutter/bin folder to the environment variables: 1. On windows 10 click start, type environment variables, then click Edit System Environment variables 2. Click Environment Variables 3. Under User Variables, select path and click edit button 4. Click New and browse the path to your flutter/bin folder 5. Click OK 6. Restart your Power Shell and run flutter commands again Upvotes: 2
2018/03/18
1,036
3,406
<issue_start>username_0: Currently, I imported the following data frame from Excel into pandas and I want to delete duplicate values based in the values of two columns. ``` # Python 3.5.2 # Pandas library version 0.22 import pandas as pd # Save the Excel workbook in a variable current_workbook = pd.ExcelFile('C:\\Users\\userX\\Desktop\\cost_values.xlsx') # convert the workbook to a data frame current_worksheet = pd.read_excel(current_workbook, index_col = 'vend_num') # current output print(current_worksheet) | vend_number | vend_name | quantity | source | | ----------- |----------------------- | -------- | -------- | CHARLS Charlie & Associates $5,700.00 Central CHARLS Charlie & Associates $5,700.00 South CHARLS Charlie & Associates $5,700.00 North CHARLS Charlie & Associates $5,700.00 West HUGHES Hughinos $3,800.00 Central HUGHES Hughinos $3,800.00 South FERNAS Fernanda Industries $3,500.00 South FERNAS Fernanda Industries $3,500.00 North FERNAS Fernanda Industries $3,000.00 West .... ``` What I want is to remove those duplicate values based in the columns quantity and source: 1. Review the quantity and source column values: 1.1. If the quantity of a vendor is equal in another row from the same vendor and source is not equal to Central then drop the repeated rows from this vendor except the row Central. 1.2. Else if the quantity of a vendor is equal in another row from the same vendor and there is no source Central then drop the repeated rows. Desired result ``` | vend_number | vend_name | quantity | source | | ----------- |----------------------- | -------- | -------- | CHARLS Charlie & Associates $5,700.00 Central HUGHES Hughinos $3,800.00 Central FERNAS Fernanda Industries $3,500.00 South FERNAS Fernanda Industries $3,000.00 West .... ``` So far, I have tried the following code but pandas is not even detecting any duplicate rows. ``` print(current_worksheet.loc[current_worksheet.duplicated()]) print(current_worksheet.duplicated()) ``` I have tried to figure out the solution but I am struggling quite a bit in this problem, so any help in this question is greatly appreciated. Feel free to improve the question.<issue_comment>username_1: You can do it two steps ``` s=df.loc[df['source']=='Central',:] t=df.loc[~df['vend_number'].isin(s['vend_number']),:] pd.concat([s,t.drop_duplicates(['vend_number','quantity'],keep='first')]) ``` Upvotes: 1 <issue_comment>username_2: Here is one way. ``` df['CentralFlag'] = (df['source'] == 'Central') df = df.sort_values('CentralFlag', ascending=False)\ .drop_duplicates(['vend_name', 'quantity'])\ .drop('CentralFlag', 1) # vend_number vend_name quantity source # 0 CHARLS Charlie&Associates $5,700.00 Central # 4 HUGHES Hughinos $3,800.00 Central # 6 FERNAS FernandaIndustries $3,500.00 South # 8 FERNAS FernandaIndustries $3,000.00 West ``` **Explanation** * Create a flag column, sort by this descending, so Central is prioritised. * Sort by `vend_name` and `quantity`, then drop the flag column. Upvotes: 4 [selected_answer]
2018/03/18
582
1,695
<issue_start>username_0: I'm trying to grab the username from this JSON in PHP: ``` ["{\"account\":{\"username\":\"test\",\"password\":\"hey\",\"info\":{\"ip\":\"172.16.17.32\",\"proxyMethod\":\"TOR\",\"time\":\"2018-03-17 05:32:58\"}}}"] ``` The JSON is stored in a file. While I have the code down to grab the JSON from the file. I'm having quite the issue with grabbing the username. What I have right now: ``` php $file = ('/var/www/html/account/generator/accounts.json'); $accountJson = json_decode(file_get_contents($file), true); echo count($accountJson); echo $accountJson[0]; echo 'done'; ? ``` But when I attempt to grab the username by doing ``` echo $acountJson[0]['account']; ``` it only echos `{`. How can I solve this?<issue_comment>username_1: You can do it two steps ``` s=df.loc[df['source']=='Central',:] t=df.loc[~df['vend_number'].isin(s['vend_number']),:] pd.concat([s,t.drop_duplicates(['vend_number','quantity'],keep='first')]) ``` Upvotes: 1 <issue_comment>username_2: Here is one way. ``` df['CentralFlag'] = (df['source'] == 'Central') df = df.sort_values('CentralFlag', ascending=False)\ .drop_duplicates(['vend_name', 'quantity'])\ .drop('CentralFlag', 1) # vend_number vend_name quantity source # 0 CHARLS Charlie&Associates $5,700.00 Central # 4 HUGHES Hughinos $3,800.00 Central # 6 FERNAS FernandaIndustries $3,500.00 South # 8 FERNAS FernandaIndustries $3,000.00 West ``` **Explanation** * Create a flag column, sort by this descending, so Central is prioritised. * Sort by `vend_name` and `quantity`, then drop the flag column. Upvotes: 4 [selected_answer]
2018/03/18
870
2,637
<issue_start>username_0: There are two maps with same structure say map1 and map2 having structure as `Map`. Map 1 contains following items: `("i1", True),("i2", True), ("i3", False), ("i4", True)` Map 2 contains following items: `("i1", True),("i2", False), ("i3", True), ("i5", True)` I want two kinds of information: `Information1: map1TrueMoreThanMap2True = 2` The map1TrueMoreThanMap2True is 2 because we are comparing map entries. In this case the diff between map1 and map2 is: `Map1 - ("i2", True),("i4", True)` `Information2: map1FalseMoreThanMap2False = 1` In this case the diff between map1 and map2 is: `Map1 - ("i3", False)` I am achieving this by writing below code: ``` Map trueCountMap1 = map1.entrySet().stream() .filter(p -> p.getValue() == Boolean.TRUE) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Map trueCountMap2 = map2.entrySet().stream() .filter(p -> p.getValue() == Boolean.TRUE) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Map falseCountMap1 = map1.entrySet().stream() .filter(p -> p.getValue() == Boolean.FALSE) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Map falseCountMap2 = map2.entrySet().stream() .filter(p -> p.getValue() == Boolean.FALSE) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); map1TrueMoreThanMap2True = (CollectionUtils.disjunction(trueCountMap1.entrySet(), trueCountMap2.entrySet()) .size())/2; map1FalseMoreThanMap2False = (CollectionUtils .disjunction(falseCountMap1.entrySet(), falseCountMap2.entrySet()).size())/2; ``` **i think the above code is verbose. Is there a better way of doing it??**<issue_comment>username_1: You can do it two steps ``` s=df.loc[df['source']=='Central',:] t=df.loc[~df['vend_number'].isin(s['vend_number']),:] pd.concat([s,t.drop_duplicates(['vend_number','quantity'],keep='first')]) ``` Upvotes: 1 <issue_comment>username_2: Here is one way. ``` df['CentralFlag'] = (df['source'] == 'Central') df = df.sort_values('CentralFlag', ascending=False)\ .drop_duplicates(['vend_name', 'quantity'])\ .drop('CentralFlag', 1) # vend_number vend_name quantity source # 0 CHARLS Charlie&Associates $5,700.00 Central # 4 HUGHES Hughinos $3,800.00 Central # 6 FERNAS FernandaIndustries $3,500.00 South # 8 FERNAS FernandaIndustries $3,000.00 West ``` **Explanation** * Create a flag column, sort by this descending, so Central is prioritised. * Sort by `vend_name` and `quantity`, then drop the flag column. Upvotes: 4 [selected_answer]
2018/03/18
1,100
4,039
<issue_start>username_0: I'm just starting to learn how to use Hibernate and I'm not be able to figure out how to properly annotate a list when it's referencing an interface. This is my case, I have a class MarketOrderImpl that implements MarketOrder like so... ``` @Entity public final class MarketOrderImpl implements MarketOrder { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private String id; private OrderType type; private BigDecimal price; private BigDecimal quantity; private BigDecimal total; public MarketOrderImpl(OrderType type, BigDecimal price, BigDecimal quantity, BigDecimal total) { this.type = type; this.price = price; this.quantity = quantity; this.total = total; } ``` and I have an MarketOrderBookImpl that has two lists that I'm not being able to anotate without an exception (private List sellOrders and private List buyOrders) ``` @Entity public final class MarketOrderBookImpl implements MarketOrderBook { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private String marketId; @OneToMany @JoinTable(name="marketorderimpl") @MapKeyColumn(name="id") private List sellOrders; @OneToMany @JoinTable(name="marketorderimpl") @MapKeyColumn(name="id") private List buyOrders; public MarketOrderBookImpl(String marketId, List sellOrders, List buyOrders) { this.marketId = marketId; this.sellOrders = sellOrders; this.buyOrders = buyOrders; } ``` This is my exception... ``` Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class:br.com.codefleck.tradebot.exchanges.trading.api.impl.MarketOrderBookImpl.sellOrders[br.com.codefleck.tradebot.tradingapi.MarketOrder]at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1136) at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:792) at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:727) at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:70) at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1695) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1424) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850) ... 66 more ``` Thanks in advance for the help!<issue_comment>username_1: You need to define target entity so hibernate can understand which domain to bind this relation. `@OneToMany(targetEntity=MarketOrderImpl.class) @JoinTable(name="marketorderimpl") @MapKeyColumn(name="id") private List sellOrders;` Upvotes: 2 <issue_comment>username_2: As a *PersistenceProvider* implementation - such as Hibernate - can't infer which concrete class is the "correct" one to use in such a case, you have to tell the ORM implementation what type to use at runtime. In section 11.1.40 (PDF page 474) of the [JPA 2.1 specification](http://download.oracle.com/otn-pub/jcp/persistence-2_1-fr-eval-spec/JavaPersistence.pdf) we find an important piece of information, related to your question: > > The entity **class** that is the target > of the association. Optional only if the collection-valued > relationship property is > defined using Java generics. Must be specified > otherwise. > > > *Hint*: Table 37 on "`OneToMany` Annotation Elements" lists further details on how to programmatically declare **runtime information** for a specific OR mapper. Given the above information, the correct approach is to declare runtime-related information for the **targetEntity** type with: ``` @OneToMany(targetEntity= MarketOrderImpl.class) @JoinTable(name="marketorderimpl") @MapKeyColumn(name="id") private List sellOrders; @OneToMany(targetEntity= MarketOrderImpl.class) @JoinTable(name="marketorderimpl") @MapKeyColumn(name="id") private List buyOrders; ``` Hope it helps. Upvotes: 3 [selected_answer]
2018/03/18
200
772
<issue_start>username_0: I want to make a gallery system in laravel 5.5. So that every time i upload photos it shows in a different album with 1st photo and title that i uploaded. And after clicking to that album shows the other photos of that album. How can i do it?<issue_comment>username_1: Manke two database named gallery and photos. It will be something like this: Gallery: id name description timestamp cover\_image more columns..... Photo model: id gallery\_id image name more columns..... Save gallery and then upload multiple files in photo table with one to many relationship Upvotes: 0 <issue_comment>username_2: Here is a good example for you : <https://www.dunebook.com/tutorial-creating-a-photo-gallery-system-with-laravel/> Upvotes: -1 [selected_answer]
2018/03/18
792
3,198
<issue_start>username_0: I have a multiprocessing program where I'm unable to work with global variables. I have a program which starts like this:- ``` from multiprocessing import Process ,Pool print ("Initializing") someList = [] ... ... ... ``` Which means I have someList variables which get initialized before my main is called. Later on in the code someList is set to some value and then I create 4 processes to process it ``` pool = Pool(4) combinedResult = pool.map(processFn, someList) pool.close() pool.join() ``` Before spawning the processes, someList is set to a valid value. However, when the processes are spawned, I see this print 4 times !! `Initializing Initializing Initializing Initializing` As it is clear in each process the initialization section at the top of the program is getting called. Also, someList gets set to empty. If my understanding is correct, each process should be a replica of the current process's state which essentially means, I should have got 4 copies of the same list. Why are the globals being re-initialized again? And in fact, why is that section even being run? Can someone please explain this to me? I referred to python docs but wasn't able to determine the root cause. They do recommend against using globals and I'm aware of it, but it still doesn't explain the call to the initialization function. Also, I'd like to use multiprocessing and not multithreading. I'm trying to understand how multiprocessing works here. Thanks for your time.<issue_comment>username_1: I think the point is, that you are creating 4 Processes, which are executing the Code you give them. They work in the same instance, but executing the same Code. So maybe, you do Multithreading or you use some if-clauses etc. to determine which Process should execute which Code. * cheers Upvotes: -1 <issue_comment>username_2: In Windows processes are not *forked* as in Linux/Unix. Instead they are *spawned*, which means that a new Python interpreter is started for each new `multiprocessing.Process`. This means that all global variables are re-initialized and if you have somehow manipulated them along the way, this will not be seen by the spawned processes. A solution to the problem is to pass the globals to the `Pool` `initilaizer` and then from there make it `global` also in the spawned process: ``` from multiprocessing import Pool def init_pool(the_list): global some_list some_list = the_list def access_some_list(index): return some_list[index] if __name__ == "__main__": some_list = [24, 12, 6, 3] indexes = [3, 2, 1, 0] pool = Pool(initializer=init_pool, initargs=(some_list,)) result = pool.map(access_some_list, indexes) print(result) ``` In this setup, you will copy the globals to each new process and they will then be accessible, however, as always, any updates done from there on will not be propagated to any other process. For that you will need something like a proper `multiprocessing.Manager`. As an extra comment, from here it is clear that global variables can be dangerous, because it is hard to understand what values they will take in the different processes. Upvotes: 4 [selected_answer]
2018/03/18
1,282
3,866
<issue_start>username_0: So I wrote this code to remove the vowels from any string given. it should work fine. And it actually does. Just not for all strings which is weird why it would work for some strings and not for others here's the code: ``` vowels = ["a", "e", "i", "o", "u"] def anti_vowel(text): text1 = list(text) print text1 for i in text1: if i.lower() in vowels: text1.remove(i) text2 = "".join(text1) return text2 ``` and here are the tests that I placed: ``` print anti_vowel("my name is Omar") print anti_vowel("Hey look Words!") print anti_vowel("Hey look more Words to look for!") ``` I tried placing print statements in the middle of the code to test it and I found something weird. the for loop iterates about 3 or 4 times to remove one vowel. I can't seem to know why<issue_comment>username_1: You don't have to convert the string to a list. Refer to this answer here: [Correct code to remove the vowels from a string in Python](https://stackoverflow.com/questions/21581824/correct-code-to-remove-the-vowels-from-a-string-in-python) Upvotes: 0 <issue_comment>username_2: This weird case happens when 2 vowels are right next to each other. Basically, you are looping for each letter in the word, but when you remove the letter (if it is a vowel), then you shorten the length of the word, and therefore the next letter will have skipped over the *real* next letter. This is a problem when the letter being skipped is a vowel, but not when it is a consonant. So how do we solve this? Well, instead of modifying the thing we're looping over, we will make a new string and modify it. So: ``` text2 = "" for letter in text1: if letter not in vowels: text2 += letter return text2 ``` This can also be achieved with list comprehension: ``` return "".join ([letter for letter in text1 if letter not in vowels]) ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Because the `for` statement checks through every letter within the list, even when it removes that vowel. Here's a quick example where it doesn't iterates 3-4 times to remove one vowel: ``` vowels = ["a", "e", "i", "o", "u"] def anti_vowel(text): text1 = list(text.lower()) text1 = [x for x in text1 if x not in vowels] text2 = "".join(text1) return (text2) print anti_vowel("my name is Omar") print anti_vowel("Hey look Words!") print anti_vowel("Hey look more Words to look for!") ``` Upvotes: 0 <issue_comment>username_4: I am using Python 2.7. I modified your code slightly as follows, ``` vowels = 'aeiou' def anti_vowel(text): text1 = list(text) print text1 for i in text: if i.lower() in vowels: text1.remove(i) text2 = "".join(text1) return text2 print anti_vowel("my name is Omar") #['m', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'O', 'm', 'a', 'r'] #my nm s mr print anti_vowel("Hey look Words!") #['H', 'e', 'y', ' ', 'l', 'o', 'o', 'k', ' ', 'W', 'o', 'r', 'd', 's', '!'] #Hy lk Wrds! print anti_vowel("Hey look more Words to look for!") #['H', 'e', 'y', ' ', 'l', 'o', 'o', 'k', ' ', 'm', 'o', 'r', 'e', ' ', 'W', 'o', 'r', 'd', 's', ' ', 't', 'o', ' ', 'l', 'o', 'o', 'k', ' ', 'f', 'o', 'r', '!'] #Hy lk mr Wrds t lk fr! ``` I cannot duplicate your problem. The `for` loop sweeps through the input string once (one character by one character) and removes any vowel encountered. Perhaps you can post your output so we can debug. Upvotes: 0 <issue_comment>username_5: This can be done without `remove()` ``` #!python2 def anti_vowel(text): vowels = ["a", "e", "i", "o", "u"] s1 = '' for i in text: if i.lower() in vowels: pass else: s1 += i return s1 print anti_vowel("my name is Omar") print anti_vowel("Hey look Words!") print anti_vowel("Hey look more Words to look for!") ``` Upvotes: 0
2018/03/18
1,084
3,275
<issue_start>username_0: I've just started learning R, and was wondering, say I have the dataset quake, and I want to generate the probability histogram of quakes near Fiji, would the code simply be `hist(quakes$lat,freq=F)`?<issue_comment>username_1: You don't have to convert the string to a list. Refer to this answer here: [Correct code to remove the vowels from a string in Python](https://stackoverflow.com/questions/21581824/correct-code-to-remove-the-vowels-from-a-string-in-python) Upvotes: 0 <issue_comment>username_2: This weird case happens when 2 vowels are right next to each other. Basically, you are looping for each letter in the word, but when you remove the letter (if it is a vowel), then you shorten the length of the word, and therefore the next letter will have skipped over the *real* next letter. This is a problem when the letter being skipped is a vowel, but not when it is a consonant. So how do we solve this? Well, instead of modifying the thing we're looping over, we will make a new string and modify it. So: ``` text2 = "" for letter in text1: if letter not in vowels: text2 += letter return text2 ``` This can also be achieved with list comprehension: ``` return "".join ([letter for letter in text1 if letter not in vowels]) ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Because the `for` statement checks through every letter within the list, even when it removes that vowel. Here's a quick example where it doesn't iterates 3-4 times to remove one vowel: ``` vowels = ["a", "e", "i", "o", "u"] def anti_vowel(text): text1 = list(text.lower()) text1 = [x for x in text1 if x not in vowels] text2 = "".join(text1) return (text2) print anti_vowel("my name is Omar") print anti_vowel("Hey look Words!") print anti_vowel("Hey look more Words to look for!") ``` Upvotes: 0 <issue_comment>username_4: I am using Python 2.7. I modified your code slightly as follows, ``` vowels = 'aeiou' def anti_vowel(text): text1 = list(text) print text1 for i in text: if i.lower() in vowels: text1.remove(i) text2 = "".join(text1) return text2 print anti_vowel("my name is Omar") #['m', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'O', 'm', 'a', 'r'] #my nm s mr print anti_vowel("Hey look Words!") #['H', 'e', 'y', ' ', 'l', 'o', 'o', 'k', ' ', 'W', 'o', 'r', 'd', 's', '!'] #Hy lk Wrds! print anti_vowel("Hey look more Words to look for!") #['H', 'e', 'y', ' ', 'l', 'o', 'o', 'k', ' ', 'm', 'o', 'r', 'e', ' ', 'W', 'o', 'r', 'd', 's', ' ', 't', 'o', ' ', 'l', 'o', 'o', 'k', ' ', 'f', 'o', 'r', '!'] #Hy lk mr Wrds t lk fr! ``` I cannot duplicate your problem. The `for` loop sweeps through the input string once (one character by one character) and removes any vowel encountered. Perhaps you can post your output so we can debug. Upvotes: 0 <issue_comment>username_5: This can be done without `remove()` ``` #!python2 def anti_vowel(text): vowels = ["a", "e", "i", "o", "u"] s1 = '' for i in text: if i.lower() in vowels: pass else: s1 += i return s1 print anti_vowel("my name is Omar") print anti_vowel("Hey look Words!") print anti_vowel("Hey look more Words to look for!") ``` Upvotes: 0
2018/03/18
762
2,296
<issue_start>username_0: data in database ``` fieldA : 'aaaaa', fieldB : { en : 'aaaaaaaaaa', de : 'bbbbbbbbbb' } ``` new data ``` val = { fieldA : 'aaaaa11', fieldB : { en : 'aaaaa1111' } } ``` i tried this code ``` Model.findOneAndUpdate({fieldA : val.fieldA},{ $set : val}) ``` when i run this command 'fieldB.de' is missing. i want to know how to update as result seem below ``` fieldA : 'aaaaa11', fieldB : { en : 'aaaaa1111', de : 'bbbbbbbbbb' } ```<issue_comment>username_1: Try this: ``` Model.findOneAndUpdate({fieldA : val.fieldA},{ "$set": { "fieldA": val.fieldA, "fieldB.en": val.fieldB.en } }) ``` In your solution you update document completny with other one. To update only specific fields you must specify this fields in "$set" object Upvotes: 0 <issue_comment>username_2: I resolve this by finding the document first and editing de object manually. ```js /* Recursive function to update manually an object */ const update = (obj, newValues) => { Object.entries(newValues).forEach( ([key, value]) => { if(typeof value === 'object'){ update(obj[key], value); } else { obj[key] = value; } }); } /* Find document, update and save */ const infoToUpdate = {}; const doc = await Model.findOne({ field: valueToFind }); if (doc) { object.update(doc, infoToUpdate); doc.save(); } ``` Upvotes: 0 <issue_comment>username_3: You have to change the object passed to `findOneAndUpdate()` so that you don't pass `fieldB` as an object, only the fields to update. It can be done with something like this: ``` let val = { fieldA: 'aaaaa11', fieldB: { en: 'aaaaa1111', }, }; if (val.fieldB) { const newFieldB = Object.entries(val.fieldB).reduce( (a, [key, value]) => ({ ...a, ['fieldB.' + key]: value }), {} ); delete val.fieldB; val = { ...val, ...newFieldB }; } Model.findOneAndUpdate({fieldA : val.fieldA},{ $set : val}) ``` With that, the value of `val` passed to `findOneAndUpdate()` is: ``` { fieldA: 'aaaaa11', 'fieldB.en': 'aaaaa1111', } ``` Instead of: ``` { fieldA: 'aaaaa11', fieldB: { en: 'aaaaa1111', }, } ``` ... and attributes of `fieldB` that you didn't specify in `val` but that were in your DB will not get overridden. Upvotes: 1
2018/03/18
585
1,901
<issue_start>username_0: i have the following ``` Directory: C:\TWS API\source\pythonclient Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 3/17/2018 9:38 PM ibapi d----- 3/17/2018 9:38 PM tests -a---- 12/28/2017 5:34 PM 98 .gitignore -a---- 12/28/2017 5:34 PM 37 MANIFEST.in -a---- 12/28/2017 5:34 PM 3269 README.md -a---- 12/28/2017 5:34 PM 526 setup.py -a---- 12/28/2017 5:34 PM 87 tox.ini ``` and want to install the module ibapi. what am i doing wrong here? ``` PS C:\TWS API\source\pythonclient> python setup.py install python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + python setup.py install + ~~~~~~ + CategoryInfo : ObjectNotFound: (python:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException ```<issue_comment>username_1: Note the error: > > python : The term 'python' is not recognized as the name of a cmdlet, > function, script file, or operable program. Check the spelling of the > name, or if a path was included, verify that the path is correct and > try again. > > > its likely that python executable not set in the environment variable, set it in your environment variable or navigate to directory where python installed. [How to add to the pythonpath in windows 7?](https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7) Upvotes: 1 <issue_comment>username_2: try: `python3 setup.py install I have both python 2 and 3 installed on my system, so I had to specify. Upvotes: 0
2018/03/18
459
1,545
<issue_start>username_0: I have a Pandas DataFrame with two relevant columns. I need to check column A (a list of names) against itself, and if two (or more) values are similar enough to each other, I sum the values in column B for those rows. To check similarity, I'm using the FuzzyWuzzy package that accepts two strings and returns a score. Data: ``` a b apple 3 orang 4 aple 1 orange 10 banana 5 ``` I want to be left with: ``` a b apple 4 orang 14 banana 5 ``` I have tried the following line, but I keep getting a KeyError ``` df['b']=df.apply(lambda x: df.loc[fuzz.ratio(df.a,x.a)>=70,'b'].sum(), axis=1) ``` I would also need to remove all rows where column b was added into another row. Any thoughts on how to accomplish this?<issue_comment>username_1: Note the error: > > python : The term 'python' is not recognized as the name of a cmdlet, > function, script file, or operable program. Check the spelling of the > name, or if a path was included, verify that the path is correct and > try again. > > > its likely that python executable not set in the environment variable, set it in your environment variable or navigate to directory where python installed. [How to add to the pythonpath in windows 7?](https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7) Upvotes: 1 <issue_comment>username_2: try: `python3 setup.py install I have both python 2 and 3 installed on my system, so I had to specify. Upvotes: 0
2018/03/18
803
2,554
<issue_start>username_0: Trying to take an integer and return it from the function as an descending integer. I did it first like this: ``` def Descending_Order(num): n = str(num) return(int(n[::-1])) ``` Because the tests only had numbers that were in descending order; kinda cheezy but hey it worked.. Now I want to do a number that is any number and make it return the largest to smallest number. As you can see i tried to dump the int into a string (n) and manipulate it like an array I suppose. EG: 1201 would return 2110 ``` def Descending_Order(num): n = str(num) i = 0 swap = 0 while i < len(n): if i+1>len(n): break elif n[i] < n[i+1]: swap = n[i] n[i]= n[i+1] n[i+1]=swap i+=1 else: i+=1 return(n) print(Descending_Order(1201)) ```<issue_comment>username_1: Strings are iterable so you can pass them into `sorted` like so: ``` def largest_number(num): num = str(num) ordered = ''.join(sorted(num, reverse=True)) return int(ordered) largest_number(87491) >> 98741 ``` [`sorted`](https://docs.python.org/3/library/functions.html#sorted) returns a list, so `sorted('87491', reverse=True)` will return: ``` ['9', '8', '7', '4', '1'] ``` Passing the list into [`join`](https://stackoverflow.com/a/1876206/3407256)(link to explanation of the join method) will return: ``` '98741' ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: A nice one-liner (Basically the same as above: turns into a string, reverse sorts it, back into int): ``` def largest_num (num): return int (sorted (str (num), reverse = True)) ``` Upvotes: -1 <issue_comment>username_3: As other answers noted, this is a sorting problem. You could use the built in sorting function, but that can take a (relatively) long time, and if you are just starting out, it can be good to write your own implementations rather than rely on library magic. Because we are only sorting integers between 0 and 9, we can use a faster sorting algorithm than the timsort that python's `sorted` uses. What we do is count the number of occurrences of each digit. We then construct a number with as many 9s as the we found in the original, then 8s... until 0. ``` def Decending_Order(num): arr = [0,0,0,0,0,0,0,0,0,0] res = [] for i in str(num): arr[int(i)] += 1 for i in range(0,9): while arr[i] > 0: res.append(str(i)) arr[i] -= 1 return res.reverse() ``` Upvotes: 1
2018/03/18
715
2,358
<issue_start>username_0: The method I have is supposed to return a String [] so i used toArray method. But I get error regarding object cannot be converted to strings. I have initialized the list as String as well and am unable to figure out the error that I am getting. Everywhere I read, they say initialize as String and I have already done that. how can I fix it?? ``` ArrayList c = new ArrayList(Arrays.asList(a)); .......(job done) return c.toArray(); ``` --The entire code: ``` public static String[] anagrams(String [] a) { ArrayList b = new ArrayList(Arrays.asList(a)); ArrayList c = new ArrayList(Arrays.asList(a)); int l=a.length; int i,j; for (i=0;i ```<issue_comment>username_1: Strings are iterable so you can pass them into `sorted` like so: ``` def largest_number(num): num = str(num) ordered = ''.join(sorted(num, reverse=True)) return int(ordered) largest_number(87491) >> 98741 ``` [`sorted`](https://docs.python.org/3/library/functions.html#sorted) returns a list, so `sorted('87491', reverse=True)` will return: ``` ['9', '8', '7', '4', '1'] ``` Passing the list into [`join`](https://stackoverflow.com/a/1876206/3407256)(link to explanation of the join method) will return: ``` '98741' ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: A nice one-liner (Basically the same as above: turns into a string, reverse sorts it, back into int): ``` def largest_num (num): return int (sorted (str (num), reverse = True)) ``` Upvotes: -1 <issue_comment>username_3: As other answers noted, this is a sorting problem. You could use the built in sorting function, but that can take a (relatively) long time, and if you are just starting out, it can be good to write your own implementations rather than rely on library magic. Because we are only sorting integers between 0 and 9, we can use a faster sorting algorithm than the timsort that python's `sorted` uses. What we do is count the number of occurrences of each digit. We then construct a number with as many 9s as the we found in the original, then 8s... until 0. ``` def Decending_Order(num): arr = [0,0,0,0,0,0,0,0,0,0] res = [] for i in str(num): arr[int(i)] += 1 for i in range(0,9): while arr[i] > 0: res.append(str(i)) arr[i] -= 1 return res.reverse() ``` Upvotes: 1
2018/03/18
2,137
6,508
<issue_start>username_0: I have two list object A and B like this: ``` A=[ {item:1, value:"ex1"}, {item:2, value:"ex1"}, {item:3, value:"ex1"}, {item:4, value:"ex1"}] B=[{item:1, value:"ex2"}, {item:4, value:"ex2"}, {item:2, value:"ex3"}, {item:5, value:"ex3"}] ``` How can i do to make B to have same items/values like A and still keep its own sequence for items it already has? I want B to remove item 5 because A don't have it, and add in item 3 to the end. I don't want to clone A, I want to modify B to become like A. **What I want is:** * Remove items in B when A don't have them: item5 * Update items in B when both A and B have them: item1, item2, item4 * Add non-existing items to end of B when A have them: item3 So, the result should be like this: ``` B = [ {item:1, value:"ex1"}, {item:4, value:"ex1"}, {item:2, value:"ex1"}, {item:3, value:"ex1"} ] ``` Mycode: (This is what i have now) ``` foreach (myClass itm in A) { foreach (myClass fd in B) { if (itm.item == fd.item) { fd.value = itm.value; } } } ```<issue_comment>username_1: You can do something similar to this: ``` var listA = new List { 1, 3, 5 }; var listB = new List { 1, 4, 3 }; //Removes items in B that aren't in A. //This will remove 4, leaving the sequence of B as 1,3 listB.RemoveAll(x => !listA.Contains(x)); //Gets items in A that aren't in B //This will return the number 5 var items = listA.Where(y => !listB.Any(x => x == y)); //Add the items in A that aren't in B to the end of the list //This adds 5 to the end of the list foreach(var item in items) { listB.Add(item); } //List B should be 1,3,5 Console.WriteLine(listB); ``` Upvotes: -1 <issue_comment>username_2: This is what you specify in the question. I tested it and it works: ``` class myClass { public int item; public string value; //ctor: public myClass(int item, string value) { this.item = item; this.value = value; } } static void updateList() { var listA = new List { new myClass(1, "A1"), new myClass(2, "A2"), new myClass(3, "A3"), new myClass(4, "A4") }; var listB = new List { new myClass(1, "B1"), new myClass(4, "B4"), new myClass(2, "B2"), new myClass(5, "B5") }; for (int i = 0; i < listB.Count; i++) //use index to be able to use RemoveAt which is faster { var b = listB[i]; var j = listA.FindIndex(x => x.item == b.item); if (j >= 0) //A has this item, update its value { var v = listA[j].value; if (b.value != v) b.value = v; } else //A does not have this item { listB.RemoveAt(i); } } foreach (var a in listA) { //if (!listB.Contains(a)) listB.Add(a); if (!listB.Any(b => b.item == a.item)) listB.Add(a); } } ``` Upvotes: 0 <issue_comment>username_3: You can write an extension method that merges the lists by iterating over the keys and checking for existence. ``` static class ExtensionMethods { static public void MergeInto(this Dictionary rhs, Dictionary lhs) { foreach (var key in rhs.Keys.Union(lhs.Keys).Distinct().ToList()) { if (!rhs.ContainsKey(key)) { lhs.Remove(key); continue; } if (!lhs.ContainsKey(key)) { lhs.Add(key, rhs[key]); continue; } lhs[key] = rhs[key]; } } } ``` Test program: ``` public class Program { public static Dictionary A = new Dictionary { { 1,"ex1" }, { 2,"EX2" }, { 3,"ex3" }, }; public static Dictionary B = new Dictionary { { 1,"ex1" }, { 2,"ex2" }, { 4,"ex4" } }; public static void Main() { A.MergeInto(B); foreach (var entry in B ) { Console.WriteLine("{0}={1}", entry.Key, entry.Value); } } } ``` Output: ``` 1=ex1 2=EX2 3=ex3 ``` [Code on DotNetFiddle](https://dotnetfiddle.net/9pK8P2) Upvotes: 1 <issue_comment>username_3: Without preserving order ------------------------ If all you want to do is keep the instance of B, but make it so all its elements match A, you can just do this: ``` B.Clear(); B.AddRange(A); ``` Preserving order ---------------- If you want to preserve order, you can still use the solution above, but you will need to sort the list that is passed to `AddRange()`. This is only a little more work. First, create a lookup table which tells you the order that that Item values originally appeared in. A generic c# `Dictionary` uses a hash table for the keys, so this is going to end up being more efficient than scanning the List repeatedly. Note that we pass `B.Count` to the constructor so that it only needs to allocate space once rather than repeatedly as it grows. ``` var orderBy = new Dictionary(B.Count); for (int i=0; i ``` Now we use our solution, sorting the input list: ``` B.Clear(); B.AddRange ( A.OrderBy( item => orderBy.GetValueOrFallback(item.Item, int.MaxValue) ) ); ``` `GetValueOrFallback` is a simple extension method on `Dictionary<,>` that makes it simpler to deal with keys that may or may not exist. You pass in the key you want, plus a value to return if the key is not found. In our case we pass `int.MaxValue` so that new items will be appended to the end. ``` static public TValue GetValueOrFallback(this Dictionary This, TKey keyToFind, TValue fallbackValue) { TValue result; return This.TryGetValue(keyToFind, out result) ? result : fallbackValue; } ``` Example ------- Put it all together with a test program: ``` public class MyClass { public int Item { get; set; } public string Value { get; set; } public override string ToString() { return Item.ToString() + "," + Value; } } static public class ExtensionMethods { static public TValue ValueOrFallback(this Dictionary This, TKey keyToFind, TValue fallbackValue) { TValue result; return This.TryGetValue(keyToFind, out result) ? result : fallbackValue; } static public void MergeInto(this List mergeFrom, List mergeInto) { var orderBy = new Dictionary(mergeFrom.Count); for (int i=0; i orderBy.ValueOrFallback(item.Item, int.MaxValue) ) ); } } public class Program { public static List A = new List { new MyClass { Item = 2,Value = "EX2" }, new MyClass { Item = 3,Value = "ex3" }, new MyClass { Item = 1,Value = "ex1" } }; public static List B = new List { new MyClass { Item = 1,Value = "ex1" }, new MyClass { Item = 2,Value = "ex2" }, new MyClass { Item = 4,Value = "ex3" }, }; public static void Main() { A.MergeInto(B); foreach (var b in B) Console.WriteLine(b); } } ``` Output: ``` 1,ex1 2,EX2 3,ex3 ``` [Code on DotNetFiddle](https://dotnetfiddle.net/QHBINR) Upvotes: 1
2018/03/18
1,972
6,201
<issue_start>username_0: Sorry I'm finding it difficult to word the issue I'm having correctly.. I have an array called `feedCounter` and an array called `postFeed`. I want to display the length of `feedCounter` and when a user clicks on it `postFeed` becomes equal to `feedCounter`, but when `feedCounter` gets a new element `postFeed` should not update with it... What I'm doing is setting `feedCounter` to a `snapshot` in firebase: ``` this.subscription.on('child_added', (snapshot) => { this.feedCounter.push(snapshot.val()); }); ``` and then in my `html` I do this: ``` {{feedCounter?.length}} ``` The problem is, `postFeed` seems to be getting binded to `feedCounter` after the first time I click on the `div` `postFeed` automatically gets updated, which I do not want.. How can I fix this? Thank you!<issue_comment>username_1: You can do something similar to this: ``` var listA = new List { 1, 3, 5 }; var listB = new List { 1, 4, 3 }; //Removes items in B that aren't in A. //This will remove 4, leaving the sequence of B as 1,3 listB.RemoveAll(x => !listA.Contains(x)); //Gets items in A that aren't in B //This will return the number 5 var items = listA.Where(y => !listB.Any(x => x == y)); //Add the items in A that aren't in B to the end of the list //This adds 5 to the end of the list foreach(var item in items) { listB.Add(item); } //List B should be 1,3,5 Console.WriteLine(listB); ``` Upvotes: -1 <issue_comment>username_2: This is what you specify in the question. I tested it and it works: ``` class myClass { public int item; public string value; //ctor: public myClass(int item, string value) { this.item = item; this.value = value; } } static void updateList() { var listA = new List { new myClass(1, "A1"), new myClass(2, "A2"), new myClass(3, "A3"), new myClass(4, "A4") }; var listB = new List { new myClass(1, "B1"), new myClass(4, "B4"), new myClass(2, "B2"), new myClass(5, "B5") }; for (int i = 0; i < listB.Count; i++) //use index to be able to use RemoveAt which is faster { var b = listB[i]; var j = listA.FindIndex(x => x.item == b.item); if (j >= 0) //A has this item, update its value { var v = listA[j].value; if (b.value != v) b.value = v; } else //A does not have this item { listB.RemoveAt(i); } } foreach (var a in listA) { //if (!listB.Contains(a)) listB.Add(a); if (!listB.Any(b => b.item == a.item)) listB.Add(a); } } ``` Upvotes: 0 <issue_comment>username_3: You can write an extension method that merges the lists by iterating over the keys and checking for existence. ``` static class ExtensionMethods { static public void MergeInto(this Dictionary rhs, Dictionary lhs) { foreach (var key in rhs.Keys.Union(lhs.Keys).Distinct().ToList()) { if (!rhs.ContainsKey(key)) { lhs.Remove(key); continue; } if (!lhs.ContainsKey(key)) { lhs.Add(key, rhs[key]); continue; } lhs[key] = rhs[key]; } } } ``` Test program: ``` public class Program { public static Dictionary A = new Dictionary { { 1,"ex1" }, { 2,"EX2" }, { 3,"ex3" }, }; public static Dictionary B = new Dictionary { { 1,"ex1" }, { 2,"ex2" }, { 4,"ex4" } }; public static void Main() { A.MergeInto(B); foreach (var entry in B ) { Console.WriteLine("{0}={1}", entry.Key, entry.Value); } } } ``` Output: ``` 1=ex1 2=EX2 3=ex3 ``` [Code on DotNetFiddle](https://dotnetfiddle.net/9pK8P2) Upvotes: 1 <issue_comment>username_3: Without preserving order ------------------------ If all you want to do is keep the instance of B, but make it so all its elements match A, you can just do this: ``` B.Clear(); B.AddRange(A); ``` Preserving order ---------------- If you want to preserve order, you can still use the solution above, but you will need to sort the list that is passed to `AddRange()`. This is only a little more work. First, create a lookup table which tells you the order that that Item values originally appeared in. A generic c# `Dictionary` uses a hash table for the keys, so this is going to end up being more efficient than scanning the List repeatedly. Note that we pass `B.Count` to the constructor so that it only needs to allocate space once rather than repeatedly as it grows. ``` var orderBy = new Dictionary(B.Count); for (int i=0; i ``` Now we use our solution, sorting the input list: ``` B.Clear(); B.AddRange ( A.OrderBy( item => orderBy.GetValueOrFallback(item.Item, int.MaxValue) ) ); ``` `GetValueOrFallback` is a simple extension method on `Dictionary<,>` that makes it simpler to deal with keys that may or may not exist. You pass in the key you want, plus a value to return if the key is not found. In our case we pass `int.MaxValue` so that new items will be appended to the end. ``` static public TValue GetValueOrFallback(this Dictionary This, TKey keyToFind, TValue fallbackValue) { TValue result; return This.TryGetValue(keyToFind, out result) ? result : fallbackValue; } ``` Example ------- Put it all together with a test program: ``` public class MyClass { public int Item { get; set; } public string Value { get; set; } public override string ToString() { return Item.ToString() + "," + Value; } } static public class ExtensionMethods { static public TValue ValueOrFallback(this Dictionary This, TKey keyToFind, TValue fallbackValue) { TValue result; return This.TryGetValue(keyToFind, out result) ? result : fallbackValue; } static public void MergeInto(this List mergeFrom, List mergeInto) { var orderBy = new Dictionary(mergeFrom.Count); for (int i=0; i orderBy.ValueOrFallback(item.Item, int.MaxValue) ) ); } } public class Program { public static List A = new List { new MyClass { Item = 2,Value = "EX2" }, new MyClass { Item = 3,Value = "ex3" }, new MyClass { Item = 1,Value = "ex1" } }; public static List B = new List { new MyClass { Item = 1,Value = "ex1" }, new MyClass { Item = 2,Value = "ex2" }, new MyClass { Item = 4,Value = "ex3" }, }; public static void Main() { A.MergeInto(B); foreach (var b in B) Console.WriteLine(b); } } ``` Output: ``` 1,ex1 2,EX2 3,ex3 ``` [Code on DotNetFiddle](https://dotnetfiddle.net/QHBINR) Upvotes: 1
2018/03/18
1,913
5,894
<issue_start>username_0: I cannot figure out how to apply background color to the cell in OpenTBS. I've tried Word's syntax but it did not work. ``` [row.cell.val][row.cell.bg;att=w:shd#w:fill] ``` Code in PHP (simplified) ``` $rs = [ // ... 'cell' => [ 'val' => 5, 'bg' => 'efefef', ], // ... ]; $TBS->MergeBlock('row', $rs); ``` I looked inside XML body of excel document, but could not understand what tags and attributes define the color of the cell. Can anyone help me?<issue_comment>username_1: You can do something similar to this: ``` var listA = new List { 1, 3, 5 }; var listB = new List { 1, 4, 3 }; //Removes items in B that aren't in A. //This will remove 4, leaving the sequence of B as 1,3 listB.RemoveAll(x => !listA.Contains(x)); //Gets items in A that aren't in B //This will return the number 5 var items = listA.Where(y => !listB.Any(x => x == y)); //Add the items in A that aren't in B to the end of the list //This adds 5 to the end of the list foreach(var item in items) { listB.Add(item); } //List B should be 1,3,5 Console.WriteLine(listB); ``` Upvotes: -1 <issue_comment>username_2: This is what you specify in the question. I tested it and it works: ``` class myClass { public int item; public string value; //ctor: public myClass(int item, string value) { this.item = item; this.value = value; } } static void updateList() { var listA = new List { new myClass(1, "A1"), new myClass(2, "A2"), new myClass(3, "A3"), new myClass(4, "A4") }; var listB = new List { new myClass(1, "B1"), new myClass(4, "B4"), new myClass(2, "B2"), new myClass(5, "B5") }; for (int i = 0; i < listB.Count; i++) //use index to be able to use RemoveAt which is faster { var b = listB[i]; var j = listA.FindIndex(x => x.item == b.item); if (j >= 0) //A has this item, update its value { var v = listA[j].value; if (b.value != v) b.value = v; } else //A does not have this item { listB.RemoveAt(i); } } foreach (var a in listA) { //if (!listB.Contains(a)) listB.Add(a); if (!listB.Any(b => b.item == a.item)) listB.Add(a); } } ``` Upvotes: 0 <issue_comment>username_3: You can write an extension method that merges the lists by iterating over the keys and checking for existence. ``` static class ExtensionMethods { static public void MergeInto(this Dictionary rhs, Dictionary lhs) { foreach (var key in rhs.Keys.Union(lhs.Keys).Distinct().ToList()) { if (!rhs.ContainsKey(key)) { lhs.Remove(key); continue; } if (!lhs.ContainsKey(key)) { lhs.Add(key, rhs[key]); continue; } lhs[key] = rhs[key]; } } } ``` Test program: ``` public class Program { public static Dictionary A = new Dictionary { { 1,"ex1" }, { 2,"EX2" }, { 3,"ex3" }, }; public static Dictionary B = new Dictionary { { 1,"ex1" }, { 2,"ex2" }, { 4,"ex4" } }; public static void Main() { A.MergeInto(B); foreach (var entry in B ) { Console.WriteLine("{0}={1}", entry.Key, entry.Value); } } } ``` Output: ``` 1=ex1 2=EX2 3=ex3 ``` [Code on DotNetFiddle](https://dotnetfiddle.net/9pK8P2) Upvotes: 1 <issue_comment>username_3: Without preserving order ------------------------ If all you want to do is keep the instance of B, but make it so all its elements match A, you can just do this: ``` B.Clear(); B.AddRange(A); ``` Preserving order ---------------- If you want to preserve order, you can still use the solution above, but you will need to sort the list that is passed to `AddRange()`. This is only a little more work. First, create a lookup table which tells you the order that that Item values originally appeared in. A generic c# `Dictionary` uses a hash table for the keys, so this is going to end up being more efficient than scanning the List repeatedly. Note that we pass `B.Count` to the constructor so that it only needs to allocate space once rather than repeatedly as it grows. ``` var orderBy = new Dictionary(B.Count); for (int i=0; i ``` Now we use our solution, sorting the input list: ``` B.Clear(); B.AddRange ( A.OrderBy( item => orderBy.GetValueOrFallback(item.Item, int.MaxValue) ) ); ``` `GetValueOrFallback` is a simple extension method on `Dictionary<,>` that makes it simpler to deal with keys that may or may not exist. You pass in the key you want, plus a value to return if the key is not found. In our case we pass `int.MaxValue` so that new items will be appended to the end. ``` static public TValue GetValueOrFallback(this Dictionary This, TKey keyToFind, TValue fallbackValue) { TValue result; return This.TryGetValue(keyToFind, out result) ? result : fallbackValue; } ``` Example ------- Put it all together with a test program: ``` public class MyClass { public int Item { get; set; } public string Value { get; set; } public override string ToString() { return Item.ToString() + "," + Value; } } static public class ExtensionMethods { static public TValue ValueOrFallback(this Dictionary This, TKey keyToFind, TValue fallbackValue) { TValue result; return This.TryGetValue(keyToFind, out result) ? result : fallbackValue; } static public void MergeInto(this List mergeFrom, List mergeInto) { var orderBy = new Dictionary(mergeFrom.Count); for (int i=0; i orderBy.ValueOrFallback(item.Item, int.MaxValue) ) ); } } public class Program { public static List A = new List { new MyClass { Item = 2,Value = "EX2" }, new MyClass { Item = 3,Value = "ex3" }, new MyClass { Item = 1,Value = "ex1" } }; public static List B = new List { new MyClass { Item = 1,Value = "ex1" }, new MyClass { Item = 2,Value = "ex2" }, new MyClass { Item = 4,Value = "ex3" }, }; public static void Main() { A.MergeInto(B); foreach (var b in B) Console.WriteLine(b); } } ``` Output: ``` 1,ex1 2,EX2 3,ex3 ``` [Code on DotNetFiddle](https://dotnetfiddle.net/QHBINR) Upvotes: 1
2018/03/18
1,176
4,117
<issue_start>username_0: My requirement is something like this. 1. I am rendering a question paper from an object using v-for. 2. Once the user **select an answer for a question**, the **question number (index) has to be v-model** with that answer. How can I achieve this? this is my code. ```js Question {{index}} ================== {{question.question}} {{question.answer1}} {{question.answer2}} {{question.answer3}} --- Save and Submit export default { data(){ return{ questions:[ {question:"what is the capital of france?",answer1:"paris",answer2:"normandy",answer3:"rome"}, {question:"what is the capital of france?",answer1:"paris",answer2:"normandy",answer3:"rome"}, {question:"what is the capital of france?",answer1:"paris",answer2:"normandy",answer3:"rome"}] } } } ```<issue_comment>username_1: Use a `v-model` to in the radioboxes. A simple way to do that is to create a `selectedAnswer` property in each `question` and bind `v-model` to it, like: ```html {{question.answer1}} ``` Notice also that I removed the `name`. You were using the same `name` attributes to **all** checkboxes, and HTML will only allow one selected radio per group (per `name`) To get **an array of selected answers**, you could simply create a computed property that maps the selected answers into an array. In the example below, the `this.answers` computed property is available with the answers. Full demo below. ```js new Vue({ el: '#app', data() { return { questions: [{ question: "what is the capital of france?", answer1: "paris", answer2: "normandy", answer3: "rome", selectedAnswer: null }, { question: "what is the capital of france?", answer1: "paris", answer2: "normandy", answer3: "rome", selectedAnswer: null }, { question: "what is the capital of france?", answer1: "paris", answer2: "normandy", answer3: "rome", selectedAnswer: null } ] } }, computed: { answers() { return this.questions.map(q => q.selectedAnswer); } } }); ``` ```html Answers: {{ answers }} Question {{index}} ================== {{question.question}} | selected: {{question.selectedAnswer || 'none'}} {{question.answer1}} {{question.answer2}} {{question.answer3}} --- Save and Submit ``` Upvotes: 2 <issue_comment>username_2: I feel `v-model` might not be the right solution in this case. Here is what I suggest you to do. ``` Question {{index}} ================== {{question.question}} {{question.answer1}} {{question.answer2}} {{question.answer3}} --- Save and Submit export default { data() { return { questions: [ { question: "what is the capital of france?", answer1: "paris", answer2: "normandy", answer3: "rome" }, { question: "what is the capital of france?", answer1: "paris", answer2: "normandy", answer3: "rome" }, { question: "what is the capital of france?", answer1: "paris", answer2: "normandy", answer3: "rome" } ] }; }, methods: { answerSelect(questionIndex, answer) { const questions = [ ...this.questions.slice(0, questionIndex), { ...this.questions[questionIndex], solution: answer }, ...this.questions.slice(questionIndex + 1, this.questions.length) ]; this.questions = questions; } } }; #app { font-family: "Avenir", Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } ``` Here is a link to the code sandbox. <https://codesandbox.io/s/o5r2xqypo9> Upvotes: 2 <issue_comment>username_3: ``` Question {{index}} ================== {{question.question}} {{question.answer1}} {{question.answer2}} {{question.answer3}} --- Save and Submit ``` **Method** ``` pushAnswers(questionIndex,answer) { this.answerSet[questionIndex] = answer; console.log(this.answerSet); } ``` Upvotes: 3 [selected_answer]
2018/03/18
3,557
9,781
<issue_start>username_0: I'm trying to understand assembly in x86 more. I have a mystery function here that I know returns an `int` and takes an `int` argument. So it looks like `int mystery(int n){}`. I can't figure out the function in C however. The assembly is: ``` mov %edi, %eax lea 0x0(,%rdi, 8), %edi sub %eax, %edi add $0x4, %edi callq < mystery _util > repz retq < mystery _util > mov %edi, %eax shr %eax and $0x1, %edi and %edi, %eax retq ``` I don't understand what the lea does here and what kind of function it could be.<issue_comment>username_1: The LEA is just a left-shift by 3, and truncating the result to 32 bit (i.e. zero-extending EDI into RDI implicilty). x86-64 System V passes the first integer arg in RDI, so all of this is consistent with one `int` arg. LEA uses memory-operand syntax and machine encoding, [but it's really just a shift-and-add instruction](https://stackoverflow.com/questions/46597055/address-computation-instruction-leaq/46597375#46597375). Using it as part of a multiply by a constant [is a common compiler optimization for x86](https://stackoverflow.com/questions/46597055/address-computation-instruction-leaq/46597375#46597375). The compiler that generated this function missed an optimization here; the first `mov` could have been avoided with ``` lea 0x0(,%rdi, 8), %eax # n << 3 = n*8 sub %edi, %eax # eax = n*7 lea 4(%rax), %edi # rdi = 4 + n*7 ``` But instead, the compiler got stuck on generating `n*7` in `%edi`, probably because it applied a peephole optimization for the constant multiply too late to redo register allocation. --- `mystery_util` returns the bitwise AND of the low 2 bits of its arg, in the low bit, so a 0 or 1 integer value, which could also be a `bool`. (`shr` with no count means a count of 1; remember that x86 has a special opcode for shifts with an implicit count of 1. 8086 only has counts of 1 or `cl`; immediate counts were added later as an extension and the implicit-form opcode is still shorter.) Upvotes: 2 <issue_comment>username_2: The `LEA` performs an address computation, but instead of dereferencing the address, it stores the computed address into the destination register. In AT&T syntax, `lea C(b,c,d), reg` means `reg = C + b + c*d` where `C` is a constant, and `b`,`c` are registers and `d` is a scalar from {1,2,4,8}. Hence you can see why LEA is popular for simple math operations: it does quite a bit in a single instruction. (\*includes correction from prl's comment below) There are some strange features of this assembly code: the `repz` prefix is only strictly defined when applied to certain instructions, and `retq` is not one of them (though the general behavior of the processor is to ignore it). See username_3's comment below with a link for more info. The use of `lea (,rdi,8), edi` followed by `sub eax, edi` to compute `arg1 * 7` also seemed strange, but makes sense once prl noted the scalar `d` had to be a constant power of 2. In any case, here's how I read the snippet: ``` mov %edi, %eax ; eax = arg1 lea 0x0(,%rdi, 8), %edi ; edi = arg1 * 8 sub %eax, %edi ; edi = (arg1 * 8) - arg1 = arg1 * 7 add $0x4, %edi ; edi = (arg1 * 7) + 4 callq < mystery _util > ; call mystery_util(arg1 * 7 + 4) repz retq ; repz prefix on return is de facto nop. < mystery _util > mov %edi, %eax ; eax = arg1 shr %eax ; eax = arg1 >> 1 and $0x1, %edi ; edi = 1 iff arg1 was odd, else 0 and %edi, %eax ; eax = 1 iff smallest 2 bits of arg1 were both 1. retq ``` Note the `+4` on the 4th line is entirely spurious. It cannot affect the outcome of mystery\_util. So, overall this ASM snippet computes the boolean (arg1 \* 7) % 4 == 3. Upvotes: 1 <issue_comment>username_3: The assembly code appeared to be computer generated, and something that was probably compiled by GCC since there is a `repz retq` after an unconditional branch (`call`). There is also an indication that because there isn't a tail call (`jmp`) instead of a `call` when going to `mystery_util` that the code was compiled with `-O1` (higher optimization levels would likely inline the function which didn't happen here). The lack of frame pointers and extra load/stores indicated that it isn't compiled with `-O0` Multiplying `x` by 7 is the same as multiplying `x` by 8 and subtracting `x`. That is what the following code is doing: ``` lea 0x0(,%rdi, 8), %edi sub %eax, %edi ``` [LEA](http://www.felixcloutier.com/x86/LEA.html) can compute addresses but it can be used for simple arithmetic as well. The syntax for a memory operand is displacement(base, index, scale). Scale can be 1, 2, 4, 8. The computation is displacement + base + index \* scale. In your case `lea 0x0(,%rdi, 8), %edi` is effectively EDI = 0x0 + RDI \* 8 or EDI = RDI \* 8. The full calculation is n \* 7 - 4; The calculation for `mystery_util` appears to simply be ``` n &= (n>>1) & 1; ``` If I take all these factors together we have a function `mystery` that passes n \* 7 - 4 to a function called `mystery_util` that returns `n &= (n>>1) & 1`. Since `mystery_util` returns a single bit value (0 or 1) it is reasonable that `bool` is the return type. I was curious if I could get a particular version of *GCC* with optimization level 1 (`-O1`) to reproduce this assembly code. I discovered that GCC 4.9.x will yield this **exact assembly code** for this given *C* program: ``` #include bool mystery\_util(unsigned int n) { n &= (n>>1) & 1; return n; } bool mystery(unsigned int n) { return mystery\_util (7\*n+4); } ``` The assembly output is: ``` mystery_util: movl %edi, %eax shrl %eax andl $1, %edi andl %edi, %eax ret mystery: movl %edi, %eax leal 0(,%rdi,8), %edi subl %eax, %edi addl $4, %edi call mystery_util rep ret ``` You can play with this code on [godbolt](https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,lang:c%2B%2B,source:'%23include%3Cstdbool.h%3E%0A%0Abool+mystery_util(unsigned+int+n)%0A%7B%0A++++n+%26%3D+(n%3E%3E1)+%26+1%3B%0A++++return+n%3B%0A%7D%0A%0Abool+mystery(unsigned+int+n)%0A%7B%0A++++return+mystery_util+(7*n%2B4)%3B%0A%7D%0A'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:33.333333333333336,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g494,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'1',directives:'0',execute:'1',intel:'1',trim:'1'),lang:c%2B%2B,libs:!(),options:'-xc+-O1+-m64',source:1),l:'5',n:'0',o:'x86-64+gcc+4.9.4+(Editor+%231,+Compiler+%231)+C%2B%2B',t:'0')),k:33.333333333333336,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compiler:1,editor:1),l:'5',n:'0',o:'%231+with+x86-64+gcc+4.9.4',t:'0')),k:33.33333333333333,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4). --- Important Update - Version without bool --------------------------------------- I apparently erred in interpreting the question. I assumed the person asking this question determined by themselves that the prototype for `mystery` was `int mystery(int n)`. I thought I could change that. According to a [related question](https://stackoverflow.com/questions/49353995/finding-the-c-function-from-assembly-through-reverse-engineer) asked on Stackoverflow a day later, it seems `int mystery(int n)` is given to you as the prototype as part of the assignment. This is important because it means that a modification has to be made. The change that needs to be made is related to `mystery_util`. In the code to be reverse engineered are these lines: ``` mov %edi, %eax shr %eax ``` *EDI* is the first parameter. *SHR* is logical shift right. Compilers would only generate this if *EDI* was an `unsigned int` (or equivalent). `int` is a signed type an would generate *SAR* (arithmetic shift right). This means that the parameter for `mystery_util` has to be `unsigned int` (and it follows that the return value is likely `unsigned int`. That means the code would look like this: ``` unsigned int mystery_util(unsigned int n) { n &= (n>>1) & 1; return n; } int mystery(int n) { return mystery_util (7*n+4); } ``` `mystery` now has the prototype given by your professor (`bool` is removed) and we use `unsigned int` for the parameter and return type of `mystery_util`. In order to generate this code with GCC 4.9.x I found you need to use `-O1 -fno-inline`. This code can be found on [godbolt](https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,lang:c%2B%2B,source:'%0Aunsigned+int+mystery_util(unsigned+int+n)%0A%7B%0A++++n+%26%3D+(n%3E%3E1)+%26+1%3B%0A++++return+n%3B%0A%7D%0A%0Aint+mystery(int+n)%0A%7B%0A++++return+mystery_util+(7*n%2B4)%3B%0A%7D%0A%0A'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:33.333333333333336,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g494,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'1',directives:'0',execute:'1',intel:'1',trim:'1'),lang:c%2B%2B,libs:!(),options:'-xc+-O1+-m64+-fno-inline+-Wall+-pedantic+-ansi',source:1),l:'5',n:'0',o:'x86-64+gcc+4.9.4+(Editor+%231,+Compiler+%231)+C%2B%2B',t:'0')),k:33.333333333333336,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compiler:1,editor:1),l:'5',n:'0',o:'%231+with+x86-64+gcc+4.9.4',t:'0')),k:33.33333333333333,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4). The assembly output is the same as the version using `bool`. If you use `unsigned int mystery_util(int n)` you would discover that it doesn't quite output what we want: ``` mystery_util: movl %edi, %eax sarl %eax ; <------- SAR (arithmetic shift right) is not SHR andl $1, %edi andl %edi, %eax ret ``` Upvotes: 4 [selected_answer]
2018/03/18
515
1,281
<issue_start>username_0: I select an input on cell L10 using a drop down list. The values of the list are AH11, AH12, AH13, AH14, AH15 and AH16 Base on this selection, I want to auto populate the value in another cell. I used the following formula in my target cell ``` =IF(OR(L10="AH11",L10="AH12"),"6",IF(OR(L10="AH15",L10="AH16"),"18")) ``` This works because AH11 and AH12 have the same values. Similarly for AH15 and 16. But AH13 and AH 14 have their unique values. How do I improve the formula to display values for AH13 and AH14 also?<issue_comment>username_1: Just nest the IF's further: ``` =IF(OR(L10="AH11",L10="AH12"),"6",IF(OR(L10="AH15",L10="AH16"),"18", IF(L10="AH13", "xx", IF(L10="AH14","yy")))) ``` Upvotes: 1 <issue_comment>username_2: Build an INDEX/MATCH using array constants instead of cell ranges. ``` =index({6, 6, 99, 100, 18, 18}, match(L10, {"AH11", "AH12", "AH13", "AH14", "AH15", "AH16"} , 0)) 'with these progressive lookup values it can be shortened to, =index({6, 99, 100, 18}, match(L10, {"AH11", "AH13", "AH14", "AH15"})) ``` I don't recommend that you return quoted text-that-looks-like-numbers. While there are limited special cases where this is desirable, it is almost always better to leave numbers as true numbers. Upvotes: 0
2018/03/18
1,654
5,268
<issue_start>username_0: I have a float for totalPoints which is being automatically increased by the Timer, but after totalPoints reaches certain number, it doesn't seem to increase no more. I did not put any limits so I'm not sure why is it happening. So, totalPoints stops increasing when it reaches "2097152" value. Here's part of my code: ``` public float totalPoins; void AccumulatePoints() { timer += Time.deltaTime * miningPowerValue; if (timer > 1f) { totalPoints += someValue; timer = 0; } } ``` So basically it accumulates points depending on **miningPowerValue**. If its low, it will accumulate on a slower rate, higher - faster. Please help. I'm confused.<issue_comment>username_1: Floating-point numbers get less precise as they get bigger. You've ran into a case where they're big enough that the amount you're trying to add is smaller than the smallest possible difference between numbers of that size. Switch to `double` or something else with more precision. Upvotes: 3 <issue_comment>username_2: To expand on <NAME>'s answer in a way that I can't simply through a comment. A [single-precision floating-point value](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) is a method of specifying a floating-point value, and in most programming languages is defined by the specification of IEEE 754. We can assume that C#'s floating-point values conform to IEEE 754. Floating point values are given a certain amount of bytes, which they use in three chunks: The sign (positive or negative), the exponent ('y' in x \* 10^y), and the value ('x' in x \* 10^y). (Note: The definition of these three chunks is a little more elaborate than stated here, but for this example, it suffices). In other words, a floating point value would encode the value "2,000.00" as "positive, 3, 2". That is, positive 2 \* 10^3, or 2 \* 1000, or 2,000. This means that a floating point value can represent a *very large* value, but it also means that very large values tend to encounter errors. At a certain point, floats need to start "lopping off" the end of their information, in order to get the best approximation for the space they have. For example, assume we were trying to use a very small version of a floating point value to define the value `1,234,567`, and it only has the space for 4 digits in its `x`. `1,234,567` would become "positive, 6, 1.234"; `1.234 + 10 ^ 6`, which calculates to `1.234 * 1,000,000`, which calculates to `1,234,000` - the last three digits are removed, because they are the "least significant" for the purposes of estimation. Assume we store this value to the variable `Foo`. Now, say you try to add `1` to this value, via `Foo += 1`. The value would become `1,234,001`. But since our floating-point value can only store the 4 largest digits, that 1 gets ignored. `1,234,000` is a *good enough* approximation for `1,234,001`. Even if you added `1` a thousand times, it wouldn't change anything because it gets rounded off every time you add. Meanwhile, adding `1,000` directly would, in fact, have an effect. This is what is happening in your code, on a much larger scale, and what <NAME> was trying to convey. This also explains why `totalPoints += 0.5f` will work when `0.1136f` wont - `0.5` is a larger number than `0.1136`, which means that `0.1136` stops being "significant" before `0.5` does. He recommended you use `double`, which is *more precise*. A [double-precision floating-point value](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) is similar to a single-precision floating point value, but considerably larger; that is, a `double` can store more bits than a `float` (about twice as many, in fact), so smaller numbers won't be lost as easily. This would solve your problem, at least up until the point where double needs to start lopping off small numbers again! Upvotes: 2 <issue_comment>username_3: The problem is that you are exceeding the precision of a `float' which is only 7 digits. Look at the following simple code: ``` void Main() { float f = 0.0f; float i = 0.1136f; int j = 0; while (f <= 3000000.0f) //I arbitrarily chose 3 million here for illustration { f += i; //Only print after every 1000th iteration of the loop if (j % 1000 == 0) { Console.WriteLine(f); } j++; } } ``` At the beginning of this code you will see values like the following: ``` 0.1136 113.7148 227.3164 340.9067 454.4931 568.0796 ``` Then, after a bit, the decimal portion starts shrinking as the whole number portion grows: ``` 9430.525 9543.807 9657.088 9770.369 9883.65 9996.932 10110.21 10223.49 10336.78 10450.06 10563.34 ``` But as the value gets higher and higher, it eventually just outputs this: ``` 999657.9 999782.9 999907.9 1000033 1000158 1000283 1000408 1000533 1000658 1000783 ``` Notice how the part after decimal shrinks but the part before it increases? Since the `float` data type only has 7 digits of precision, the least significant digits after the decimal point are chopped off. `double` on the other hand has 16 digits of precision. I hope this helps to explain what is happening. Upvotes: 2 [selected_answer]
2018/03/18
1,464
3,456
<issue_start>username_0: I'm trying to come up with a function that does the following to a `data.frame` outputting a new `data.frame` with the same names: **1-** Creates a `seq(min(target), max(target), .1)`. **2-** Takes the *mean of all other* variables. For example, if `q` is our `data.frame`, and `jen` is the `target` in it, I want to reformat `q` such that `jen`'s data becomes `seq(min(jen), max(jen), .1)`, and both `bob` and `joe` just change to their mean values. Is it possible to do this in R? I tried something but it is far from being accurate. ``` q = data.frame(bob = 1:5 - 3, jen = c(1.7, 2.6, 2.5, 4.4, 3.8) - 3, joe = 5:9) change <- function(dataframe = q, target = "jen"){ n <- names(dataframe) dataframe[target] <- seq(from = min(target), max(target), .1) } ```<issue_comment>username_1: A base R solution. My idea is to create the target column first in the function, and then use a for-loop to add the mean of other columns. ``` # Example data frame q <- data.frame(bob = 1:5 - 3, jen = c(1.7, 2.6, 2.5, 4.4, 3.8) - 3, joe = 5:9) # Create then function change <- function(dat, target){ vec <- dat[, target] target_new <- seq(min(vec), max(vec), by = 0.1) dat2 <- data.frame(target_new) names(dat2) <- target for (i in names(dat)[!names(dat) %in% target]){ dat2[[i]] <- mean(dat[[i]]) } dat2 <- dat2[, names(dat)] return(dat2) } # Apply the function change(q, "jen") # bob jen joe # 1 0 -1.3 7 # 2 0 -1.2 7 # 3 0 -1.1 7 # 4 0 -1.0 7 # 5 0 -0.9 7 # 6 0 -0.8 7 # 7 0 -0.7 7 # 8 0 -0.6 7 # 9 0 -0.5 7 # 10 0 -0.4 7 # 11 0 -0.3 7 # 12 0 -0.2 7 # 13 0 -0.1 7 # 14 0 0.0 7 # 15 0 0.1 7 # 16 0 0.2 7 # 17 0 0.3 7 # 18 0 0.4 7 # 19 0 0.5 7 # 20 0 0.6 7 # 21 0 0.7 7 # 22 0 0.8 7 # 23 0 0.9 7 # 24 0 1.0 7 # 25 0 1.1 7 # 26 0 1.2 7 # 27 0 1.3 7 # 28 0 1.4 7 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: My solution uses colMeans function and repeats the result as many times as the sequence is long. Then I replace the target column with the sequence results. ``` q = data.frame(bob = 1:5 - 3, jen = c(1.7, 2.6, 2.5, 4.4, 3.8) - 3, joe = 5:9) manip <- function(target, df){ t.column <- which(colnames(df) == target) dfmeans <- colMeans(df) minmax <- range(df[,t.column],na.rm = T) t.seq <- seq(minmax[1],minmax[2],.1) newdf <- matrix(dfmeans, ncol = length(dfmeans))[rep(1, length(t.seq)),] newdf[,t.column] <- t.seq colnames(newdf) <- colnames(df) return(as.data.frame(newdf)) } manip("jen",q) ``` Upvotes: 1 <issue_comment>username_3: Here is one option with `base R` ``` data.frame(Map(function(x, y) if(x=="mean") get(x)(y) else get(x)(min(y), max(y), by = 0.1), setNames(c("mean", "seq", "mean"), names(q)), q)) ``` --- Or with `dplyr` ``` library(dplyr) q %>% summarise(bob = mean(bob), jen = list(seq(min(jen), max(jen), by = 0.1)), joe = mean(joe)) %>% unnest ``` Or if there are many columns to get the `mean` and only a single column sequence, then instead of specifying one by one ``` q %>% mutate_at(c(1,3), mean) %>% group_by(bob, joe) %>% summarise(jen = list(seq(min(jen), max(jen), by = 0.1))) %>% unnest ``` Or use `complete` ``` q %>% group_by(bob = mean(bob), joe = mean(joe)) %>% complete(jen = seq(min(jen), max(jen), by = .1)) ``` Upvotes: 2
2018/03/18
937
3,310
<issue_start>username_0: I've just started with Jekyll and have been working through tutorials. I wanted to try one of the supported gem-based themes instead of the default Minima theme. Running on `localhost:4000` ... No matter what I do, my site renders using the Minima theme. I've read elsewhere about pages *not rendering* because of mis-matched front matter or different default directories. That's not happening to me. My page always renders as if the theme is Minima. This is my `Gemfile`: ``` source "https://rubygems.org" gem "github-pages", group: :jekyll_plugins gem "jekyll-theme-cayman" gem "jekyll-theme-hacker" gem "minima" ``` I updated `_config.yml` to use a specific theme: ``` theme: jekyll-theme-hacker ``` When I run `bundle install` everything looks fine .. no errors. When I run `bundle exec jeckyll build`, also no warnings or errors. What am I missing?<issue_comment>username_1: As mentioned on GitHub repo of the theme [here](https://github.com/pages-themes/hacker#usage) you need to define the group of the gem in order to be previewed locally. ``` source "https://rubygems.org" gem "github-pages", group: :jekyll_plugins gem "jekyll-theme-cayman" gem "jekyll-theme-hacker", group: :jekyll_plugins gem "minima" ``` this might be your issue. Upvotes: 0 <issue_comment>username_2: TL;DR: I'm chalking this up to conflicting versions of jekyll. At various points I found jekyll versions 3.0.1, 3.6.2, and 3.7.3. I removed all versions then installed 3.7.3 Details: I decided to make a new site to test things, and then tried changing themes in a similar manner to my original question. What I noticed was that the new site's Gemfile and \_config.yml looked different than those from the old site. And, the Gemfile explicitly specified `gem "jekyll", "~> 3.7.2"`, whereas my old Gemfile didn't have this line. That is what prompted me to look into version conflicts. Last week I installed jekyll via `apt-get`. This was the version that was installed: ``` username_2@computer:ga_blog$ jekyll --version jekyll 3.0.1 ``` Last night I reinstalled and this happened: ``` username_2@computer:ga_blog$ sudo gem install jekyll Successfully installed jekyll-3.7.3 Parsing documentation for jekyll-3.7.3 Done installing documentation for jekyll after 0 seconds 1 gem installed username_2@computer:ga_blog$ bundle exec jekyll --version jekyll 3.6.2 ``` Clearly, something was up with versions. So, I did: ``` username_2@computer:ga_blog$ sudo apt-get --purge autoremove jekyll username_2@computer:ga_blog$ sudo gem install jekyll Successfully installed jekyll-3.7.3 Parsing documentation for jekyll-3.7.3 Done installing documentation for jekyll after 0 seconds 1 gem installed username_2@computer:ga_blog$ jekyll --version WARN: Unresolved specs during Gem::Specification.reset: rouge (< 4, >= 1.7) WARN: Clearing out unresolved specs. Please report a bug if this causes problems. jekyll 3.7.3 ``` Though I get a warning, everything seems to be working fine now. I tried to do `gem cleanup rouge`, like they did [here](https://stackoverflow.com/questions/17936340/unresolved-specs-during-gemspecification-reset), but still get the same warning. Changing themes now works as expected. I guess I should have avoided apt-get and used the gem to install. Upvotes: 2
2018/03/18
302
954
<issue_start>username_0: I can say - (if key = 'Left') or (if key = 'Right'), but for some reason i can't say - (if key = 'Enter'). Why isn't this working? Can I not use the enter key for getKey in graphics.py?<issue_comment>username_1: The key value comes from the `_onkey` event listener: ``` def _onKey(self, evnt): self.lastKey = evnt.keysym ``` You can see the valid keysyms for Tk [here](https://www.tcl.tk/man/tcl8.4/TkCmd/keysyms.htm). This lists `Return` as a valid type, as well as `KP_Enter` for the keypad enter key. Upvotes: 0 <issue_comment>username_2: Old thread, but I had the same problem and looked through the graphics.py module to find out how it worked. Looks like it uses tkinter's key input system, supported keys are here [<https://www.tcl.tk/man/tcl8.4/TkCmd/keysyms.htm][1]> As for my code, this worked: ``` keyString = win.getKey() if(keyString == "Return"): #do your thing here ``` Hope it helps! Upvotes: 1
2018/03/18
650
2,336
<issue_start>username_0: I understand the whole process of dialogflow and I have a working deployed bot with 2 different intents. How do I actually get the response from the bot when a user answers questions? (I set the bot on fulfillment to go to my domain). Using rails 5 app and it's deployed with Heroku. Thanks!<issue_comment>username_1: Not Entirely familiar with Dilogflow, but if you want to receive a response when an action occurs on another app this usually mean you need to receive web-hooks from them > > A WebHook is an HTTP callback: an HTTP POST that occurs when something happens; a simple event-notification via HTTP POST. A web application implementing WebHooks will POST a message to a URL when certain things happen. > > > I would recommend checking their [fulfillment](https://dialogflow.com/docs/fulfillment) documentation for an example. Hope this helps you out. Upvotes: 0 <issue_comment>username_2: If you have already set the `GOOGLE_APPLICATION_CREDENTIALS` path to the jso file, now you can test using a ruby script. 1. Create a ruby file -> ex: `chatbot.rb` 2. Write the code bellow in the file. > > > ``` > project_id = "Your Google Cloud project ID" > session_id = "mysession" > texts = ["hello"] > language_code = "en-US" > > require "google/cloud/dialogflow" > > session_client = Google::Cloud::Dialogflow::Sessions.new > session = session_client.class.session_path project_id, session_id > puts "Session path: #{session}" > > texts.each do |text| > query_input = { text: { text: text, language_code: language_code } } > response = session_client.detect_intent session, query_input > query_result = response.query_result > > puts "Query text: #{query_result.query_text}" > puts "Intent detected: #{query_result.intent.display_name}" > puts "Intent confidence: #{query_result.intent_detection_confidence}" > puts "Fulfillment text: #{query_result.fulfillment_text}\n" > end > > ``` > > 3. Insert your project\_id. You can find this information on your agent on Dialogflow. Click on the gear on the right side of the Agent's name in the left menu. 4. Run the ruby file in the terminal or in whatever you using to run ruby files. Then you see the bot replying to the "hello" message you have sent. Obs: Do not forget to install the google-cloud gem: Upvotes: 1
2018/03/18
570
1,894
<issue_start>username_0: I have a content column in my table data and it is varchar type. I wonder is there a way to just show part of the content if it has long text like 2000 characters. I just don't want to see everything displayed in my row unless I want to click on it. Partial texts in option is checked by default. I am just hoping there is a way to reduce the height of my row. [![enter image description here](https://i.stack.imgur.com/f4BZg.png)](https://i.stack.imgur.com/f4BZg.png) [![enter image description here](https://i.stack.imgur.com/JTWxu.png)](https://i.stack.imgur.com/JTWxu.png)<issue_comment>username_1: **UPDATE**: Since this is about phpMyAdmin and not PHP and/or MySQL, then this is how you display less content/text in phpMyAdmin: [![enter image description here](https://i.stack.imgur.com/7pbqE.png)](https://i.stack.imgur.com/7pbqE.png) --- **This is how you replace multiple newlines into one:** So you want to replace multiple newline's with just one? Just modify the input of the user before `INSERT`ing it to the database. You can use [`preg_replace`](http://php.net/manual/en/function.preg-replace.php). For example: ``` php $val = 'test test test'; $val = preg_replace("/[\r\n]+/", "\n", $val); // This is optional: //$text = nl2br($text); echo $val; ? ``` Upvotes: 0 <issue_comment>username_2: Before entering the data into the database you can use the pre tag. Something like this `$description=" ``` " . $description . " ``` ";` Pre stands for preformatted text. Upvotes: -1 <issue_comment>username_3: If it's a PHPMyadmin question. There is a link in its interface where you can limit how long is viewable of a column. [![enter image description here](https://i.stack.imgur.com/YAW44.png)](https://i.stack.imgur.com/YAW44.png) If my memory serves me correct it sometimes is labeled 'full texts' as well, which is also a link. Upvotes: 1
2018/03/18
302
1,124
<issue_start>username_0: I am trying to create an Android calculator which uses strings in Kotlin. I do not know how to delete a comma (or the negative) if it already contains one. Here is my code which adds the comma correctly but doesn't delete it if the user clicks again: ```kotlin if (!buClickValue.contains(".")) { buClickValue += "." } else { buClickValue.replace(".", "") } ```<issue_comment>username_1: The `replace()` method is designed to return the value of the new `String` after replacing the characters. In your case, the value obtained after replacing the characters is never reassigned back to the original variable. Specifically in your else clause, the line should be changed to - ``` buClickValue = buClickValue.replace(".", "") ``` Upvotes: 8 [selected_answer]<issue_comment>username_2: The more logical technic is not to replace but to filter ``` buClickValue = buClickValue.filterNot { it == "."[0] } or buClickValue = buClickValue.filterNot { it == '.' } ``` Or to extend ``` filtered = ".,;:" buClickValue = buClickValue.filterNot { filtered.indexOf(it) > -1 } ``` Upvotes: 4
2018/03/18
1,151
3,401
<issue_start>username_0: Is there any way to replace range of numbers wih single numbers in a character string? Number can range from n-n, most probably around 1-15, 4-10 ist also possible. the range could be indicated with a) - ``` a <- "I would like to buy 1-3 cats" ``` or with a word b) for example: to, bis, jusqu'à ``` b <- "I would like to buy 1 jusqu'à 3 cats" ``` The results should look like ``` "I would like to buy 1,2,3 cats" ``` I found this: [Replace range of numbers with certain number](https://stackoverflow.com/questions/31359954/replace-range-of-numbers-with-certain-number) but could not really use it in R.<issue_comment>username_1: This is, in fact, a little tricky, unless someone has already written a package that does this (that I'm not aware of). ``` a <- "I would like to buy 1-3 cats" pos <- unlist(gregexpr("\\d+\\D+", a)) a_split <- unlist(strsplit(a, "")) replacement <- paste(seq.int(a_split[pos[1]], a_split[pos[2]]), collapse = ",") gsub("\\d+\\D+\\d+", replacement, a) # [1] "I would like to buy 1,2,3 cats" ``` EDIT: To show that the same solution works for arbitrary non digit characters between two numbers: ``` b <- "I would like to buy 1 jusqu'à 3 cats" pos_b <- unlist(gregexpr("\\d+\\D+", b)) b_split <- unlist(strsplit(b, "")) replacement <- paste(seq.int(b_split[pos_b[1]], b_split[pos_b[2]]), collapse = ",") gsub("\\d+\\D+\\d+", replacement, b) # [1] "I would like to buy 1,2,3 cats" ``` You can add arbitrary requirements for the run of nondigit characters if you'd like. If you need help with that, just share what the limits on the words or symbols that are between the numbers are! Upvotes: 2 <issue_comment>username_2: Not the most efficient, but ... ``` s <- c("I would like to buy 1-3 cats", "I would like to buy 1 jusqu'à 3 cats", "foo 22-33", "quux 11-3 bar") gre <- gregexpr("([0-9]+(-| to | bis | jusqu'à )[0-9]+)", s) gre2 <- gregexpr('[0-9]+', regmatches(s, gre)) regmatches(s, gre) <- lapply(regmatches(regmatches(s, gre), gre2), function(a) paste(do.call(seq, as.list(as.integer(a))), collapse = ",")) s # [1] "I would like to buy 1,2,3 cats" "I would like to buy 1,2,3 cats" # [3] "foo 22,23,24,25,26,27,28,29,30,31,32,33" "quux 11,10,9,8,7,6,5,4,3 bar" ``` Upvotes: 2 <issue_comment>username_3: `gsubfn` in the gsubfn package is like `gsub` but instead of replacing the match with a replacement string it allows the user to specify a function (possibly in formula notation as done here). It then passes the matches to the capture groups in the regular expression, i.e. the matches to the parenthesized parts of the regular expression, as separate arguments and replaces the entire match with the output of the function. Thus we match `"(\\d+)(-| to | bis | jusqu'à )(\\d+)"` which results in three capture groups so 3 arguments to the function. In the function we use `seq` with the first and third of these. Note that `seq` can take character arguments and interpret them as numeric so we did not have to convert the arguments to numeric. Thus we get this one-liner: ``` library(gsubfn) s <- c(a, b) # test input strings gsubfn("(\\d+)(-| to | bis | jusqu'à )(\\d+)", ~ paste(seq(..1, ..3), collapse = ","), s) ``` giving: ``` [1] "I would like to buy 1,2,3 cats" "I would like to buy 1,2,3 cats" ``` Upvotes: 4 [selected_answer]
2018/03/18
979
2,937
<issue_start>username_0: I want to design an API that serves all the files in my django media directory in response to a GET request-- what should my app's view.py look like?<issue_comment>username_1: This is, in fact, a little tricky, unless someone has already written a package that does this (that I'm not aware of). ``` a <- "I would like to buy 1-3 cats" pos <- unlist(gregexpr("\\d+\\D+", a)) a_split <- unlist(strsplit(a, "")) replacement <- paste(seq.int(a_split[pos[1]], a_split[pos[2]]), collapse = ",") gsub("\\d+\\D+\\d+", replacement, a) # [1] "I would like to buy 1,2,3 cats" ``` EDIT: To show that the same solution works for arbitrary non digit characters between two numbers: ``` b <- "I would like to buy 1 jusqu'à 3 cats" pos_b <- unlist(gregexpr("\\d+\\D+", b)) b_split <- unlist(strsplit(b, "")) replacement <- paste(seq.int(b_split[pos_b[1]], b_split[pos_b[2]]), collapse = ",") gsub("\\d+\\D+\\d+", replacement, b) # [1] "I would like to buy 1,2,3 cats" ``` You can add arbitrary requirements for the run of nondigit characters if you'd like. If you need help with that, just share what the limits on the words or symbols that are between the numbers are! Upvotes: 2 <issue_comment>username_2: Not the most efficient, but ... ``` s <- c("I would like to buy 1-3 cats", "I would like to buy 1 jusqu'à 3 cats", "foo 22-33", "quux 11-3 bar") gre <- gregexpr("([0-9]+(-| to | bis | jusqu'à )[0-9]+)", s) gre2 <- gregexpr('[0-9]+', regmatches(s, gre)) regmatches(s, gre) <- lapply(regmatches(regmatches(s, gre), gre2), function(a) paste(do.call(seq, as.list(as.integer(a))), collapse = ",")) s # [1] "I would like to buy 1,2,3 cats" "I would like to buy 1,2,3 cats" # [3] "foo 22,23,24,25,26,27,28,29,30,31,32,33" "quux 11,10,9,8,7,6,5,4,3 bar" ``` Upvotes: 2 <issue_comment>username_3: `gsubfn` in the gsubfn package is like `gsub` but instead of replacing the match with a replacement string it allows the user to specify a function (possibly in formula notation as done here). It then passes the matches to the capture groups in the regular expression, i.e. the matches to the parenthesized parts of the regular expression, as separate arguments and replaces the entire match with the output of the function. Thus we match `"(\\d+)(-| to | bis | jusqu'à )(\\d+)"` which results in three capture groups so 3 arguments to the function. In the function we use `seq` with the first and third of these. Note that `seq` can take character arguments and interpret them as numeric so we did not have to convert the arguments to numeric. Thus we get this one-liner: ``` library(gsubfn) s <- c(a, b) # test input strings gsubfn("(\\d+)(-| to | bis | jusqu'à )(\\d+)", ~ paste(seq(..1, ..3), collapse = ","), s) ``` giving: ``` [1] "I would like to buy 1,2,3 cats" "I would like to buy 1,2,3 cats" ``` Upvotes: 4 [selected_answer]
2018/03/18
1,036
3,081
<issue_start>username_0: ``` int main() { char *p[] = {"hello", "goodbye"}; char **a; a = malloc(4 * 8); } ``` I want a to have double the slots of p. How would I successfully do that without manually putting in numbers. All IK is the size of p should be there and x 2 for the double. How would I get the 8?<issue_comment>username_1: This is, in fact, a little tricky, unless someone has already written a package that does this (that I'm not aware of). ``` a <- "I would like to buy 1-3 cats" pos <- unlist(gregexpr("\\d+\\D+", a)) a_split <- unlist(strsplit(a, "")) replacement <- paste(seq.int(a_split[pos[1]], a_split[pos[2]]), collapse = ",") gsub("\\d+\\D+\\d+", replacement, a) # [1] "I would like to buy 1,2,3 cats" ``` EDIT: To show that the same solution works for arbitrary non digit characters between two numbers: ``` b <- "I would like to buy 1 jusqu'à 3 cats" pos_b <- unlist(gregexpr("\\d+\\D+", b)) b_split <- unlist(strsplit(b, "")) replacement <- paste(seq.int(b_split[pos_b[1]], b_split[pos_b[2]]), collapse = ",") gsub("\\d+\\D+\\d+", replacement, b) # [1] "I would like to buy 1,2,3 cats" ``` You can add arbitrary requirements for the run of nondigit characters if you'd like. If you need help with that, just share what the limits on the words or symbols that are between the numbers are! Upvotes: 2 <issue_comment>username_2: Not the most efficient, but ... ``` s <- c("I would like to buy 1-3 cats", "I would like to buy 1 jusqu'à 3 cats", "foo 22-33", "quux 11-3 bar") gre <- gregexpr("([0-9]+(-| to | bis | jusqu'à )[0-9]+)", s) gre2 <- gregexpr('[0-9]+', regmatches(s, gre)) regmatches(s, gre) <- lapply(regmatches(regmatches(s, gre), gre2), function(a) paste(do.call(seq, as.list(as.integer(a))), collapse = ",")) s # [1] "I would like to buy 1,2,3 cats" "I would like to buy 1,2,3 cats" # [3] "foo 22,23,24,25,26,27,28,29,30,31,32,33" "quux 11,10,9,8,7,6,5,4,3 bar" ``` Upvotes: 2 <issue_comment>username_3: `gsubfn` in the gsubfn package is like `gsub` but instead of replacing the match with a replacement string it allows the user to specify a function (possibly in formula notation as done here). It then passes the matches to the capture groups in the regular expression, i.e. the matches to the parenthesized parts of the regular expression, as separate arguments and replaces the entire match with the output of the function. Thus we match `"(\\d+)(-| to | bis | jusqu'à )(\\d+)"` which results in three capture groups so 3 arguments to the function. In the function we use `seq` with the first and third of these. Note that `seq` can take character arguments and interpret them as numeric so we did not have to convert the arguments to numeric. Thus we get this one-liner: ``` library(gsubfn) s <- c(a, b) # test input strings gsubfn("(\\d+)(-| to | bis | jusqu'à )(\\d+)", ~ paste(seq(..1, ..3), collapse = ","), s) ``` giving: ``` [1] "I would like to buy 1,2,3 cats" "I would like to buy 1,2,3 cats" ``` Upvotes: 4 [selected_answer]
2018/03/18
1,036
3,869
<issue_start>username_0: I want to ensure that a password a user enters is at least 7 characters long and has at least one uppercase letter, one lowercase letter, one number, and one symbol. The code seems to pass through the if loop until the symbol argument where it gets stuck. ``` puts "Please enter your desired password: " password = [] pass_clear = () while pass_clear == (nil) do password = gets.to_s.chomp if password.length < 7 puts "Your password must contain at least seven characters." elsif password.count("a-z") == password.length puts "Your password must contain at least one uppercase character." elsif password.count("A-Z") == password.length puts "Your password must contain at least one lowercase character." elsif password.count("!","@","#","$","%","^","&","*","(",")","_","-","+","=") < 1 puts "Your password must contain at least one symbol." elsif password.count("0","1","2","3","4","5","6","7","8","9") < 1 puts "Your password must contain at least one number." else puts "Thank you, your account is complete." pass_clear == 1 end end ``` This is the output: ``` Please enter your desired password: <PASSWORD> Your password must contain at least seven characters. Please enter your desired password: <PASSWORD> Your password must contain at least one uppercase character. Please enter your desired password: <PASSWORD> Your password must contain at least one symbol. Please enter your desired password: <PASSWORD>$ Your password must contain at least one symbol. Please enter your desired password: ``` And it continues looping through the symbol stage regardless of how many symbols there are. How can I ensure these symbols are recognized so the loop can finish?<issue_comment>username_1: You are quoting each of the symbols which is incorrect. You also have to escape the - and ^ characters ``` password.count("!@#$%\\^&*()_\\-+=") ``` works for me in this example. You'll also need to use a range for your numbers like: ``` password.count("0-9") ``` The - character is used for the ranges like "a-z" so it has to be escaped, the carat ^ is used to negate a count so: password.count("^a-z") would return a count of everything that wasn't in the range of a-z. This can come in handy as you may want to prevent certain characters from being in your password strings. You could do something like: ``` password.count("^a-zA-Z!@#$%\\^&*()_\\-+=0-9) ``` This would count any other characters outside what you've defined so you would want to get a zero return value to know they didn't use any forbidden characters. Some further clarification on ranges in `count()`. The term "range" should not be confused with the Ruby class "Range". The class of Range uses ".." or "..." for the intervening items. In the `count()` method the range being considered is the ASCII range from the first character's ASCII number to the second character's ASCII number. That's why in my original typo of `A-z` it was counting ASCII 65 ("A") to ASCII 122 ("z") which happens to include the characters ASCII 92 to 96 which are not letters but \ ] ^ \_ ` Upvotes: 3 [selected_answer]<issue_comment>username_2: One option is to use a regex that contains four positive lookaheads, all of which operate from the beginning of the string. ``` R = / (?=.*\p{Ll}) # match lowercase letter (?=.*\p{Lu}) # match uppercase letter (?=.*\d) # match digit (?=.*[#{Regexp.escape("!@#$%^&*(,)_+=-")}]) # match special char /x # free-spacing regex def mode def password_ok?(str) str.match?(R) end password_ok? "aA1#" #=> true password_ok? "A1#" #=> false password_ok? "a1#" #=> false password_ok? "aA#" #=> false password_ok? "aA1" #=> false ``` Upvotes: 0
2018/03/18
827
3,351
<issue_start>username_0: Write a public static method named q1 that takes no parameters and has return type boolean. This method will attempt to open a file named "location.txt" and returns true if the file exists and contains the String "statistical" as a sub-String on any line, and false if "statistical" is not found. This method will also return false if "location.txt" does not exist. This is what I did, Im not sure how to put this as a boolean. ``` public static boolean q1() { String filename = x; // creating file name location.txt try { String x = "location.txt"; System.out.print("location.txt file has been created"); String textToWrite = "statistical"; Files.write(Paths.get(x), textToWrite.getBytes()); } catch (IOException e) { boolean r = false; return r; } BufferedReader br = new BufferedReader(new FileReader("location.txt")); String textToWrite; while ((textToWrite = br.readLine()) != null) { } return f; } ```<issue_comment>username_1: The first part of your code seems to be creating a file that satisfies the criteria given (that is, it makes the following code, and the requirements pointless). Don't do that. Read the file line-by-line. Check if the line you read contains the string you are searching for. If it does `return true`. Otherwise `return false`. Like, ``` public static boolean q1() { String fileName = "location.txt", toFind = "statistical"; try (BufferedReader br = new BufferedReader(new FileReader(new File(fileName)))) { String line; while ((line = br.readLine()) != null) { if (line.contains(toFind)) { return true; } } } catch (IOException e) { e.printStackTrace(); } return false; } ``` Upvotes: 1 <issue_comment>username_2: Using the Stream API introduced in Java 8: ``` /** * Returns whether the file 'location.txt' exists and any line contains the string "statistical". * * @return true if the file exists and any line contains "statistical", false otherwise * @throws IOException if an I/O error occurs */ public static boolean q1() throws IOException { Path path = Paths.get("location.txt"); try (Stream lines = Files.lines(path)) { return lines.anyMatch(line -> line.contains("statistical")); } catch (FileNotFoundException e) { return false; } catch (UncheckedIOException e) { // Stream wraps IOExceptions, because streams don't throw checked exceptions. Unwrap them. throw e.getCause(); } } ``` Edit: Using try-with-resource to dispose file system resources. > > The returned stream encapsulates a Reader. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed. > > > Edit 2: Unwrapping the stream's UncheckedIOException to make it easier for the caller to handle exceptions. > > After this method returns, then any subsequent I/O exception that occurs while reading from the file or when a malformed or unmappable byte sequence is read, is wrapped in an UncheckedIOException that will be thrown from the Stream method that caused the read to take place. In case an IOException is thrown when closing the file, it is also wrapped as an UncheckedIOException. > > > Upvotes: 2
2018/03/18
799
3,342
<issue_start>username_0: I usually set all my auto layout code in the updateCOnstratins method of my view controller for the constraints of all the subclasses defining the view. Then in the subviews I place my constraints in the updateConstraints methods there. This makes me have a property of every single view in my class so I can reference it later on after I set translates.... to false. But Im reading that you don't have to set it in updateConstraints. Just not I read an article where the person says an apple engineer said that if the constraints are only made once then you can put them pretty much where ever. Yet, if you have constrains that change during the views lifecycle you place them in updateConstraints? Here are the links <http://swiftandpainless.com/where-to-put-the-auto-layout-code/> <http://swiftandpainless.com/dont-put-view-code-into-your-view-controller/>. So where should It go? Was this just an old way of doing this and now it has changed?<issue_comment>username_1: The first part of your code seems to be creating a file that satisfies the criteria given (that is, it makes the following code, and the requirements pointless). Don't do that. Read the file line-by-line. Check if the line you read contains the string you are searching for. If it does `return true`. Otherwise `return false`. Like, ``` public static boolean q1() { String fileName = "location.txt", toFind = "statistical"; try (BufferedReader br = new BufferedReader(new FileReader(new File(fileName)))) { String line; while ((line = br.readLine()) != null) { if (line.contains(toFind)) { return true; } } } catch (IOException e) { e.printStackTrace(); } return false; } ``` Upvotes: 1 <issue_comment>username_2: Using the Stream API introduced in Java 8: ``` /** * Returns whether the file 'location.txt' exists and any line contains the string "statistical". * * @return true if the file exists and any line contains "statistical", false otherwise * @throws IOException if an I/O error occurs */ public static boolean q1() throws IOException { Path path = Paths.get("location.txt"); try (Stream lines = Files.lines(path)) { return lines.anyMatch(line -> line.contains("statistical")); } catch (FileNotFoundException e) { return false; } catch (UncheckedIOException e) { // Stream wraps IOExceptions, because streams don't throw checked exceptions. Unwrap them. throw e.getCause(); } } ``` Edit: Using try-with-resource to dispose file system resources. > > The returned stream encapsulates a Reader. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed. > > > Edit 2: Unwrapping the stream's UncheckedIOException to make it easier for the caller to handle exceptions. > > After this method returns, then any subsequent I/O exception that occurs while reading from the file or when a malformed or unmappable byte sequence is read, is wrapped in an UncheckedIOException that will be thrown from the Stream method that caused the read to take place. In case an IOException is thrown when closing the file, it is also wrapped as an UncheckedIOException. > > > Upvotes: 2
2018/03/18
1,039
3,480
<issue_start>username_0: I am new to programming and trying to grasp the concepts. What I am trying to accomplish: 1. Loop through first table to get a string to search for 2. Then find the first instance of that string in a second table (if it exists) 3. Then insert/copy a row (from the first table) into the second table ABOVE the row where the instance was found (in the second table)...or if no instance exists: add a new row at the bottom of the second table and insert/copy the row there. I think I have the second part working correctly Where I am coming up short is figuring out the ListObject approach to do this correctly. I tried utilizing an 'activecell' approach but that isn't giving me the correct location within the table. I have searched extensively and found very little on inserting or even pasting into dynamic locations within a table using the ListObject approach. ``` Dim lastRow, eachRow1, unitRow, qtyRow As Long Dim ws1, ws2, ws3 As Worksheet Dim tbl1, tbl2, tbl3 As ListObject Dim chkFrst As Boolean Dim qtyValue, yumItem As String Dim qty, stockQty, calcQty As Integer Dim lastDate, reDate As Date Dim findRng As Range Dim NewRow, addRow As ListRow Set ws1 = Sheets("UPDATE") Set ws2 = Sheets("DATA") Set ws3 = Sheets("LOG") Set tbl1 = ws1.ListObjects("Update_Table") Set tbl2 = ws2.ListObjects("Data_Table") Set tbl3 = ws3.ListObjects("Log_Table") For unitRow = 1 To tbl1.ListRows.Count yumItem = tbl1.ListColumns("ITEM").DataBodyRange.Cells(unitRow, 1).Value Set findRng = tbl3.Range.Find(What:=yumItem) If findRng Is Nothing Then Set NewRow = tbl3.ListRows.Add(AlwaysInsert:=True) NewRow.Range.RowHeight = 25 NewRow.Range = tbl1.DataBodyRange.Cells.Range("A" & unitRow & ":O" & unitRow).Value Else Application.Goto findRng, True ActiveCell.EntireRow.Insert Shift = xlDown Dim crntRow As Long crntRow = ActiveCell.Row Set NewRow = tbl3.InsertRowRange.Cells.Range(crntRow) NewRow.Range = tbl1.DataBodyRange.Cells.Range("A" & unitRow & ":O" & unitRow).Value End If Next unitRow ``` Any and all help is greatly appreciated!<issue_comment>username_1: You can use `EntireRow.Insert` with your `FindRng` range. ``` Set findRng = tbl3.Range.Find(What:=yumItem) findRng.EntireRow.Insert Shift:=xlDown ``` ~~This will create a new row directly above your range.~~ This will shift down the found row, leaving an empty row in it's place.1 --- Only want to insert a new row for certain columns? Just replace `EntireRow` with `Columns()`. The below example will insert a row for the columns `A:C`: ``` findRng.Columns("A:C").Insert Shift:=xlDown ``` --- *1 Thanks for [clarifying](https://stackoverflow.com/questions/49344216/excel-2016-insert-row-above-find-result-in-table/49344320?noredirect=1#comment85688898_49344320) that point, Jeeped!* Upvotes: 1 <issue_comment>username_2: Thanks for the insight, I was thinking I had to use ListRows.Add to coincide with the ListObject format. So inserting the row isn't a problem but I have to format the cells a certain way and need to reference the new row so I tried ``` findRng.Columns("A:O").Insert Shift:=xlDown Set NewRow = findRng.Offset(-1, 0) NewRow.Range.RowHeight = 25 NewRow.Range = tbl1.DataBodyRange.Cells.Range("A" & unitRow & ":O" & unitRow).Value ``` But now I'm getting 'wrong number of arguments or invalid property assignment'. How do I Set the new row? Upvotes: 0
2018/03/18
768
1,756
<issue_start>username_0: I have a string: ``` key = "41521" ``` And I want to convert it into an array like this: ``` array = [41, 15, 52, 21] ``` I went about it like so: ``` array = [] array << key[0..1].to_i array << key[1..2].to_i array << key[2..3].to_i array << key[3..4].to_i ``` What would be a better way?<issue_comment>username_1: ``` (0..(key.length-2)).map{|i| key.slice(i, 2)} ``` Upvotes: 0 <issue_comment>username_2: ``` key = "41521" key.each_char.each_cons(2).map { |a| a.join.to_i } #=> [41, 15, 52, 21] ``` or ``` key.gsub(/\d(?=(\d))/).with_object([]) { |s,a| a << (s<<$1).to_i } #=> [41, 15, 52, 21] ``` or ``` a = [] e = key.each_char #=> # loop { a << (e.next << e.peek).to\_i } a #=> [41, 15, 52, 21] ``` In #3 [Enumerator#peek](http://ruby-doc.org/core-2.4.0/Enumerator.html#method-i-peek) raises a `StopInteration` exception when the internal position of the enumerator is at the end (unless `key` is an empty string, in which case [Enumerator#next](http://ruby-doc.org/core-2.4.0/Enumerator.html#method-i-next) raises the `StopInteration` exception). [Kernel#loop](http://ruby-doc.org/core-2.4.0/Kernel.html#method-i-loop) handles the exception by breaking out of the loop. Upvotes: 4 [selected_answer]<issue_comment>username_3: Not as short as some other answers, but for me, more easier to see the steps: ``` arr = key.chars.each_with_index .reduce([]) {|s,(v,i)| s << (v + (key[i+1] || '')).to_i } .select {|s| s.to_s.length > 1 } # arr: [41, 15, 52, 21] ``` Upvotes: 1 <issue_comment>username_4: ``` key.gsub(/(?<=.)\d(?=.)/, '\&\&').scan(/\d{2}/).map(&:to_i) # => [41, 15, 52, 21] ``` or ``` (0...key.length).map{|i| key[i, 2].to_i} # => [41, 15, 52, 21, 1] ``` Upvotes: 2
2018/03/18
1,021
2,306
<issue_start>username_0: I am trying to write a python 3 code for following function: I have a list named Config, ``` Config = [[32, 31, 33, 34], [32, 42, 13, 33], [32, 42, 34, 44], [42, 42, 43, 44]] ``` This list has 4 sublists. Now I want to get a new list from Config as follows (without first and fourth sublist), ``` ConfigRevised = [[32, 42, 13, 33], [32, 42, 34, 44]] ``` Because from each of the sublist it can be observed that: 1. [32, 31, 33, 34]: 1st character of each item in list are same [3, 3, 3, 3] . 2. [32, 42, 13, 33]: 1st character of each item in list are not same [3, 2, 1, 3] . 3. [32, 42, 34, 44]: 1st character of each item in list are not same [3, 4, 3, 4] . 4. [42, 42, 43, 44]: 1st character of each item in list are same [4, 4, 4, 4]. Now, I want to delete sublist 1 and sublist 4, because first character of sublist items are same.<issue_comment>username_1: ``` (0..(key.length-2)).map{|i| key.slice(i, 2)} ``` Upvotes: 0 <issue_comment>username_2: ``` key = "41521" key.each_char.each_cons(2).map { |a| a.join.to_i } #=> [41, 15, 52, 21] ``` or ``` key.gsub(/\d(?=(\d))/).with_object([]) { |s,a| a << (s<<$1).to_i } #=> [41, 15, 52, 21] ``` or ``` a = [] e = key.each_char #=> # loop { a << (e.next << e.peek).to\_i } a #=> [41, 15, 52, 21] ``` In #3 [Enumerator#peek](http://ruby-doc.org/core-2.4.0/Enumerator.html#method-i-peek) raises a `StopInteration` exception when the internal position of the enumerator is at the end (unless `key` is an empty string, in which case [Enumerator#next](http://ruby-doc.org/core-2.4.0/Enumerator.html#method-i-next) raises the `StopInteration` exception). [Kernel#loop](http://ruby-doc.org/core-2.4.0/Kernel.html#method-i-loop) handles the exception by breaking out of the loop. Upvotes: 4 [selected_answer]<issue_comment>username_3: Not as short as some other answers, but for me, more easier to see the steps: ``` arr = key.chars.each_with_index .reduce([]) {|s,(v,i)| s << (v + (key[i+1] || '')).to_i } .select {|s| s.to_s.length > 1 } # arr: [41, 15, 52, 21] ``` Upvotes: 1 <issue_comment>username_4: ``` key.gsub(/(?<=.)\d(?=.)/, '\&\&').scan(/\d{2}/).map(&:to_i) # => [41, 15, 52, 21] ``` or ``` (0...key.length).map{|i| key[i, 2].to_i} # => [41, 15, 52, 21, 1] ``` Upvotes: 2
2018/03/18
753
2,855
<issue_start>username_0: I am new to RxJS and I am trying to subscribe to an observable function in two different and I am wondering if there is a way to trigger a call from one of the functions can also change the outcome in the second file. I have an action creator and authGuard subscribe to my loginService and I am trying the action creator will trigger once I call the login function from the auth guard. action.js ``` this.loginService.handleLogin(userId) .subscribe((data) => { console.log("response in action.js", response); }, (e) => { console.log(e); }); ``` authGuard.js ``` this.loginService.handleLogin(userId) .subscribe((response) => { console.log("response in authGuard.js", response); }, (err) => { console.log("error", err); }) ``` loginService.js ``` handleLogin(userId) { const url = `api/user/${userId}`; return this.http.get(url, { headers: this.headers }) .map((response: Response) => { return response.json(); }) .catch((e) => { return Observable.throw(e); }); } ``` expectation: I am expecting to get console.logs results in action.js and authGuard.js when I call handlLogin function of loginService from either file.<issue_comment>username_1: Each time you call handleLogin, a separate observable is being created and returned. So your two files are not subscribed to the same object. Take a look at the answers here for how to structure your handleLogin implementation to fix this: [What is the correct way to share the result of an Angular Http network call in RxJs 5?](https://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-result-of-an-angular-http-network-call-in-r). Note in particular this answer about `shareReplay()` which is probably the better up to date answer though it's not the highest scored: <https://stackoverflow.com/a/43943217/518955> Upvotes: 1 <issue_comment>username_2: The HTTP observable makes an HTTP request for each subscriber. To share a single HTTP request for multiple observers, you need something like the [share](https://www.learnrxjs.io/operators/multicasting/share.html) operator. ``` export class FetchService { data$: Observable; constructor(){ this.data$ = this.\_http.request(this.\_url) .map((res:Response)=>res.json()) .catch(this.errorHandler) .share(); } getData(){ return this.data$; } } ``` Now the multiple observers will share the same observable. > > This operator is a specialization of publish which creates a > subscription when the number of observers goes from zero to one, then > shares that subscription with all subsequent observers until the > number of observers returns to zero, at which point the subscription > is disposed. > > > Upvotes: 0
2018/03/18
646
2,330
<issue_start>username_0: ``` from sys import argv def prime(): for i in range(2,num): if num % i == 0: print(f"{num} can be divisible by {i}.") checker = False num = int(input("Enter the number you want to check is prime: ")) checker = True if num < 2: print(f"{num} is a prime number.") elif num == 0: print(f"{num} is not a prime number.") elif num > 0: prime() print(f"Is this number a prime - {checker}.") else: print(f"Please write number larger than 0.") ``` Hello guys, I've just started to code and this is probably a really simple question. I want my code to either find the factors of a number or print if a number is a prime - but my boolean value in the "prime" function never updates to False. Not sure why! Thank you.<issue_comment>username_1: Each time you call handleLogin, a separate observable is being created and returned. So your two files are not subscribed to the same object. Take a look at the answers here for how to structure your handleLogin implementation to fix this: [What is the correct way to share the result of an Angular Http network call in RxJs 5?](https://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-result-of-an-angular-http-network-call-in-r). Note in particular this answer about `shareReplay()` which is probably the better up to date answer though it's not the highest scored: <https://stackoverflow.com/a/43943217/518955> Upvotes: 1 <issue_comment>username_2: The HTTP observable makes an HTTP request for each subscriber. To share a single HTTP request for multiple observers, you need something like the [share](https://www.learnrxjs.io/operators/multicasting/share.html) operator. ``` export class FetchService { data$: Observable; constructor(){ this.data$ = this.\_http.request(this.\_url) .map((res:Response)=>res.json()) .catch(this.errorHandler) .share(); } getData(){ return this.data$; } } ``` Now the multiple observers will share the same observable. > > This operator is a specialization of publish which creates a > subscription when the number of observers goes from zero to one, then > shares that subscription with all subsequent observers until the > number of observers returns to zero, at which point the subscription > is disposed. > > > Upvotes: 0
2018/03/18
578
2,130
<issue_start>username_0: I am trying to insert a data object via web API to the database. when I using the Postmen, POST request is the success. but in angular 5 app post request indicates 500 Internal saver error. here is my source code. player.service.ts ``` @Injectable() export class PlayerService { private _postPlayer = 'http://192.168.8.101/api/Values/insertData'; constructor(private _http: HttpClient) { } httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', }) }; // save the new player save(palyer: Player): Observable { console.log(palyer.playingRole); return this.\_http.post(this.\_postPlayer, palyer, this.httpOptions) } } ``` here are my Components ``` export class AddplayerComponent implements OnInit { player: Player = new Player(); playerAdd: FormGroup; players: Player[]; constructor(private plService: PlayerService) { } ngOnInit() { this.playerAdd = new FormGroup( { firstName: new FormControl(), lastName: new FormControl(), nickName: new FormControl(), birthday: new FormControl(), playingRole: new FormControl(), battingStyle: new FormControl(), bowllingStyle: new FormControl(), mobileNumber: new FormControl(), email: new FormControl() } ); } save() { console.log(this.playerAdd.value); this.player = this.playerAdd.value; this.plService.save(this.player) .subscribe(); } } ``` Here are my ASP.NET WebApi Post ``` [HttpPost] public void insertData([FormBody] Player Ob){ // to connect EF6 context } ``` Get request is working fine. but Post request is not working.<issue_comment>username_1: You need to `stringify` your object: ``` return this._http.post(this.\_postPlayer, JSON.stringify(palyer), this.httpOptions) ``` And added the `microsoft.aspnet.webapi.cors` package to the API. Upvotes: 2 [selected_answer]<issue_comment>username_2: The error was I got here is not adding to the microsoft.aspnet.webapi.cors package to the API. just added it and its working fine. Thanks all for the support me. Upvotes: 0
2018/03/18
2,105
8,084
<issue_start>username_0: I am trying to validate multiple groups of radio buttons with pureJS. Basically my client has a group of around 50 questions, and each one has 4 radio buttons that can be used to pick 1 of 4 answers. They do not want to use jQuery, but pureJS, I have gotten the following to work when there is just one question, but not when there is multiples, any help would be appreciated. ``` document.getElementById("submit_btn").addEventListener("click", function(event){ var all_answered = true; var inputRadios = document.querySelectorAll("input[type=radio]") for(var i = 0; i < inputRadios.length; i++) { var name = inputRadios[i].getAttribute("name"); if (document.getElementsByName(name)[i].checked) { return true; var all_answered = true; } else { var all_answered = false; } } if (!all_answered) { alert("Some questiones were not answered. Please check all questions and select an option."); event.preventDefault(); } }); ``` The questions are all laid out like this - ``` 33 Troubleshoot technology issues. Very Interested Interested Slightly Interested Not Interested ``` This is the original jQuery used by the client which now has to be in pureJS ``` jQuery(document).ready(function () { jQuery("#question_list").submit(function () { var all_answered = true; jQuery("input:radio").each(function () { var name = jQuery(this).attr("name"); if (jQuery("input:radio[name=" + name + "]:checked").length == 0) { all_answered = false; } }); if (!all_answered) { alert("Some questiones were not answered. Please check all questions and select an option."); return false; } }); }); ```<issue_comment>username_1: Everything inside your `for` clause makes absolutely no sense. Here's why: * Since you already have `inputRadios`, there is no point and getting their name and then using that to get the elements by name, because you already have them. * Since you use `return true`, the function exits and everything beyond that is disregarded. * Instead of updating the existent `all_answered` variable you create a new, local one that will be lost once the current iteration ends. **What you should do:** 1. Instead of getting all inputs, get all answers, the `div.options` elements that contain the inputs for each answer, and iterate over those. 2. Then, use the `id` of the answer, because it's the same as the name of the inputs, to get the related inputs. 3. Use [`some`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) to ensure that there is a checked input among the group. Then, check whether there isn't and stop the loop. You've found an unanswered question. **Snippet:** ```js document.getElementById("submit_btn").addEventListener("click", function(event) { var /* Create a flag set by default to true. */ all_answered = true, /* Get all answers. */ answers = document.querySelectorAll(".options[id ^= ans_]"); /* Iterate over every answer. */ for (var i = 0; i < answers.length; i++) { var /* Use the id of the answer to get its radiobuttons. */ radios = document.querySelectorAll("[name = " + answers[i].id + "]"), /* Save whether there is a checked input for the answer. */ hasChecked = [].some.call(radios, function(radio) { return radio.checked; }); /* Check whether there is a checked input for the answer or not. */ if (!hasChecked) { /* Set the all_answered flag to false and break the loop. */ all_answered = false; break; } } /* Check whether not all answers have been answered. */ if (!all_answered) { console.log("Some questions were not answered..."); } else { console.log("All questions are answered!"); } }); ``` ```css .question { display: inline-block } ``` ```html Troubleshoot technology issues. Very Interested Interested Slightly Interested Not Interested Troubleshoot technology issues. Very Interested Interested Slightly Interested Not Interested Troubleshoot technology issues. Very Interested Interested Slightly Interested Not Interested Submit ``` Upvotes: 1 <issue_comment>username_2: Not sure if it's just an issue with the copy, but you have a `return true` in your `for` loop which will cause the entire function to simply return true if just one is answered. Removing that would help. Ignoring that though, your solution is a bit unwieldy, as it'll loop through every single input on the page individually and will mark it false if not every radio button is unchecked. Here is a different approach. Basically, get all of the radio buttons, then group them into arrays by question. Then, loop through each of those arrays and check that within each group, at least one is answered. ```js document.querySelector('form').addEventListener('submit', e => { // Get all radio buttons, convert to an array. const radios = Array.prototype.slice.call(document.querySelectorAll('input[type=radio]')); // Reduce to get an array of radio button sets const questions = Object.values(radios.reduce((result, el) => Object.assign(result, { [el.name]: (result[el.name] || []).concat(el) }), {})); // Loop through each question, looking for any that aren't answered. const hasUnanswered = questions.some(question => !question.some(el => el.checked)); if (hasUnanswered) { console.log('Some unanswered'); } else { console.log('All set'); } e.preventDefault(); // just for demo purposes... normally, just put this in the hasUnanswered part }); ``` ```html A B C D A B C D Submit ``` First up, I get all of the radio buttons that have a type of radio (that way if there are others, I won't bother with them). Then, I turn the `NodeList` returned by `querySelectorAll()` into an `Array` by using `Array.prototype.slice.call()` and giving it my `NodeList`. After that, I use `reduce()` to group the questions together. I make it an array with the element's name as the key (since I know that's how they have to be grouped). After the reduce, since I don't really care about it being an object with the key, I use `Object.values()` just to get the arrays. After that, I use `some()` over the set of questions. If that returns true, it'll mean I have at least one unanswered question. Finally, inside that `some()`, I do another over the individual radio buttons of the question. For this, I want to return `!some()` because if there isn't at least one that is answered, then I should return true overall (that I have at least one question not answered). The above is a bit verbose. This one is a bit more concise and is what I would likely use in my own code: ```js document.querySelector('form').addEventListener('submit', e => { if (Object.values( Array.prototype.reduce.call( document.querySelectorAll('input[type=radio]'), (result, el) => Object.assign(result, { [el.name]: (result[el.name] || []).concat(el) }), {} ) ).some(q => !q.some(el => el.checked))) { e.preventDefault(); console.log('Some questions not answered'); } }); ``` ```html A B C D A B C D Submit ``` Upvotes: 2 <issue_comment>username_3: The following is a simplified version, but there should be enough code to get you heading in the right direction. ```js var answer = []; function checkAnswerCount(e) { // for the answer ids var i = 0, max = answer.length; // for the radios var j = 0; rMax = 0; // And a few extras var tmp = null, answerCount = 0; for(;i ``` ```html Question 1. Answer 1, op1 Answer 1, op2 Question 2. Answer 2, op1 Answer 2, op2 Question 3. Answer 3, op1 Answer 3, op2 Submit / check ``` Upvotes: 0
2018/03/18
620
2,183
<issue_start>username_0: I am in the process of moving my NodeJS backend over to Python3.6. In NodeJS I was able to use the aws SDK to get items between two dates like so : ``` ``` var now = moment().tz("Pacific/Auckland").format() var yesterday = moment().add(-24,"Hours").tz("Pacific/Auckland").format() var docClient = new AWS.DynamoDB.DocumentClient(); var params = { TableName : process.env.TableName, FilterExpression : '#ts between :val1 and :val2', ExpressionAttributeNames: { "#ts": "timeStamp", }, ExpressionAttributeValues: { ':val1': yesterday, ':val2': now } } ``` ``` And this works fine, however the between function in boto3 does not seem to do the same thing. This is the current code I am using to try get something similar: ``` ``` import boto3 import time from datetime import datetime, timedelta from boto3.dynamodb.conditions import Key, Attr dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('table_name') now = int(datetime.timestamp(datetime.now())) three_hours_ago = int(datetime.timestamp(datetime.now() - timedelta(hours=3))) fe = Key('timeStamp').between(three_hours_ago,now); response = table.scan( FilterExpression=fe ) print(response) ``` ``` This returns no items, I am sure that there are items between these two dates. Any help would be much appreciated.<issue_comment>username_1: I managed to resolve this using the following code: ``` now = datetime.datetime.now() three_hours_ago = now - datetime.timedelta(hours=3) # TODO make the db UTC now = now.strftime('%FT%T+13:00') three_hours_ago = three_hours_ago.strftime('%FT%T+13:00') fe = Key('timeStamp').between(three_hours_ago,now); response = table.scan( FilterExpression=fe ) ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: A possible solution could be: ``` attr = boto3.dynamodb.conditions.Attr('timeStamp') response = table.scan( FilterExpression=attr.between(first_date,second_date) ) ``` However, please note that the date should be formatted as YYYY-MM-DD (ISO 8601) Upvotes: 2
2018/03/18
484
1,692
<issue_start>username_0: I need a simple python program that looks for a string in a list and if it doesn't find it generates the next one in **alphabetical DESCENDING ORDER** .By that, I meant if it does not find **'abz'** it will generate **ac** deleting the last char when it reaches *'z'*. Another example: I have a list like: list = ['allena', 'allend','alphosis','alpinist', 'alternative'] **Assuming I don't know what is in the list.** After the function find **allend** in the list it will check for **allene** to **allenz**, and after **alleo** to **allez** and after **alle** to **allz** ... Thereby by removing the last char in the string everytime it is **'z'**.... the function will reach **alp** and **alt**... until it reaches **a** The function will change the last character of a string and remove it when it becomes **'z'** until it remains the first char only. Thank you guys!<issue_comment>username_1: I managed to resolve this using the following code: ``` now = datetime.datetime.now() three_hours_ago = now - datetime.timedelta(hours=3) # TODO make the db UTC now = now.strftime('%FT%T+13:00') three_hours_ago = three_hours_ago.strftime('%FT%T+13:00') fe = Key('timeStamp').between(three_hours_ago,now); response = table.scan( FilterExpression=fe ) ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: A possible solution could be: ``` attr = boto3.dynamodb.conditions.Attr('timeStamp') response = table.scan( FilterExpression=attr.between(first_date,second_date) ) ``` However, please note that the date should be formatted as YYYY-MM-DD (ISO 8601) Upvotes: 2
2018/03/18
815
2,292
<issue_start>username_0: I am just learning about mutexess. I thought the following program would return a total of 1000, but I am getting varied results, so I assume I am doing something wrong... ``` package main import ( "fmt" "sync" ) var total int var locker sync.RWMutex func add() { for x := 1; x <= 100; x++ { locker.Lock() total += 1 locker.Unlock() } } func main() { for x := 1; x <= 10; x++ { go add() } fmt.Printf("Total is %v\n", total) } ```<issue_comment>username_1: You're not waiting for any of the goroutines you started to *finish* before checking the result. Use a `WaitGroup` to wait for all of them to complete. Upvotes: 2 <issue_comment>username_2: You have a data race. Therefore, the results are undefined. ``` package main import ( "fmt" "sync" ) var total int var locker sync.RWMutex func add() { for x := 1; x <= 100; x++ { locker.Lock() total += 1 locker.Unlock() } } func main() { for x := 1; x <= 10; x++ { go add() } fmt.Printf("Total is %v\n", total) } ``` Output: ``` $ go run -race racer.go ================== WARNING: DATA RACE Read at 0x0000005ba408 by main goroutine: runtime.convT2E64() /home/peter/go/src/runtime/iface.go:335 +0x0 main.main() /home/peter/src/racer.go:23 +0x84 Previous write at 0x0000005ba408 by goroutine 14: main.add() /home/peter/src/racer.go:14 +0x76 Goroutine 14 (running) created at: main.main() /home/peter/src/racer.go:21 +0x52 ================== Total is 960 Found 1 data race(s) exit status 66 $ ``` Upvotes: 1 <issue_comment>username_3: Main function returns before gorutines finished their works, you should add `sync.WaitGroup`, this code works as you expected: <https://play.golang.com/p/_OfrZae0soB> ``` package main import ( "fmt" "sync" ) var total int var locker sync.RWMutex func add(wg *sync.WaitGroup) { defer wg.Done() for x := 1; x <= 100; x++ { locker.Lock() total += 1 locker.Unlock() } } func main() { var wg sync.WaitGroup for x := 1; x <= 10; x++ { wg.Add(1) go add(&wg) } wg.Wait() fmt.Printf("Total is %v\n", total) } ``` Upvotes: 3 [selected_answer]
2018/03/18
3,738
6,920
<issue_start>username_0: I am trying to determine the number of times that x or y individuals (represented by a unique number each) are dominant to each other. I have used count to summarize the data: ``` Dominance1<-count(Dominance, c('Dominant', 'Subordinate')) ``` And the data look like this: ``` > Dominant Subordinate freq 5 9 14 5 10 9 5 11 4 5 15 7 5 18 14 5 22 6 5 24 9 5 26 5 5 40 8 5 43 5 9 10 4 9 11 6 9 15 1 9 18 7 9 22 14 9 24 6 9 25 7 10 15 1 10 18 1 10 22 2 10 40 1 10 43 1 10 75 4 ``` ... and so on (All of the unique IDs are: 5,9, 10, 11, 80, 15, 75,18,85,22,82,24,25,26,86,68,79,83,81,77,91,40,87,43,78... total dataset is 321 rows of the different relationships observed between these IDs and the frequency of observations). But I need to also look at how many times '9' was dominant when '5' was subordinate, side by side. Is it possible to order so that the data looks like this? ``` > Dominant Subordinate freq 5 9 14 9 5 0 5 11 4 11 5 7 ``` Currently it's just in order based on the 'Dominant' column. Is there a way to alternate like I showed above so that I can see how often x is dominant to y and compare to how often y is dominant to x lined up like that? Here is the full dataset: ``` Dom Sub freq 5 9 14 5 10 9 5 11 4 5 15 7 5 18 14 5 22 6 5 24 9 5 26 5 5 40 8 5 43 5 5 75 15 5 77 10 5 78 10 5 80 3 5 81 2 5 82 12 5 83 11 5 85 8 5 87 11 5 91 16 9 10 4 9 11 6 9 15 1 9 18 7 9 22 14 9 24 6 9 25 7 9 26 6 9 40 12 9 43 8 9 75 10 9 77 1 9 79 1 9 80 4 9 82 20 9 85 9 9 87 7 9 91 4 10 15 1 10 18 1 10 22 2 10 40 1 10 43 1 10 75 4 10 78 1 10 79 4 10 80 3 10 81 1 10 87 1 11 10 2 11 26 1 11 40 1 11 43 3 11 77 1 11 80 5 11 85 1 15 18 2 15 22 1 15 43 1 15 77 1 15 78 1 15 79 2 15 81 1 15 83 2 15 85 2 15 87 2 15 91 2 18 22 2 18 24 1 18 78 2 18 79 1 18 80 4 22 24 2 22 40 1 24 10 1 24 18 1 24 22 7 24 26 11 24 75 1 24 78 3 24 79 8 24 81 11 24 83 5 24 86 8 24 91 13 25 5 3 25 9 1 25 10 3 25 11 3 25 15 2 25 18 1 25 22 6 25 24 5 25 26 3 25 40 5 25 43 8 25 75 3 25 77 7 25 78 5 25 79 5 25 80 3 25 81 2 25 82 6 25 83 5 25 85 2 25 87 6 25 91 3 26 10 3 26 11 8 26 18 5 26 22 1 26 40 9 26 43 5 26 77 1 26 78 7 26 80 5 26 83 1 26 85 3 26 91 1 40 10 1 40 15 1 40 22 4 40 25 1 40 75 1 40 80 1 40 81 1 40 83 1 40 85 1 40 87 2 40 91 1 43 18 2 43 22 2 43 24 7 43 40 4 43 75 3 43 77 2 43 79 2 43 80 3 43 82 1 68 5 15 68 9 41 68 10 3 68 11 5 68 15 6 68 18 9 68 22 12 68 24 8 68 25 14 68 26 1 68 40 8 68 43 10 68 75 6 68 77 9 68 78 3 68 79 6 68 80 3 68 81 3 68 82 5 68 83 5 68 85 12 68 86 9 68 87 9 68 91 4 75 10 1 75 15 1 75 18 2 75 22 4 75 24 2 75 26 2 75 40 3 75 77 1 75 78 6 75 79 6 75 80 6 75 81 1 75 82 2 75 87 7 77 5 1 77 15 1 77 18 7 77 22 2 77 24 1 77 40 4 77 78 8 77 79 2 77 80 4 77 81 7 77 82 1 77 85 5 77 87 3 78 10 3 78 11 1 78 15 1 78 18 1 78 40 2 78 43 1 78 83 2 78 86 2 79 5 4 79 9 20 79 15 1 79 18 1 79 26 4 79 68 1 79 75 1 79 77 1 79 78 2 79 80 1 79 81 4 79 82 10 79 83 9 79 85 4 79 91 15 80 22 2 80 43 1 80 78 2 81 5 14 81 9 20 81 10 2 81 18 8 81 22 11 81 25 3 81 26 4 81 43 1 81 68 1 81 75 4 81 77 1 81 78 4 81 79 3 81 80 11 81 82 13 81 83 13 81 85 1 81 86 3 81 87 1 81 91 16 82 10 4 82 15 4 82 18 1 82 22 1 82 24 3 82 26 2 82 40 7 82 43 3 82 77 5 82 78 2 82 80 4 82 83 3 82 85 2 82 87 4 83 9 2 83 10 4 83 11 3 83 15 7 83 18 2 83 22 2 83 25 2 83 26 5 83 43 3 83 68 1 83 75 3 83 77 7 83 78 5 83 80 2 83 81 1 83 82 2 83 85 1 83 87 9 83 91 4 85 10 2 85 11 2 85 15 1 85 18 1 85 22 2 85 26 1 85 40 2 85 43 6 85 75 4 85 78 1 85 79 2 85 80 2 86 5 9 86 9 6 86 10 5 86 11 6 86 15 5 86 18 5 86 22 9 86 25 22 86 26 6 86 40 3 86 43 12 86 68 1 86 75 16 86 77 4 86 78 4 86 79 9 86 80 8 86 82 16 86 83 6 86 85 6 86 87 5 86 91 12 87 10 1 87 77 1 87 80 4 87 85 1 91 10 4 91 11 3 91 18 5 91 22 1 91 24 1 91 26 2 91 40 1 91 43 1 91 75 3 91 77 4 91 80 2 91 82 9 91 85 8 91 87 8 ```<issue_comment>username_1: You're not waiting for any of the goroutines you started to *finish* before checking the result. Use a `WaitGroup` to wait for all of them to complete. Upvotes: 2 <issue_comment>username_2: You have a data race. Therefore, the results are undefined. ``` package main import ( "fmt" "sync" ) var total int var locker sync.RWMutex func add() { for x := 1; x <= 100; x++ { locker.Lock() total += 1 locker.Unlock() } } func main() { for x := 1; x <= 10; x++ { go add() } fmt.Printf("Total is %v\n", total) } ``` Output: ``` $ go run -race racer.go ================== WARNING: DATA RACE Read at 0x0000005ba408 by main goroutine: runtime.convT2E64() /home/peter/go/src/runtime/iface.go:335 +0x0 main.main() /home/peter/src/racer.go:23 +0x84 Previous write at 0x0000005ba408 by goroutine 14: main.add() /home/peter/src/racer.go:14 +0x76 Goroutine 14 (running) created at: main.main() /home/peter/src/racer.go:21 +0x52 ================== Total is 960 Found 1 data race(s) exit status 66 $ ``` Upvotes: 1 <issue_comment>username_3: Main function returns before gorutines finished their works, you should add `sync.WaitGroup`, this code works as you expected: <https://play.golang.com/p/_OfrZae0soB> ``` package main import ( "fmt" "sync" ) var total int var locker sync.RWMutex func add(wg *sync.WaitGroup) { defer wg.Done() for x := 1; x <= 100; x++ { locker.Lock() total += 1 locker.Unlock() } } func main() { var wg sync.WaitGroup for x := 1; x <= 10; x++ { wg.Add(1) go add(&wg) } wg.Wait() fmt.Printf("Total is %v\n", total) } ``` Upvotes: 3 [selected_answer]
2018/03/18
548
1,959
<issue_start>username_0: I'd like to use a selector to grey out an icon when it is not enabled. It seems that something like this should work (with a white background): ``` android:alpha="0.5" android:alpha="1" ``` But it results in a java.lang.NumberFormatException during run time. I also tried "0.5f". Same error. This is similar to [Is there a way to set drawable's Alpha using XML?](https://stackoverflow.com/questions/8179250/is-there-a-way-to-set-drawables-alpha-using-xml) but I'm specifically asking about the NumberFormatException. Incidentally, I also tried using integer values between 0 and 255. I get the same error.<issue_comment>username_1: You can't do android:alpha that way inside an item. You could put something like a shape inside an item, or you can use drawable within item to achieve the same effect. What do you mean by "grey out" though? What you have shown isn't really greying out so much as making something partially opaque. If the item was originally red and you change alpha to 0.5, it's still going to be a shade of red. But assuming we are starting at a color grey, in this case F5F5F5 (Material Grey 100), then you could do it this way: ``` xml version="1.0" encoding="utf-8"? ``` Notice the "80" in the false state giving a different opacity. Here is an example of doing something similar but with rectangular shapes inside the items: ``` xml version="1.0" encoding="utf-8"? ``` Upvotes: 0 <issue_comment>username_2: Considering this is your color selector, which is located under res/color/my\_selector.xml **Note**: This works in device Android 23 and above You can use alpha inside this color selector as ``` ``` To use this - ``` ``` Refer following link for more reference: <https://developer.android.com/reference/android/content/res/ColorStateList.html> Upvotes: 2 <issue_comment>username_3: The alpha parameter must be in the item tag ``` xml version="1.0" encoding="utf-8"? ``` Upvotes: 0
2018/03/18
1,131
3,794
<issue_start>username_0: It gives me an error of "Trying to get property of non-object" can you help me? It works normally on my offline server but if I upload it on my liveserver it gives an error I if I dd my controller gives result. ``` Collection {#287 ▼ #items: array:3 [▼ 0 => Branch {#297 ▼ #connection: "mysql" #table: null #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] #perPage: 15 +exists: true +wasRecentlyCreated: false #attributes: array:6 [▶] #original: array:6 [▶] #casts: [] #dates: [] #dateFormat: null #appends: [] #events: [] #observables: [] #relations: array:1 [▼ "cashier" => User {#301 ▼ #fillable: array:4 [▶] #hidden: array:2 [▶] #connection: "mysql" #table: null #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] #perPage: 15 +exists: true +wasRecentlyCreated: false #attributes: array:8 [▼ "id" => 5 "name" => "qqqa<NAME>" "email" => "<EMAIL>" "password" => <PASSWORD>" "usertype" => "cashier" "remember_token" => null "created_at" => "2018-01-22 03:30:20" "updated_at" => "2018-01-22 05:56:19" ] #original: array:8 [▶] #casts: [] #dates: [] #dateFormat: null #appends: [] #events: [] #observables: [] #relations: [] #touches: [] +timestamps: true #visible: [] #guarded: array:1 [▶] #rememberTokenName: "<PASSWORD>" } ] #touches: [] +timestamps: true #hidden: [] #visible: [] #fillable: [] #guarded: array:1 [▶] } 1 => Branch {#298 ▶} 2 => Branch {#299 ▶} ] } ``` But when I make my code to disyplay the name of the cashier. with this code ``` @foreach($dataBranch as $Branch) | {{$Branch->branch\_name}} | {{$Branch->cashier->name}} | @endforeach ``` It gives me an error of "Trying to get property of non-object" can you help me? It works normally on my offline server but if I upload it on my liveserver it gives an error Please help<issue_comment>username_1: You can't do android:alpha that way inside an item. You could put something like a shape inside an item, or you can use drawable within item to achieve the same effect. What do you mean by "grey out" though? What you have shown isn't really greying out so much as making something partially opaque. If the item was originally red and you change alpha to 0.5, it's still going to be a shade of red. But assuming we are starting at a color grey, in this case F5F5F5 (Material Grey 100), then you could do it this way: ``` xml version="1.0" encoding="utf-8"? ``` Notice the "80" in the false state giving a different opacity. Here is an example of doing something similar but with rectangular shapes inside the items: ``` xml version="1.0" encoding="utf-8"? ``` Upvotes: 0 <issue_comment>username_2: Considering this is your color selector, which is located under res/color/my\_selector.xml **Note**: This works in device Android 23 and above You can use alpha inside this color selector as ``` ``` To use this - ``` ``` Refer following link for more reference: <https://developer.android.com/reference/android/content/res/ColorStateList.html> Upvotes: 2 <issue_comment>username_3: The alpha parameter must be in the item tag ``` xml version="1.0" encoding="utf-8"? ``` Upvotes: 0
2018/03/18
603
2,051
<issue_start>username_0: How do I read a line of text printed on a pad in ncurses? I am trying to use the `ncurses` function `winchnstr`. I am confused about how to use `chtype*` in the function. I understand that `chtype` is a `long int`, but when I use `chtype` in my code I get a segment fault. In the below example the `long int y` prints 20. I need to be able to read a line of text on the pad. Can someone show me how to do it? ``` long int p[20]; wmove(pad,prow,ccol); long int y = winchnstr(pad, p,20)&A_CHARTEXT; ``` > > Edit: > > > Whenever I print the return from the function, I get the number of characters returned. I am confused. How can I turn this into a printable string? ``` fprintf(file,"%d",y); ```<issue_comment>username_1: You can't do android:alpha that way inside an item. You could put something like a shape inside an item, or you can use drawable within item to achieve the same effect. What do you mean by "grey out" though? What you have shown isn't really greying out so much as making something partially opaque. If the item was originally red and you change alpha to 0.5, it's still going to be a shade of red. But assuming we are starting at a color grey, in this case F5F5F5 (Material Grey 100), then you could do it this way: ``` xml version="1.0" encoding="utf-8"? ``` Notice the "80" in the false state giving a different opacity. Here is an example of doing something similar but with rectangular shapes inside the items: ``` xml version="1.0" encoding="utf-8"? ``` Upvotes: 0 <issue_comment>username_2: Considering this is your color selector, which is located under res/color/my\_selector.xml **Note**: This works in device Android 23 and above You can use alpha inside this color selector as ``` ``` To use this - ``` ``` Refer following link for more reference: <https://developer.android.com/reference/android/content/res/ColorStateList.html> Upvotes: 2 <issue_comment>username_3: The alpha parameter must be in the item tag ``` xml version="1.0" encoding="utf-8"? ``` Upvotes: 0
2018/03/18
1,563
5,947
<issue_start>username_0: What's the equivalent of `document.querySelectorAll('.classname')` in React? I understand I should use Refs, but how dow I observe multiple Refs `onScroll`? I usually use a function like the one below to check the viewport position of multiple elements in the page, and trigger different css animation when each element enters the viewport: HTML ``` * * * * ``` Javascript ``` getPosition: function (element) { const rect = element.getBoundingClientRect(); if ((rect.top > -1) && (rect.top < (window.innerHeight * 0.75))) { element.setAttribute('data-js-position','in-viewport'); } else if ((rect.top > 0) && (rect.top < window.innerHeight)) { element.setAttribute('data-js-position','entering-viewport'); } else if (rect.top > window.innerHeight) { element.setAttribute('data-js-position','below-viewport'); } else if (rect.bottom < 0) { element.setAttribute('data-js-position','above-viewport'); } } window.addEventListener('scroll', function() { [].forEach.call(document.querySelectorAll('[data-js-position]'), el => { positionChecker.getPosition(el); }) }); ``` How would I implement something similar in React? Can you give me an example of a function that observes multiple divs in React? Even better: how can I abstract this function in `App.js`, so that I can use it also in child Components?<issue_comment>username_1: Make each `li` html element its own component and hold a `ref` reference to it in its own state. ``` class LiElement extends React.Component { componentDidMount() { this.ref.getPosition() } render() { return ( - this.ref = ctx}> ) } } ``` Upvotes: 3 <issue_comment>username_2: Iterating through refs might get you something similar to what you're trying to achieve. In this example I'm storing every node in a local Map so you can iterate through them and get their getBoundingClientRect. *Note, that there are several ways of doing this, you don't have to create a Map, you can just get each element's "ref", but you would have to assign a different "ref" value to each "li".* *Also, it would be a good idea to throttle the handleScroll call.*. ``` class App extends React.Component { constructor(props) { super(props); this._nodes = new Map(); } componentDidMount() { window.addEventListener("scroll", this.handleScroll); } handleScroll = e => { Array.from(this._nodes.values()) // make sure it exists .filter(node => node != null) .forEach(node => { this.getPosition(node); }); }; getPosition = node => { const rect = node.getBoundingClientRect(); // do something cool here console.log("rect:", rect); }; componentWillUnmount() { window.removeEventListener("scroll", this.handleScroll); } render() { return ( * this.\_nodes.set(1, c)}> Your thing 1 * this.\_nodes.set(2, c)}> Your thing 2 * this.\_nodes.set(3, c)}> Your thing 3 ); } } ``` Upvotes: 0 <issue_comment>username_3: Adding this other possible solution: creating a new react component `VisibilitySensor`, so to use only one ref and only one function ``` import React, { Component } from 'react'; class VisibilitySensor extends Component { componentDidMount() { window.addEventListener('scroll', this.getElementPosition = this.getElementPosition.bind(this)); this.getElementPosition(); } componentWillUnmount() { window.removeEventListener('scroll', this.getElementPosition); } getElementPosition() { const element = this.visibilitySensor; var rect = element.getBoundingClientRect(); if ((rect.top > 0) && (rect.top < (window.innerHeight * 0.75))) { element.setAttribute("data-position","in-viewport"); } else if (rect.top > window.innerHeight) { element.setAttribute("data-position","below-viewport"); } else if (rect.bottom < 0) { element.setAttribute("data-position","above-viewport"); } } render() { return ( { this.visibilitySensor = element; }}> {this.props.children} ); } } export default VisibilitySensor; ``` Then wrapping every `li` (or `div`) I need to watch with the above component. I personally ended up disliking the solution above, because the new added `div` would mess up with my css styling, particularly width of child related to width of parent, etc.. ``` * * * * ``` Upvotes: 0 <issue_comment>username_4: I was able to work around this with the useRef hook by adding a ref on the parent element that holds all the children you wish to scroll to. So in your case, you could do: TOP OF YOUR REACT CODE ``` const parentScrollRef = React.useRef(); ``` HTML ``` * * * * ``` Then you'd use call the onQuerySelectorAll on the ref. With react v16, you will be able to call the querySelectorAll on the ref.current object. So the code should look like this: ``` getPosition: function (element) { const rect = element.getBoundingClientRect(); if ((rect.top > -1) && (rect.top < (window.innerHeight * 0.75))) { element.setAttribute('data-js-position','in-viewport'); } else if ((rect.top > 0) && (rect.top < window.innerHeight)) { element.setAttribute('data-js-position','entering-viewport'); } else if (rect.top > window.innerHeight) { element.setAttribute('data-js-position','below-viewport'); } else if (rect.bottom < 0) { element.setAttribute('data-js-position','above-viewport'); } } // You would then target the ref, no need to hit the whole window. parentScrollRef.current.addEventListener('scroll', function() { const dataPositions = parentScrollRef.current.querySelectorAll(".data-js-position"); dataPositions.forEach((position) => { positionChecker.getPosition(el); } }); //Also remember your clean up xD return ( parentScrollRef.current.removeEventListener('scroll', function() { // cleanup function }); ) ``` Upvotes: 0
2018/03/18
894
3,465
<issue_start>username_0: I have used the and tags to create collapsible menus with buttons to open certain elements on the page, but when I click a button it closes the collapsed menu. How can I keep that collapsed menu opened after clicking a button within that menu? I have used the `onclick="closeAll()"` to close all the menus while I open one, but just need to keep the menu open that I am on after I click a button within that menu (to show users where they have navigated from). Here is part of my code: ``` ![](gfx/menu_motors.png) '; function closeAll() { var i, a = document.getElementsByTagName('details'); for (i in a) { a[i].open = ''; } } ```<issue_comment>username_1: First thing I would do is to stop using the inline event attributes. Then, to be able to have an event handler binded to a child element (your buttons) of another element which also has an event handler, the trick you need to know is the jQuery [`.stopPropagation()`](https://api.jquery.com/event.stoppropagation/). That is preventing the event from bubbling up to the parent... And below (as a bonus), I used only one function binded to the `sub_but` class for all the buttons. Then, using [`switch()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch), decide what to do based on the value of the clicked button. The [`details`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details) tag is interesting. I wasn't aware about it. It has a boolean attribute to expand/collapse it... But surprisingly, the values are `false` for collapsed or `""` for opened (`true` doesn't seem to work... And that is good to know). ```js // The arrow click handler $("details").on("click",function(){ console.log("You clicked on the detail arrow"); // Close all other details tags. $("details").each(function(){ this.open = false; }); }); // The button click handler $(".sub_but").on("click",function(event){ // To top the event from bubbling up event.stopPropagation(); // Evaluate which button was clicked switch(this.value){ case "Your Garage": console.log("You clicked Your Garage"); // Do something specific here... break; case "Travel By Car": console.log("You clicked Travel By Car"); // Do something specific here... break; case "Car Dealership": console.log("You clicked Car Dealership"); // Do something specific here... break; case "Street Race": console.log("You clicked Street Race"); // Do something specific here... break; case "Gas Station": console.log("You clicked Gas Station"); // Do something specific here... break; } }); ``` ```html ![](gfx/menu_motors.png) Some other details... What could be interesting to know? ``` *Better try the snippet in full page because of the console logs...* Upvotes: 3 [selected_answer]<issue_comment>username_2: This is the final code i needed and username_1's answer is absolutely correct thank you! ``` // The arrow click handler $("details").on("click",function(){ //console.log("You clicked on the detail arrow"); // Close all other details tags. $("details").each(function(){ this.open = false; }); }); // The button click handler $(".sub_but").on("click",function(event){ // To top the event from bubbling up event.stopPropagation(); }); ``` Upvotes: 1
2018/03/18
844
3,358
<issue_start>username_0: When trying to make the assertion "Does the current url equal homepage url?", should the current url logic be put directly into the test method. Like so, `let currentUrl = browser.getCurrentUrl();` or can this logic be put into a page object like a home page. To me it feels uncomfortable to ask a page object about the current url, if that url doesn't have anything to do with the page object itself. At the same time it is discouraged to put webdriver api calls directly in the test methods. How should I go about testing this type of logic?<issue_comment>username_1: First thing I would do is to stop using the inline event attributes. Then, to be able to have an event handler binded to a child element (your buttons) of another element which also has an event handler, the trick you need to know is the jQuery [`.stopPropagation()`](https://api.jquery.com/event.stoppropagation/). That is preventing the event from bubbling up to the parent... And below (as a bonus), I used only one function binded to the `sub_but` class for all the buttons. Then, using [`switch()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch), decide what to do based on the value of the clicked button. The [`details`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details) tag is interesting. I wasn't aware about it. It has a boolean attribute to expand/collapse it... But surprisingly, the values are `false` for collapsed or `""` for opened (`true` doesn't seem to work... And that is good to know). ```js // The arrow click handler $("details").on("click",function(){ console.log("You clicked on the detail arrow"); // Close all other details tags. $("details").each(function(){ this.open = false; }); }); // The button click handler $(".sub_but").on("click",function(event){ // To top the event from bubbling up event.stopPropagation(); // Evaluate which button was clicked switch(this.value){ case "Your Garage": console.log("You clicked Your Garage"); // Do something specific here... break; case "Travel By Car": console.log("You clicked Travel By Car"); // Do something specific here... break; case "Car Dealership": console.log("You clicked Car Dealership"); // Do something specific here... break; case "Street Race": console.log("You clicked Street Race"); // Do something specific here... break; case "Gas Station": console.log("You clicked Gas Station"); // Do something specific here... break; } }); ``` ```html ![](gfx/menu_motors.png) Some other details... What could be interesting to know? ``` *Better try the snippet in full page because of the console logs...* Upvotes: 3 [selected_answer]<issue_comment>username_2: This is the final code i needed and username_1's answer is absolutely correct thank you! ``` // The arrow click handler $("details").on("click",function(){ //console.log("You clicked on the detail arrow"); // Close all other details tags. $("details").each(function(){ this.open = false; }); }); // The button click handler $(".sub_but").on("click",function(event){ // To top the event from bubbling up event.stopPropagation(); }); ``` Upvotes: 1
2018/03/18
1,081
4,569
<issue_start>username_0: I have an Android Studio based application written in Java. I works fine and does not cause Android Studio to complain about anything: ``` public class MainActivity extends AppCompatActivity { static Context maincActivityContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mainActivityContext = getApplicationContext(); ... } /* JNI function called from c++ */ private void updateStatus(String event, final String call) { ... runOnUiThread(new Runnable() { @Override public void run() { TextView caller_uri = new TextView(mainActivityContext); ... } }); } ... } ``` I then went and asked Android Studio to convert it from Java to Kotlin. After the conversion, MainActivity looked like this: ``` class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mainActivityContext = applicationContext ... } /* JNI function called from C++ */ private void updateStatus(String event, final String call) { ... runOnUiThread(new Runnable() { @Override public void run() { TextView caller_uri = new TextView(mainActivityContext); ... } }); } companion object { internal lateinit var mainActivityContext: Context ... } } ``` Otherwise as in the Java version, but class variable mainActivityContext was moved from the top of MainActivity to companion object. Now again the app worked fine, but Android Studio complained about the mainActivityContext variable declaration: ``` Do not place Android context classes in static fields ``` I then moved the declaration back to where it was in the Java version: ``` class MainActivity : AppCompatActivity() { internal lateinit var mainActivityContext: Context override fun onCreate(savedInstanceState: Bundle?) { mainActivityContext = applicationContext ... ``` and Android Studio was satisfied. However, when I tried to run the app, it crashed like this: > > 03-18 16:08:52.788 7467 7467 E AndroidRuntime: kotlin.UninitializedPropertyAccessException: lateinit property mainActivityContext has not been initialized > > > 03-18 16:08:52.788 7467 7467 E AndroidRuntime: at com.foo.bar.MainActivity.updateStatus(MainActivity.kt:362) > > > For sure the variable was (like before) initialized in onCreate function. Question: Why the initialization is not available in the runOnUIThread code and what is the proper way to get the variable seen as initialized there? I checked earlier threads about this topic and could not find (or understand) an answer that would apply here.<issue_comment>username_1: Never put any android context inside a `static` field (which in `Kotlin` goes into the `companion object`), it is a bad practice since you can get a memory leak that way. If you want to access the context in a class, either pass a context to it in it's constructor or if the class is like an activity, use `getApplicationContext()` to access the Context. In your example, you don't need to store the context at all, since your activity is actually a `Context` itself (you can use `this` as context). Upvotes: 2 <issue_comment>username_2: I was able to get rid of mainActivityContext variable altogether by passing activity context as parameter to the function that starts the native application and then passing it back to MainActivity as parameter of updateStatus function: ``` class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { ... Thread(Runnable { nativeAppStart(applicationContext) }).start() } } ``` Native app looks like this: ``` static jobject *appContext; JNIEXPORT void JNICALL Java_com_tutpro_baresip_MainActivity_baresipStart(JNIEnv *env, jobject thiz, jobject *context) { appContext = context; ... } ``` and its updateStatus call looks like this: ``` jmethodID statusId = (*env)->GetMethodID(env, pctx->jniHelperClz, "updateStatus", "(Landroid/content/Context;Ljava/lang/String)V"); ... (*env)->CallVoidMethod(env, pctx->jniHelperObj, statusId, appContext, status); ``` Now I have working application context available in updateStatus function and th next problem is how to use that to set content view. I'll post another question about it. Thanks to all who contributed. Upvotes: 0
2018/03/18
628
2,077
<issue_start>username_0: Below is a small part of my raw json file, if a user is in game the game field appears in the json if there not in game the json removes the game field. I am trying to count how many users are in game by counting the game fields > > Raw json > > > ``` "members": [ { "username": "Squadman", "game": { "name": "World of Warcraft" }, } ] ``` what i have working on one part is ``` $count = count($result['members']); ``` and i echo it out like this ``` **php echo $count; ?** ``` but that just counts members I want to count the members only in game i tried ``` $countingame = count($result['members']['game]); ``` But get no result<issue_comment>username_1: Use > > $countingame = count($result['members'][0]['game]); > > > As members is an array Upvotes: 0 <issue_comment>username_2: I have tested this and this should work: JSON code: ``` { "members": [ { "username": "Squadman", "game": { "name": "World of Warcraft" } }, { "username": "Bob", "game": { "name": "Battlefield" } }, { "username": "Jane" } ] } ``` PHP code: ``` php $json = file_get_contents('https://example.com/file.json'); $decodedJson = json_decode($json, true); $array = $decodedJson['members']; $count = 0; foreach ($array as $key = $value) { if(isset($value['game']['name']) && $value['game']['name'] != '') { $count++; } } echo $count; ?> ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: To count members in games, you need to check for the existence of the 'game' key in the members array that you get from json\_decode. You can do that with isset. ``` $result = json_decode($result, true); $count = count($result['members']); for ($countingame = $i = 0; $i++; $i < $count) $countingame += isset($result['members'][$i]['game']) ? 1 : 0; echo "$count members in $countingame games"; ``` Upvotes: 1
2018/03/18
938
3,444
<issue_start>username_0: Based on my limited searching, it seems GraphQL can only support equal filtering. So, Is it possible to do Github GraphQL searching with the filtering conditions of, * stars > 10 * forks > 3 * total commit >= 5 * total issues >= 1 * open issues <= 60 * size > 2k * score > 5 * last update is within a year I.e., filtering will *all* above conditions. Is it possible?<issue_comment>username_1: This is not an answer but an update of what I've collected so far. * According to "[Select \* for Github GraphQL Search](https://stackoverflow.com/questions/49348326/)", not all above criteria might be available in the Repository edge. Namely, the "total commit", "open issues" and "score" might not be available. * The purpose of the question is obviously to find the valuable repositories and weed off the lower-quality ones. I've [**collected**](https://gist.github.com/suntong/30ca6ef2a7c32c966a045118fc57de6c) all the available fields that might be helpful for such assessment [here](https://gist.github.com/suntong/97a919c21e6adc53447f5059a34d334a). A copy of it as of 2018-03-18: ``` query SearchMostTop10Star($queryString: String!, $number_of_repos:Int!) { search(query: $queryString, type: REPOSITORY, first: $number_of_repos) { repositoryCount edges { node { ... on Repository { name url description # shortDescriptionHTML repositoryTopics(first: 12) {nodes {topic {name}}} primaryLanguage {name} languages(first: 3) { nodes {name} } releases {totalCount} forkCount pullRequests {totalCount} stargazers {totalCount} issues {totalCount} createdAt pushedAt updatedAt } } } } } variables { "queryString": "language:JavaScript stars:>10000", "number_of_repos": 3 } ``` Anyone can try it out [as per here](https://developer.github.com/v4/guides/using-the-explorer/). Upvotes: 1 <issue_comment>username_2: When querying for repositories, you can apply a filter only for a certain number of the fields in your list: * number of stars * number of forks * size * last update Although you cannot specify them in the query filter, you can include other fields in your query and verify the values in the client application: * total number of issues * number of open issues While, in theory, you can also query for the number of commits, applying your specific parameter arguments, that query returns a server error, it most probably times out. For that reason, those lines are commented out. Here's the GraphQL query: ``` query { search( type:REPOSITORY, query: """ stars:>10 forks:>3 size:>2000 pushed:>=2018-08-08 """, last: 100 ) { repos: edges { repo: node { ... on Repository { url allIssues: issues { totalCount } openIssues: issues(states:OPEN) { totalCount } # commitsCount: object(expression: "master") { # ... on Commit { # history { # totalCount # } # } # } } } } } } ``` The specification for repository queries can be found here: <https://help.github.com/en/articles/searching-for-repositories#search-by-repository-size> Upvotes: 4 [selected_answer]
2018/03/18
1,806
7,117
<issue_start>username_0: I want to capture mouse events for the child window,but the problem is Mouse events are not passed to this child window.... After finding information on the Internet, I found that I need to customize the button.But I still did not get any respond after doing this. Can anyone tell me what else I need to do to capture mouse events inside this Child window? Here is my code: ``` from PyQt5 import QtCore,QtWidgets from PyQt5.QtWidgets import * import sys class My_top_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(640, 532) self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) self.verticalLayout.setObjectName("verticalLayout") self.Products = MyButton() self.verticalLayout.addWidget(self.Products) self.Products.clicked.connect(self.accept) _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.Products.setText(_translate("Dialog", "top window")) def accept(self): self.dialog = QDialog() ui = My_second_Dialog() ui.setupUi(self.dialog) self.dialog.show() class My_second_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(640, 480) self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) self.verticalLayout.setObjectName("verticalLayout") self.fetch = MyButton() self.verticalLayout.addWidget(self.fetch) self.fetch.clicked.connect(self.accept) _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.fetch.setText(_translate("Dialog", "second window")) def accept(self): QMessageBox.information(self, "success", "success.") class MyButton(QPushButton): def __init__(self, parent=None): super(MyButton, self).__init__(parent) self.setFixedSize(111, 111) def mousePressEvent(self, QMouseEvent): if QMouseEvent.button() == QtCore.Qt.LeftButton: self.clicked.emit(True) self.parent().mousePressEvent(QMouseEvent) if __name__ == '__main__': app = QApplication(sys.argv) dialog = QDialog() ui = My_top_Dialog() ui.setupUi(dialog) dialog.show() sys.exit(app.exec_()) ```<issue_comment>username_1: Try it: ``` from PyQt5 import QtCore,QtWidgets from PyQt5.QtWidgets import * import sys class My_top_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(640, 532) self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) self.verticalLayout.setObjectName("verticalLayout") self.Products = MyButton() self.verticalLayout.addWidget(self.Products) self.Products.clicked.connect(self.accept) _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.Products.setText(_translate("Dialog", "top window")) def accept(self): self.dialog = QDialog() self.ui = My_second_Dialog() self.ui.setupUi(self.dialog) self.dialog.show() class My_second_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(640, 480) self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) self.verticalLayout.setObjectName("verticalLayout") self.fetch = MyButton() self.verticalLayout.addWidget(self.fetch) self.fetch.clicked.connect(self.accept) _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.fetch.setText(_translate("Dialog", "second window")) def accept(self): QMessageBox.information(self.fetch, "Success", "success.") # +++ self.fetch class MyButton(QPushButton): def __init__(self, parent=None): super(MyButton, self).__init__(parent) self.setFixedSize(111, 111) def mousePressEvent(self, event): #QMouseEvent): if event.button() == QtCore.Qt.LeftButton: self.clicked.emit(True) #self.parent().mousePressEvent(QMouseEvent) # --- if __name__ == '__main__': app = QApplication(sys.argv) dialog = QDialog() ui = My_top_Dialog() ui.setupUi(dialog) dialog.show() sys.exit(app.exec_()) ``` [![enter image description here](https://i.stack.imgur.com/LWiR3.jpg)](https://i.stack.imgur.com/LWiR3.jpg) Upvotes: -1 <issue_comment>username_2: It's the second way to solve the problem. Because the reply comment cannot show the code block, so I show my code here,I think the root cause of my problem is that I don't have associated main window and child window Completely.Whether it is building a relationship from a member or inheriting a class directly ,both of these Can make child window signal and trigger unaffected,Here is my code: ``` from PyQt5 import QtCore,QtWidgets from PyQt5.QtWidgets import * import sys class My_top_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(640, 532) self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) self.verticalLayout.setObjectName("verticalLayout") self.Products = MyButton() self.verticalLayout.addWidget(self.Products) self.Products.clicked.connect(self.accept) _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.Products.setText(_translate("Dialog", "top window")) def accept(self): dialog = My_second_Dialog() dialog.exec_() class My_second_Dialog(QDialog,My_top_Dialog): def __init__(self,parent = None): QDialog.__init__(self,parent) self.setupUi(self) def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(640, 480) self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) self.verticalLayout.setObjectName("verticalLayout") self.fetch = MyButton() self.verticalLayout.addWidget(self.fetch) self.fetch.clicked.connect(self.accept) _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.fetch.setText(_translate("Dialog", "second window")) def accept(self): QMessageBox.information(self, "success", "success.") class MyButton(QPushButton): def __init__(self, parent=None): super(MyButton, self).__init__(parent) self.setFixedSize(111, 111) def mousePressEvent(self, QMouseEvent): if QMouseEvent.button() == QtCore.Qt.LeftButton: self.clicked.emit(True) self.parent().mousePressEvent(QMouseEvent) if __name__ == '__main__': app = QApplication(sys.argv) dialog = QDialog() ui = My_top_Dialog() ui.setupUi(dialog) dialog.show() sys.exit(app.exec_()) ``` Upvotes: 1 [selected_answer]
2018/03/18
564
1,787
<issue_start>username_0: I want to know how to i sort the items i have in my listbox from a txt file by the lowest number to the highest? ``` private void Form1_Load(object sender, EventArgs e) { try { try { string[] lines = System.IO.File.ReadAllLines("file.txt"); foreach (string line in lines) { listBox1.Items.Add(line); } } catch { } } catch { } } ``` In my txt file ``` Shirt = 10$ pants = 20$ shoes = 60$ hat = 10$ socks = 5$ ```<issue_comment>username_1: you must seperate string and number in dicionary then orderby on numbers ``` Dictionary dic = new Dictionary(); foreach (var line in lines) { string[] str = line.Split('='); var num= str[1].Replace("$",""); // for seperate $ and number dic.Add(str[0], (Convert.ToInt32(num))); } foreach(var sortItem in dic.OrderBy(x=>x.Value)) { listBox1.Items.Add(sortItem .Key + " = "+ sortItem .Value.ToString() + "$"); } ``` output is : ``` socks = 5$ Shirt = 10$ hat = 10$ pants = 20$ shoes = 60$ ``` Upvotes: 1 <issue_comment>username_2: we can use linq to perform this operation: ``` string[] lines = File.ReadAllLines(@"D:\Professionals\POC\linQ\linQ\DataFile.txt", Encoding.UTF8); if (lines.Count() > 0) { Dictionary listIndex = lines.ToDictionary( x => x.Split('=')[0].Trim(), x => (x.Contains("$") ? Convert.ToInt32(x.Split('=')[1].Replace("$", "")) : 0) ); listIndex = listIndex.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value); if (listIndex != null && listIndex.Count > 0) { //---your code } } ``` Upvotes: 0
2018/03/18
1,195
3,692
<issue_start>username_0: I'm trying to execute a query via bash with `bq` command. The query works when executed via web UI as well as via app script @ script.google.com. However, when executed as a simple bash (or just via the cmd prompt) I keep receiving a `"Syntax error: Unexpected keyword THEN at [1:393]"`. Col 393 refers to the middle part of a case when statement. I've done lots of searching and can't figure out what I am doing wrong (since the query works elsewhere). Might anyone have advice on what is causing the error? ``` bq query --destination_table abcdefcloud:ds_tables.daily_over_frequency_output --replace --use_legacy_sql=false 'with freq as (select month as month,campaign_id,campaign,case when freq = '1' then 'a' when freq = '2' then 'b' when freq = '3-6' then 'c' when freq = '7-9' then 'd' when freq = '10-19' then 'e' when freq = '20-29' then 'f' when freq = '30-39' then 'g' when freq = '40-49' then 'h' when freq = '50-59' then 'i' when freq = '60-69' then 'j' when freq = '70-79' then 'k' when freq = '80-89' then 'l' when freq = '90-99' then 'm' when freq = '100+' then 'n' else 'other' end as sort, freq,sum(imps) as imps,sum(uu) as uu from... ``` Thanks so much for your help. Brian P<issue_comment>username_1: Assuming the `freq` column is numeric (it probably should be), then your `CASE` expression should fail, because `3-6` is not a valid number. Try this version instead: ``` case when freq = 1 then 'a' when freq = 2 then 'b' when freq between 3 and 6 then 'c' when freq between 7 and 9 then 'd' when freq between 10 and 19 then 'e' when freq between 20 and 29 then 'f' ... when freq > 100 then 'n' else 'other' end as sort ``` Upvotes: 0 <issue_comment>username_2: I think this is your problem: ``` freq = '1' then 'a' ``` If you look closely at the quotation marks, you'll notice that they are the same kind used to quote the query :) This ends up being evaluated as something like: ``` freq = then ``` ... Which I don't think is what you want. It should "just work", minus any semantic errors in your query, if you use double quotes instead. Upvotes: 0 <issue_comment>username_3: The issue here is being caused by the use of the same single quotes within the query which are the same quotes as what you are wrapping the entire query in. Your options: 1. Escape all the quotes in the query `when freq = \'1\' then \'a\'` 2. Change quotes to be double quotes `when freq = "1" then "a"` 3. Pass the query to bq query command via a file instead. `cat your_query.sql | bq query` **Option 3**: is the most elegant solution and also helps to organize your code in a nice way keeping SQL as SQL and not having lots of SQL embedded directly in bash code. You wouldn't need to make any changes to the current SQL. The full example would look like ``` cat your_query.sql | bq query \ --destination_table abcdefcloud:ds_tables.daily_over_frequency_output \ --replace \ --use_legacy_sql=false ``` Where `your_query.sql` would contain: ``` with freq as (select month as month,campaign_id,campaign,case when freq = '1' then 'a' when freq = '2' then 'b' when freq = '3-6' then 'c' when freq = '7-9' then 'd' when freq = '10-19' then 'e' when freq = '20-29' then 'f' when freq = '30-39' then 'g' when freq = '40-49' then 'h' when freq = '50-59' then 'i' when freq = '60-69' then 'j' when freq = '70-79' then 'k' when freq = '80-89' then 'l' when freq = '90-99' then 'm' when freq = '100+' then 'n' else 'other' end as sort, freq,sum(imps) as imps,sum(uu) as uu from... ``` Upvotes: 2 [selected_answer]
2018/03/18
959
3,043
<issue_start>username_0: I am trying to learn Fortran programming language, as a test I wrote a simple program like this: ``` !Fortran Program program first print *, "Hello World" end program first ``` Then I threw this code file in to mac terminal and run `gfortran first.f95` which then gave me an output of `a.out` as expected. However, when I try to run the output in terminal by navigating into the output directory and typing `./a.out`. It gave me this error output: ``` dyld: Library not loaded: @rpath/libgfortran.3.dylib Referenced from: /Users/liang/Desktop/Programs/Fortran/Test/a.out Reason: image not found ``` `liang` is my username.<issue_comment>username_1: Assuming the `freq` column is numeric (it probably should be), then your `CASE` expression should fail, because `3-6` is not a valid number. Try this version instead: ``` case when freq = 1 then 'a' when freq = 2 then 'b' when freq between 3 and 6 then 'c' when freq between 7 and 9 then 'd' when freq between 10 and 19 then 'e' when freq between 20 and 29 then 'f' ... when freq > 100 then 'n' else 'other' end as sort ``` Upvotes: 0 <issue_comment>username_2: I think this is your problem: ``` freq = '1' then 'a' ``` If you look closely at the quotation marks, you'll notice that they are the same kind used to quote the query :) This ends up being evaluated as something like: ``` freq = then ``` ... Which I don't think is what you want. It should "just work", minus any semantic errors in your query, if you use double quotes instead. Upvotes: 0 <issue_comment>username_3: The issue here is being caused by the use of the same single quotes within the query which are the same quotes as what you are wrapping the entire query in. Your options: 1. Escape all the quotes in the query `when freq = \'1\' then \'a\'` 2. Change quotes to be double quotes `when freq = "1" then "a"` 3. Pass the query to bq query command via a file instead. `cat your_query.sql | bq query` **Option 3**: is the most elegant solution and also helps to organize your code in a nice way keeping SQL as SQL and not having lots of SQL embedded directly in bash code. You wouldn't need to make any changes to the current SQL. The full example would look like ``` cat your_query.sql | bq query \ --destination_table abcdefcloud:ds_tables.daily_over_frequency_output \ --replace \ --use_legacy_sql=false ``` Where `your_query.sql` would contain: ``` with freq as (select month as month,campaign_id,campaign,case when freq = '1' then 'a' when freq = '2' then 'b' when freq = '3-6' then 'c' when freq = '7-9' then 'd' when freq = '10-19' then 'e' when freq = '20-29' then 'f' when freq = '30-39' then 'g' when freq = '40-49' then 'h' when freq = '50-59' then 'i' when freq = '60-69' then 'j' when freq = '70-79' then 'k' when freq = '80-89' then 'l' when freq = '90-99' then 'm' when freq = '100+' then 'n' else 'other' end as sort, freq,sum(imps) as imps,sum(uu) as uu from... ``` Upvotes: 2 [selected_answer]
2018/03/18
641
2,341
<issue_start>username_0: I am developing a search engine for our college using Django-Haystack-Solr. I want auto-suggestion and spell check feature. So I used `auto_query()` and `spelling_suggestion()` method. This is my `views.py` file. As of now, it is only static script not taking any form input from actual user. ``` from django.shortcuts import render from haystack.query import SearchQuerySet import json from django.http import HttpResponse def testpage(request): search_keyword = 'stikar' data = SearchQuerySet().auto_query(search_keyword) spelling = data.spelling_suggestion() sqs = SearchQuerySet().autocomplete(context_auto=spelling) suggestions = [result.title for result in sqs] link = [result.url for result in sqs] context = [result.context for result in sqs] the_data = json.dumps({ 'results': suggestions, 'link': link, 'context': context }) return HttpResponse(the_data, content_type='application/json') ``` My main `url.py` file: ``` from django.conf.urls import url, include from django.contrib import admin from search.views import testpage urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test/', testpage), # this is where JSON API is being generated url(r'^', include('haystack.urls')), # this is where actual search page with search form is ] ``` I want that JSON response to be called whenever I go to that particular view. I want AJAX request to perform. P.S: API is being rendered perfectly fine, no issues there. and sorry for bad English. Please ask me for any extra information. Thank you. :)<issue_comment>username_1: Try using [jQuery autocomplete](https://jqueryui.com/autocomplete/ "jQuery AutoComplete") and call this api Upvotes: 1 <issue_comment>username_2: I have JSON format something like this: ```json { 'results': [suggestions], 'link': [link], 'context': [context] } ``` This JSON comes from `/testpage/` and I want to use that in `/testquery/`. Here goes code for `testquery.html` let assume that you want to perform a GET method with query param `q`. ```js $.ajax({ type:"GET", url:"/testpage/", data:{ 'q': }, success:function(data) { console.log(data.results); console.log(data.link); console.log(data.context); } }); ``` Upvotes: 0