date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/16
576
2,100
<issue_start>username_0: We plan to have a large database with objects that have structure like this: Person1: skills: ['a','b','c'] Person2: skills: ['a','b'] Person3: skills: ['d','e','f'] Person4: skills: ['a','b','d'] And then given an input of skills, the algorithm/technology shoud be able to quickly find the best fit Person given some skills. Example: Find person with skills: a, b -> returns the list ordened like this [Person1,Person2,Person4,Person3] So i would like some recommendations on what technology (database / language) to build this on top and which algorithm should perform good on a database with about 10k registers.<issue_comment>username_1: Independently of the database you're planning to use queries you consider primary (the ones used more often) may have a huge benefit from indexing. You should create the index in the same order of the queries. Based on the model you used for your example I take it that you're using a NoSQL DB. Indexes provide better performance on search but takes more time to record. Finally I have to say that 10k is not a big collection, but querying nested arrays may be much slower without index. Upvotes: 0 <issue_comment>username_2: You want to use an [**inverted index**](https://en.wikipedia.org/wiki/Inverted_index) for this problem. The basic idea is to invert your representation from ``` 1 -> a, b, c 2 -> a, b 3 -> d, e, f 4 -> a, b, d ``` to ``` a -> 1, 2, 4 b -> 1, 2, 4 c -> 1 d -> 3, 4 e -> 3 f -> 3 ``` Now for each skill, you have a list of people capable of that skill (possibly ordered by skill level). In order to get the result for skills a, b you scan through the lists of a and b and increase the counter of each person you found, which gives you persons 1, 2, 4 each with count 3. This is basically the same index structure as used for text search (here you have documents containing terms). Systems like [elastic search](https://www.elastic.co/guide/en/elasticsearch/guide/current/inverted-index.html) include more advanced inverted indices that might suit your needs. Upvotes: 2 [selected_answer]
2018/03/16
1,207
4,758
<issue_start>username_0: I use io.fabric8.kubernetes-client, version 3.1.8 to do RollingUpdate of kubernetes resource. It is fine for Deployment. But I meet an exception for StatefulSet. But it is also fine if I use 'kubectl apply -f \*\*\*.yaml' for the StatefulSet. Code to RollingUpdate Deployment: ``` public void createOrReplaceResourceByYaml(String namespace, KubernetesResource resource) { KubernetesClient client = k8sRestClient.newKubeClient(); Deployment deployment = (Deployment) resource; logger.info(String.format("Create/Replace Deployment [%s] in namespace [%s].", ((Deployment) resource).getMetadata().getName(), namespace)); NonNamespaceOperation> deployments = client.extensions().deployments().inNamespace(namespace); Deployment result = deployments.createOrReplace(deployment); logger.info(String.format("Created/Replaced Deployment [%s].", result.getMetadata().getName())); } ``` Code to RollingUpdate StatefulSet ``` public void createOrReplaceResourceByYaml(String namespace, KubernetesResource resource) { KubernetesClient client = k8sRestClient.newKubeClient(); StatefulSet statefulSet = (StatefulSet) resource; logger.info(String.format("Create/Replace StatefulSet [%s] in namespace [%s].", statefulSet.getMetadata().getName(), namespace)); NonNamespaceOperation> statefulSets = client.apps().statefulSets().inNamespace(namespace); StatefulSet result = statefulSets.createOrReplace(statefulSet); logger.info(String.format("Created/Replaced StatefulSet [%s].", result.getMetadata().getName())); } ``` Exception when do RollingUpdate of StatefulSet > > Failure executing: PUT at: <https://kubernetes.default.svc/apis/apps/v1beta1/namespaces/itsma1/statefulsets/pro-rabbitmq>. Message: StatefulSet.apps "pro-rabbitmq" is invalid: spec: Forbidden: updates to statefulset spec for fields other than 'replicas', 'template', and 'updateStrategy' are forbidden.. Received status: Status(apiVersion=v1, code=422, details=StatusDetails(causes=[StatusCause(field=spec, message=Forbidden: updates to statefulset spec for fields other than 'replicas', 'template', and 'updateStrategy' are forbidden., reason=FieldValueForbidden, additionalProperties={})], group=apps, kind=StatefulSet, name=pro-rabbitmq, retryAfterSeconds=null, uid=null, additionalProperties={}), kind=Status, message=StatefulSet.apps "pro-rabbitmq" is invalid: spec: Forbidden: updates to statefulset spec for fields other than 'replicas', 'template', and 'updateStrategy' are forbidden., metadata=ListMeta(resourceVersion=null, selfLink=null, additionalProperties={}), reason=Invalid, status=Failure, additionalProperties={}). > > > **I am curious why the error happened and how to fix it.**<issue_comment>username_1: In StatefulSet, unlike Deployment, you can update only limited number of values - `replicas`, `template`, and `updateStrategy`. You issue happening because Fabric trying to update values which is impossible to update. The only thing you can do is carefully prepare a new `statefulSet` object which will have a same name as old but contain only values which you can update. Alternative way is to delete old `statefulSet` before upload a new one with a same name. Also, try to use a Kubernetes version upper 1.9 if you don't, because `statefulSet` is officially stable only in 1.9 and above. BTW, here is a [bug](https://github.com/fabric8io/kubernetes-client/issues/931) in Fabric's GitHub which can effect your code. Upvotes: 3 <issue_comment>username_2: You can try this to update the StatefulSet `client.apps().statefulSets().withName("repl1").rolling().withTimeout(5, TimeUnit.MINUTES).updateImage("");` If you want to only scale, you can try this `client.apps().statefulSets().withName("repl1").scale(5, true);` Upvotes: 3 [selected_answer]<issue_comment>username_3: I had this problem recently too, and I found the problem is the client tries to modify spec->selector->matchLabels->deployment, then the server throw that error back since that field is not editable based on the error message. So, I filed an [issue](https://github.com/fabric8io/kubernetes-client/issues/1076) to them. However, if you want true "rolling" update of your stateful set and your kube cluster is recent enough, you could try to do `k8client.apps().statefulSets().inNamespace(namespace).withName(name).cascading(false).replace(statefulSet)` The `cascading(false)` seems did the trick, it basically tells the client just update the stateful set without scaling down the pods first. And cluster will handle the rolling process for you if your update strategy is rolling. Upvotes: 0 <issue_comment>username_4: As stateful set is stateful object unlike pod. To update its configuration you can delete it and create again. Upvotes: 0
2018/03/16
614
2,489
<issue_start>username_0: How should I configure SwiftGen when using Cocoapods and multiple targets? I have a project with two targets (MyProject and MyProject Dev) which has SwiftGen integrated with Cocoapods. I can build the first target with no problems whatsoever. However the 'Dev' target always fails. The script phase is the last step in Build Phases, however running it earlier or later seems to make no difference. On failure, I've observed the following: * The generated .swift file has an import statement, 'import MyProject' which shouldn't be there * 'No type named [ClassName] in module [MyProject]' OR 'No such module [MyProject]' SwiftGen version I'm using is 5.2.1 Xcode 9.2, targeting iOS 10.0 SwiftGen from version 5 onwards requires a configuration file, so I've set one up as follows: ``` output_paths: Sources/Generated storyboards: - paths: MyProject/Storyboards/Base.lproj templateName: swift4 output: MyProject/Storyboards/Storyboards.swift params: ignoreTargetModule: true ``` So far I've looked up documentation and the following issue: [https://github.com/SwiftGen/SwiftGen/issues/273](https://github.com/SwiftGen/SwiftGen/issues/273 "using SwiftGen with multiple targets") However the difference is that I'm using a different type of SG installation and my project fails to build (rather than simply not generating any resources) Cleaning project, build folder and deleting derived data had no effect. I'm assuming that I may have missed something in configuration setup, but I can't see what that would be. First question on here, so apologies if I missed something, will be happy to edit.<issue_comment>username_1: Hesitant to call this a solution, it's more of a workaround, but the following approach has at least allowed the projects to be built and run. * Remove the SwiftGen script phase from the 'Dev' target * Build the project using the main scheme that includes SwiftGen to generate all the necessary objects and constructs * Switch to Dev scheme and run the project. The Strings.swift file created by SwiftGen is linked to both targets, so even after running the script in one scheme the resources within that file will be available to both regular and Dev targets. Hope this helps someone. Upvotes: 0 <issue_comment>username_2: I had the same issue with generating `Storyboard` file. Try to modify your config file: `params: ignoreTargetModule: true module:` Hope it will help. Upvotes: 3 [selected_answer]
2018/03/16
3,868
12,923
<issue_start>username_0: I am trying to complete some homework in a DeepLearning.ai course assignment. When I try the assignment in Coursera platform everything works fine, however, when I try to do the same `imports` on my local machine it gives me an error, ``` ModuleNotFoundError: No module named 'lr_utils' ``` I have tried resolving the issue by installing `lr_utils` but to no avail. There is no mention of this module online, and now I started to wonder if that's a proprietary to `deeplearning.ai`? Or can we can resolve this issue in any other way?<issue_comment>username_1: "lr\_utils" is not official library or something like that. Purpose of "lr\_utils" is to fetch the dataset that is required for course. 1. option (didn't work for me): [go to this page and there is a python code for downloading dataset and creating "lr\_utils"](https://zhuanlan.zhihu.com/p/29229244) * I had a problem with fetching data from provided url (but at least you can try to run it, maybe it will work) 2. option (worked for me): in the comments (at the same page [1](https://zhuanlan.zhihu.com/p/29229244)) there are links for manually downloading dataset and "lr\_utils.py", so here they are: * [link for dataset download](https://pan.baidu.com/s/1gfGhPLp) * [link for lr\_utils.py script download](https://pan.baidu.com/s/1pLv8Mx1) * Remember to extract dataset when you download it and you have to put dataset folder and "lr\_utils.py" in the same folder as your python script that is using it (script with this line "import lr\_utils"). Upvotes: 3 <issue_comment>username_2: Download the datasets from the answer above. And use this code (It's better than the above since it closes the files after usage): ``` def load_dataset(): with h5py.File('datasets/train_catvnoncat.h5', "r") as train_dataset: train_set_x_orig = np.array(train_dataset["train_set_x"][:]) train_set_y_orig = np.array(train_dataset["train_set_y"][:]) with h5py.File('datasets/test_catvnoncat.h5', "r") as test_dataset: test_set_x_orig = np.array(test_dataset["test_set_x"][:]) test_set_y_orig = np.array(test_dataset["test_set_y"][:]) classes = np.array(test_dataset["list_classes"][:]) train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0])) test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0])) return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes ``` Upvotes: 3 <issue_comment>username_3: As per the answer above, lr\_utils is a part of the deep learning course and is a utility to download the data sets. It should readily work with the paid version of the course but in case you 'lost' access to it, I noticed this github project has the lr\_utils.py as well as some data sets ~~https://github.com/andersy005/deep-learning-specialization-coursera/tree/master/01-Neural-Networks-and-Deep-Learning/week2/Programming-Assignments~~ Note: The chinese website links did not work when I looked at them. Maybe the server storing the files expired. I did see that this github project had some datasets though as well as the lr\_utils file. EDIT: The link no longer seems to work. Maybe this one will do? <https://github.com/knazeri/coursera/blob/master/deep-learning/1-neural-networks-and-deep-learning/2-logistic-regression-as-a-neural-network/lr_utils.py> Upvotes: 4 [selected_answer]<issue_comment>username_4: You will be able to find the `lr_utils.py` and all the other `.py` files (and thus the code inside them) required by the assignments: 1. Go to the first assignment (ie. Python Basics with numpy) - *which you can always access whether you are a paid user or not* 2. And then click on '**Open**' button in the Menu bar above. *(see the image below)* ![](https://i.stack.imgur.com/IxZxZ.png). Then you can include the code of the modules directly in your code. Upvotes: 4 <issue_comment>username_5: 1. Here is the way to get dataset from as @username_3: <https://github.com/andersy005/deep-learning-specialization-coursera/tree/master/01-Neural-Networks-and-Deep-Learning/week2/Programming-Assignments/datasets> 2. write a lr\_utils.py file, as above answer @username_2, put it into any of sys.path() directory. 3. def load\_dataset(): with h5py.File('datasets/train\_catvnoncat.h5', "r") as train\_dataset: .... !!! BUT make sure that you delete 'datasets/', cuz now the name of your data file is train\_catvnoncat.h5 4. restart kernel and good luck. Upvotes: 0 <issue_comment>username_6: I may add to the answers that you can save the file with lr\_utils script on the disc and import that as a module using importlib util function in the following way. The below code came from the general thread about import functions from external files into the current user session: [How to import a module given the full path?](https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path) ``` ### Source load_dataset() function from a file # Specify a name (I think it can be whatever) and path to the lr_utils.py script locally on your PC: util_script = importlib.util.spec_from_file_location("utils function", "D:/analytics/Deep_Learning_AI/functions/lr_utils.py") # Make a module load_utils = importlib.util.module_from_spec(util_script) # Execute it on the fly util_script.loader.exec_module(load_utils) # Load your function load_utils.load_dataset() # Then you can use your load_dataset() coming from above specified 'module' called load_utils train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_utils.load_dataset() # This could be a general way of calling different user specified modules so I did the same for the rest of the neural network function and put them into separate file to keep my script clean. # Just remember that Python treat it like a module so you need to prefix the function name with a 'module' name eg.: # d = nnet_utils.model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1000, learning_rate = 0.005, print_cost = True) nnet_script = importlib.util.spec_from_file_location("utils function", "D:/analytics/Deep_Learning_AI/functions/lr_nnet.py") nnet_utils = importlib.util.module_from_spec(nnet_script) nnet_script.loader.exec_module(nnet_utils) ``` That was the most convenient way for me to source functions/methods from different files in Python so far. I am coming from the R background where you can call just one line function source() to bring external scripts contents into your current session. Upvotes: 0 <issue_comment>username_7: below is your code, just save your file named "lr\_utils.py" and now you can use it. ``` import numpy as np import h5py def load_dataset(): train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r") train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels test_dataset = h5py.File('datasets/test_catvnoncat.h5', "r") test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels classes = np.array(test_dataset["list_classes"][:]) # the list of classes train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0])) test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0])) return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes ``` if your code file can not find you newly created lr\_utils.py file just write this code: ``` import sys sys.path.append("full path of the directory where you saved Ir_utils.py file") ``` Upvotes: 1 <issue_comment>username_8: The above answers didn't help, some links had expired. So, **lr\_utils** is not a pip library but a file in the same notebook as the CourseEra website. You can click on "Open", and it'll open the explorer where you can download everything that you would want to run in another environment. (I used this on a browser.) Upvotes: 0 <issue_comment>username_9: The way I fixed this problem was by: 1. clicking **File -> Open** -> You will see the **lr\_utils.py** file ( it does not matter whether you have paid/free version of the course). 2. opening the **lr\_utils.py** file in Jupyter Notebooks and clicking **File -> Download** ( store it in your own folder ), rerun importing the modules. It will work like magic. 3. I did the same process for the **datasets** folder. Upvotes: 3 <issue_comment>username_10: This is how i solved mine, i copied the lir\_utils file and paste it in my notebook thereafter i downloaded the dataset by zipping the file and extracting it. With the following code. Note: Run the code on coursera notebook and select only the zipped file in the directory to download. ``` !pip install zipfile36 zf = zipfile.ZipFile('datasets/train_catvnoncat_h5.zip', mode='w') try: zf.write('datasets/train_catvnoncat.h5') zf.write('datasets/test_catvnoncat.h5') finally: zf.close() ``` Upvotes: 0 <issue_comment>username_11: I could download the dataset directly from coursera page. Once you open the Coursera notebook you go to File -> Open and the following window will be display: [enter image description here](https://i.stack.imgur.com/JJOSA.png) Here the notebooks and datasets are displayed, you can go to the datasets folder and download the required data for the assignment. The package lr\_utils.py is also available for downloading. Upvotes: 2 <issue_comment>username_12: You can download train and test dataset directly here: <https://github.com/berkayalan/Deep-Learning/tree/master/datasets> And you need to add this code to the beginning: ``` import numpy as np import h5py import os def load_dataset(): train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r") train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels test_dataset = h5py.File('datasets/test_catvnoncat.h5', "r") test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels classes = np.array(test_dataset["list_classes"][:]) # the list of classes train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0])) test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0])) return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes ``` Upvotes: 2 <issue_comment>username_13: I faced similar problem and I had followed the following steps: =============================================================== 1. import the following library ------------------------------- ```` import numpy as np import matplotlib.pyplot as plt import h5py import scipy from PIL import Image from scipy import ndimage ```` 2. download the train\_catvnoncat.h5 and test\_catvnoncat.h5 from any of the below link: ---------------------------------------------------------------------------------------- [https://github.com/berkayalan/Neural-Networks-and-Deep-Learning/tree/master/datasets] or [https://github.com/JudasDie/deeplearning.ai/tree/master/Improving%20Deep%20Neural%20Networks/Week1/Regularization/datasets] 3. create a folder named datasets and paste these two files in this folder. --------------------------------------------------------------------------- [ Note: datasets folder and your source code file should be in same directory] 4. run the following code ------------------------- ```` def load_dataset(): with h5py.File('datasets1/train_catvnoncat.h5', "r") as train_dataset: train_set_x_orig = np.array(train_dataset["train_set_x"][:]) train_set_y_orig = np.array(train_dataset["train_set_y"][:]) with h5py.File('datasets1/test_catvnoncat.h5', "r") as test_dataset: test_set_x_orig = np.array(test_dataset["test_set_x"][:]) test_set_y_orig = np.array(test_dataset["test_set_y"][:]) classes = np.array(test_dataset["list_classes"][:]) train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0])) test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0])) return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes ```` 5. Load the data: ----------------- ```` train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset() ```` check datasets -------------- ```` print(len(train_set_x_orig)) print(len(test_set_x_orig)) ```` your data set is ready, you may check the len of the train\_set\_x\_orig, train\_set\_y variable. For mine, it was 209 and 50 ----------------------------------------------------------------------------------------------------------------------------- Upvotes: 2
2018/03/16
661
2,475
<issue_start>username_0: I have a number of methods in a React class component. The component itself receives a number of props. I am wondering if I should take the props and add each of them as `this.propName` in the constructor and then access the props using `this.propName`. Here is an example. What is best practice? ``` const classComponent = class classComponent extends Component { constructor(props) { super(props) this.propA = props.propA this.propB = props.propB } methodA() { console.log(this.propA) } } ``` **Alternative** ``` const classComponent = class classComponent extends Component { constructor(props) { super(props) } methodA() { console.log(this.props.propA) } } ```<issue_comment>username_1: Once you create a variable it uses memory and, even if you are referencing a type, like an array or an object, you make your file bigger. Creating new names for variables already accessible to your class/function make no sense, so don't do it. Upvotes: 0 <issue_comment>username_2: Official documentation of React.js in [State and Lifecycle](https://reactjs.org/docs/state-and-lifecycle.html) section says: > > While `this.props` is set up by React itself and `this.state` has a special meaning, **you are free to add additional fields to the class manually if you need to store something that is not used for the visual output**. > > > In your case, most likely it should stay as a `prop`. Whenever you pass anything as a parameter, which in React.js philosophy would be a `prop`, it's most likely an ingredient of the visual effect. Upvotes: 2 [selected_answer]<issue_comment>username_3: The way you handled the `props` does not allow the component to update when it receives new props; mainly because `constructor` is only called once--at the creation of the component. A better way to do it is to use Destructuring assignment in the `render` function: ``` render() { {propA, propB, ...rest} = this.props; //Rest code here, using propA, propB //However, don't use this.propA, or this.propB } ``` If you still like to do the way you want to do, you have to add the following function inside your component, to make your component update whenever it receives new props: ``` componentWillReceiveProps(nextProps) { this.propA = nextProps.propA; this.propB = nextProps.propB; } ``` As you can see, unnecessary code had to be included, so I think this is a wrong way to do it! Upvotes: 0
2018/03/16
641
2,472
<issue_start>username_0: I made a main menu in unity so now I'm down to the scripting. I have tried the `mouseup` / `mousedown` functions but nothing is wrong with my code but it won't work period no debug logs not errors just plain nothing. Here's my C# Script to change levels. ``` using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MainMenu : MonoBehaviour { public bool Start; public bool Quit; void OnMouseUp(){ if(Start) { SceneManager.LoadScene(1); } if (Quit) { Application.Quit(); } } } ``` This is very simple but I still don't see why it isn't working.<issue_comment>username_1: Once you create a variable it uses memory and, even if you are referencing a type, like an array or an object, you make your file bigger. Creating new names for variables already accessible to your class/function make no sense, so don't do it. Upvotes: 0 <issue_comment>username_2: Official documentation of React.js in [State and Lifecycle](https://reactjs.org/docs/state-and-lifecycle.html) section says: > > While `this.props` is set up by React itself and `this.state` has a special meaning, **you are free to add additional fields to the class manually if you need to store something that is not used for the visual output**. > > > In your case, most likely it should stay as a `prop`. Whenever you pass anything as a parameter, which in React.js philosophy would be a `prop`, it's most likely an ingredient of the visual effect. Upvotes: 2 [selected_answer]<issue_comment>username_3: The way you handled the `props` does not allow the component to update when it receives new props; mainly because `constructor` is only called once--at the creation of the component. A better way to do it is to use Destructuring assignment in the `render` function: ``` render() { {propA, propB, ...rest} = this.props; //Rest code here, using propA, propB //However, don't use this.propA, or this.propB } ``` If you still like to do the way you want to do, you have to add the following function inside your component, to make your component update whenever it receives new props: ``` componentWillReceiveProps(nextProps) { this.propA = nextProps.propA; this.propB = nextProps.propB; } ``` As you can see, unnecessary code had to be included, so I think this is a wrong way to do it! Upvotes: 0
2018/03/16
274
895
<issue_start>username_0: I have a row that is created through jQuery via append, which contains a delete button. **Desire Output:** 1. Instead of the word "delete" I would like to implement a font-awesome "fa-fa-trash" icon in the button. 2. What is the proper way to implement this? ```js function dataTable(data) { var row = $('| '); $('#table').append(row); row.append($( ' |')); } ```<issue_comment>username_1: You just change the input type submit to button ``` row.append(' delete |'); ``` Upvotes: 0 <issue_comment>username_2: [here is my Jsfiddle](https://jsfiddle.net/Munkhdelger/mavvtkve/) ``` Submit ``` ```js time = function datatable(data){ table = $("table tbody tr"); table.append( " Submit "+data+" |" ); } ``` ```html append button to table bruh | | | --- | | first td without for visible | ``` Upvotes: 2 [selected_answer]
2018/03/16
911
2,930
<issue_start>username_0: *QGIS* installer keeps telling "QGIS requires Python 3.6." after which it quits installing on *Mac*. However I have python 3.6.4 at least on 4 locations 1) ~/anaconda/bin/python 2) /usr/bin/python3 3) /usr/local/bin/python 4) /usr/local/bin/python3.6 (through a symbolic link). All these files refer to the same file, when invoking them they all yield: Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 12:04:33) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE\_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. Does anyone know where `QGIS3` installer looks for `python 3.6`, so I could set a symbolic link to the `python 3.6` version that is already installed through `Anaconda`? Thanks, Theo<issue_comment>username_1: According to [this answer](https://gis.stackexchange.com/a/274600/77207), the path is in: ``` /usr/local/Cellar/python3/3.x.y_z/Frameworks/Python.framework ``` Upvotes: 1 <issue_comment>username_2: Ran into this problem myself. Creating a symbolic link to where the installer expects to find python works. I had to find where Homebrew installed Python... (note the version in the path) ``` sudo ln -s /usr/local/Cellar/python/3.6.5/Frameworks/Python.framework /Library/Frameworks/Python.framework ``` Upvotes: 4 <issue_comment>username_3: I had to install python 3.6 directly downloaded from www.python.org (ignoring the already installed version by Anaconda). This worked. See remark on <http://www.kyngchaos.com/blog/2018/20180315_qgis_3_must_use_python.org_python_3> Upvotes: 2 <issue_comment>username_4: I had python 3.7 and QGIS 3.X was looking for python 3.6. error: "*qgis requires python 3.6*" to downgrade I tried many things but finally "brew prune" and installing 3.6 directly from python.org worked for me. <https://www.python.org/downloads/release/python-366/> Upvotes: 3 <issue_comment>username_5: I installed Python 3.6.5 from the main [Python webpage](https://www.python.org/downloads/release/python-365/) ignoring the existing ***Anaconda*** version that I use regularly. Then once it is completed I checked my PATH and I had both directory ```none echo $PATH /Library/Frameworks/Python.framework/Versions/3.6/bin:/anaconda3/bin: ``` You can check the folder of python using `which python3` and it should give you the Frameworks. I installed the GDAL and then QGIS without any problems. I run QGIS and it is working, until now :) **Remember:** you will need to use pip3 to install any missing modules other wise it you will be calling the pip under anaconda. owslib, PyYaml, psycopg2, jinja2, pygments, numpy, plotly. ``` pip3 install modulename ``` Upvotes: 0 <issue_comment>username_6: Install via the terminal with ``` conda install -c conda-forge qgis ``` I had the same issue and could only install QGIS with this solution. <https://anaconda.org/conda-forge/qgis> Upvotes: 2
2018/03/16
376
1,080
<issue_start>username_0: I have: ``` $regExge = "/(?!((<.*?)))\b(Öffnung)\b(?!(([^<>]*?)>))/s"; $replacege = "Öffnung"; ``` And I used preg\_replace to replace Öffnung string to html `Öffnung` ``` $content = preg_replace($regExge, $replacege, $content); ``` But it not working, only working with normal string. There any way? Thank you.<issue_comment>username_1: You need to indicate that your pattern should cover an encoding which includes the special characters. UTF-8 is one option here, and can be indicated by using `/u` at the end of the pattern: ``` $regExge = "/(?!((<.*?)))\b(Öffnung)\b(?!(([^<>]*?)>))/su"; $replacege = "Öffnung"; // ^^^ $content = preg_replace($regExge, "stuff", $replacege); print $content; stuff ``` [Demo ----](http://rextester.com/NPHWH97463) Upvotes: 3 [selected_answer]<issue_comment>username_2: You can try this modified version. ``` $content = "Offnung Öffnung s;ldjfjkasÖffnung"; $regExge = "/Öffnung/"; $replacege = "Öffnung"; $content = preg_replace($regExge, $replacege, $content); echo $content; ``` Upvotes: 1
2018/03/16
389
1,266
<issue_start>username_0: For example, ``` hash09 Update something5 hashNew Update something4 hashOld Update something3 hash03 Update something2 hash02 Update something hash01 Add something ``` If I want to see what has beed introduced in hashNew, should I use ``` git diff hashNew..hashOld ``` or ``` git diff hashOld..hashNew ``` or ``` git diff hashNew~ ``` or ``` git diff hashNew^ ```<issue_comment>username_1: To show what changes are introduced by a particular commit, `git show` is handy. More info at [man git-show](https://gitirc.eu/git-show.html). For more information about the syntax, [man gitrevisions](https://gitirc.eu/gitrevisions.html) gives thorough explanations. Upvotes: 0 <issue_comment>username_2: You should use: ``` git diff hashOld hashNew ``` it produces the same output as: ``` git diff hashOld..hashNew ``` Keep in mind that: * ^ – indicates the parent commit * ~ – indicates the first parent commit so, in order to use them to see what has been introduced in hasNew, you could write: ``` git diff hashNew~ hasNew ``` or ``` git diff hasNew^ hasNew ``` with ``` git diff hashNew^ ``` you would be comparing the working directory with hashOld, since hasOld is the parent commit of hashNew Upvotes: 1
2018/03/16
358
1,183
<issue_start>username_0: I am very new to Scala. I would like to assign a string as variable name: ``` val names = Vector("a","b","c") for (name <~ names){ val = "test" } ``` I would like to have three variables assigned as: ``` a: String = test b: String = test c: String = test ``` How do I code to get this result?<issue_comment>username_1: To show what changes are introduced by a particular commit, `git show` is handy. More info at [man git-show](https://gitirc.eu/git-show.html). For more information about the syntax, [man gitrevisions](https://gitirc.eu/gitrevisions.html) gives thorough explanations. Upvotes: 0 <issue_comment>username_2: You should use: ``` git diff hashOld hashNew ``` it produces the same output as: ``` git diff hashOld..hashNew ``` Keep in mind that: * ^ – indicates the parent commit * ~ – indicates the first parent commit so, in order to use them to see what has been introduced in hasNew, you could write: ``` git diff hashNew~ hasNew ``` or ``` git diff hasNew^ hasNew ``` with ``` git diff hashNew^ ``` you would be comparing the working directory with hashOld, since hasOld is the parent commit of hashNew Upvotes: 1
2018/03/16
341
1,186
<issue_start>username_0: ``` Optional> optionalList = getList(someInput); ``` How do i retrieve an element from this list? How to iterate this list?<issue_comment>username_1: You can unwrap the list and use it like a normal list. ``` List list = optionalList.orElseGet(Collections::emptyList); list.forEach(System.out::println); // process the list // e.g. printing its elements ``` If you just want a `forEach(..)` and don't need the list unwrapped. ``` optionalList.orElseGet(Collections::emptyList) .forEach(System.out::println); ``` You can check if is present ``` if (optionalList.isPresent()) { List myList = optionalList.get(); // process list present } else { // process not present } ``` Or keep using optional to access to one of its elements ``` Optional longAt5 = optionalList.filter(list -> list.size() > 5) .map(list -> list.get(5)); ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Check if there is a value present and then do some logic: ``` optionalList.ifPresent(list -> { ... }); ``` As for processing the list, you could do: ``` optionalList.orElseGet(() -> Collections.emptyList()).forEach(e -> {...}); ``` Upvotes: 1
2018/03/16
647
1,923
<issue_start>username_0: ``` #include #include int \*squares(int max\_val) { int \*result = malloc(max\_val \* sizeof(int)); int i; for(i = 1; i <= max\_val; i++) { result[i-1] = i\*i; } return(result); } int main() { int \*sq = squares(10); int i; for(i = 0; i < 10; i++) { printf("%d\t", sq[i]); } printf("\n"); return(0); } ``` Basically take's an integer and returns a integer array of its squares. (Above works) How would I do this without malloc or pointers? ``` #include #include int[] squares(int max\_val) { int result[max\_val]; int i; for(i = 1; i <= max\_val; i++) { result[i-1] = i\*i; } return(result); } int main() { int sq[] = squares(10); int i; for(i = 0; i < 10; i++) { printf("%d\t", sq[i]); } printf("\n"); return(0); } ``` Above errors because of the function call. Is this possible? Or do we have to do it with pointers?<issue_comment>username_1: You can unwrap the list and use it like a normal list. ``` List list = optionalList.orElseGet(Collections::emptyList); list.forEach(System.out::println); // process the list // e.g. printing its elements ``` If you just want a `forEach(..)` and don't need the list unwrapped. ``` optionalList.orElseGet(Collections::emptyList) .forEach(System.out::println); ``` You can check if is present ``` if (optionalList.isPresent()) { List myList = optionalList.get(); // process list present } else { // process not present } ``` Or keep using optional to access to one of its elements ``` Optional longAt5 = optionalList.filter(list -> list.size() > 5) .map(list -> list.get(5)); ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Check if there is a value present and then do some logic: ``` optionalList.ifPresent(list -> { ... }); ``` As for processing the list, you could do: ``` optionalList.orElseGet(() -> Collections.emptyList()).forEach(e -> {...}); ``` Upvotes: 1
2018/03/16
530
1,938
<issue_start>username_0: VERY new, barely understand functions. Here is an example of my issue: ``` function getx() { x = 3; } function gety() { y = 2; } getx(); gety(); document.write("The sum of x and y is " + x + y); ``` `OUTPUT: The sum of x and y is 32` I would like to know how I can make it so x + y = 5 instead of 32. Obviously 3 + 2 isn't 32, can someone explain to me how I might output the right answer?<issue_comment>username_1: You're concatenating the string with `x` before the add operation. So, you need to wrap your Math operation with parentheses in order to avoid string concatenation. ```js function getx() { x = 3; } function gety() { y = 2; } getx(); gety(); document.write("The sum of x and y is " + (x + y)); ``` Upvotes: 2 <issue_comment>username_2: Your functions getx() and gety() aren’t returning any values because you don’t have a return statement. By calling the functions the way you do, you are creating two global variables: x and y, and initializing the to 3 and 2, respectively. You should avoid using global variables in this capacity. Your global variables (or functions) can overwrite window variables (or functions). Any function, including the window object, can overwrite your global variables and functions. Your variables should be declared with var instead. Unless specificied, js variables are not strongly typed, And since you are using the concatenation operator before adding the variables together, it sees them as a string and this is why your concatenation is putting 3 and 2 together. If you change your code to something like this, it should accomplish what you’re trying to achieve. ``` function getx() { var x = 3; return x; } function gety() { var y = 2; return y; } document.write("The sum of x and y is " + (gety() + getx())); ``` Upvotes: 0
2018/03/16
1,981
7,111
<issue_start>username_0: I am running Docker in Docker (specifically to run Jenkins which then runs Docker builder containers to build a project images and then runs these and then the test containers). This is how the jenkins image is built and started: ``` docker build --tag bb/ci-jenkins . mkdir $PWD/volumes/ docker run -d --network=host \ -v /var/run/docker.sock:/var/run/docker.sock \ -v /usr/bin/docker:/usr/bin/docker \ -v $PWD/volumes/jenkins_home:/var/jenkins_home \ --name ci-jenkins bb/ci-jenkins ``` Jenkins works fine. But then there is a `Jenkinsfile` based job, which runs this: ``` docker run -i --rm -v /var/jenkins_home/workspace/forkMV_jenkins-VOLTRON-3057-KQXKVJNXOU4DGSUG3P27IR3QEDHJ6K7HPDEZYN7W6HCOTCH3QO3Q:/tmp/build collab/collab-services-api-mvn-builder:2a074614 mvn -B -T 2C install ``` And this ends up with an error: > > The goal you specified requires a project to execute but there is no POM in this directory (/tmp/build). > > > When I do `docker exec -it sh` to the container, the `/tmp/build` is empty. But when I am in the Jenkins container, the path `/var/jenkins_home/...QO3Q/` exists and it contains the workspace with all the files checked out and prepared. So I wonder - **how can Docker happily mount the volume and then it's empty?\*** What's even more confusing, this setup works for my colleague on Mac. I am on Linux, Ubuntu 17.10, Docker latest.<issue_comment>username_1: After some research, calming down and thinking, I realized that Docker-in-Docker is not **really** so much "-in-", as it is rather "Docker-next-to-Docker". The trick to make a container able to run another container is sharing `/var/run/docker.sock` through a volume: `-v /var/run/docker.sock:/var/run/docker.sock` And then the `docker` client in the container actually calls Docker on the host. The volume source path (left of `:`) does not refer to the middle container, but to the host filesystem! After realizing that, the fix is to make the paths to the Jenkins `workspace` directory the same in the host filesystem and the Jenkins (middle) container: ``` docker run -d --network=host \ ... -v /var/jenkins_home:/var/jenkins_home ``` And voilá! It works. (I created a symlink instead of moving it, seems to work too.) It is a bit complicated if you're looking at colleague's Mac, because Docker is implemented a bit differently there - it is running in an Alpine Linux based VM but pretending not to. (Not 100 % sure about that.) On Windows, I read that the paths have another layer of abstraction - mapping from `C:/somewhere/...` to a Linux-like path. I hope I'll save someone hours of figuring out :) Upvotes: 6 [selected_answer]<issue_comment>username_2: A better approach is to use [Jenkins Docker plugin](https://wiki.jenkins.io/display/JENKINS/Docker+Plugin) and let it do all the mountings for you and just add `-v /var/run/docker.sock:/var/run/docker.sock` in its `inside` function arguments. E.g. ``` docker.build("bb/ci-jenkins") docker.image("bb/ci-jenkins").inside('-v /var/run/docker.sock:/var/run/docker.sock') { ... } ``` Upvotes: 2 <issue_comment>username_3: Alternative Solution with Docker cp =================================== I was facing the same problem of mounting volumes from a Build that runs in a Docker Container running in a Jenkins server in Kubernetes. As we use `docker-in-docker`, `dind`, I couldn't mount the volume in either ways proposed here. I'm still not sure what the reason is, but I found an alternative way: use `docker cp` to copy the build artifacts. [![enter image description here](https://i.stack.imgur.com/4euQN.png)](https://i.stack.imgur.com/4euQN.png) Multi-stage Docker Image for Tests ================================== I'm using the following Dockerfile stage for Unit + Integration tests. ``` # # Build stage to for building the Jar # FROM maven:3.2.5-jdk-8 as builder MAINTAINER <EMAIL> # Only copy the necessary to pull only the dependencies from registry ADD ./pom.xml /opt/build/pom.xml # As some entries in pom.xml refers to the settings, let's keep it same ADD ./settings.xml /opt/build/settings.xml WORKDIR /opt/build/ # Prepare by downloading dependencies RUN mvn -s settings.xml -B -e -C -T 1C org.apache.maven.plugins:maven-dependency-plugin:3.0.2:go-offline # Run the full packaging after copying the source ADD ./src /opt/build/src RUN mvn -s settings.xml install -P embedded -Dmaven.test.skip=true -B -e -o -T 1C verify # Building only this stage can be done with the --target builder switch # 1. Build: docker build -t config-builder --target builder . # When running this first stage image, just verify the unit tests # Overriden them by removing the "!" for integration tests # 2. docker run --rm -ti config-builder mvn -s settings.xml -Dtest="*IT,*IntegrationTest" test CMD mvn -s settings.xml -Dtest="!*IT,!*IntegrationTest" -P jacoco test ``` Jenkins Pipeline For tests ========================== * My Jenkins pipeline has a stage for running parallel tests (Unit + Integration). * What I do is to build the Test Image in a stage, and run the tests in parallel. * I use `docker cp` to copy the build artifacts from inside the test docker container that can be started after running the tests in a named container. + Alternatively, you can use Jenkins stash to carry the test results to a `Post` stage At this point, I solved the problem with a `docker run --name test:SHA` and then I use `docker start test:SHA` and then `docker cp test:SHA:/path .`, where `.` is the current workspace directory, which is similar to what we need with a docker volume mounted to the current directory. ``` stage('Build Test Image') { steps { script { currentBuild.displayName = "Test Image" currentBuild.description = "Building the docker image for running the test cases" } echo "Building docker image for tests from build stage ${env.GIT_COMMIT}" sh "docker build -t tests:${env.GIT_COMMIT} -f ${paas.build.docker.dockerfile.runtime} --target builder ." } } stage('Tests Execution') { parallel { stage('Execute Unit Tests') { steps { script { currentBuild.displayName = "Unit Tests" currentBuild.description = "Running the unit tests cases" } sh "docker run --name tests-${env.GIT_COMMIT} tests:${env.GIT_COMMIT}" sh "docker start tests-${env.GIT_COMMIT}" sh "docker cp tests-${env.GIT_COMMIT}:/opt/build/target ." // https://jenkins.io/doc/book/pipeline/jenkinsfile/#advanced-scripted-pipeline#using-multiple-agents stash includes: '**/target/*', name: 'build' } } stage('Execute Integration Tests') { when { expression { paas.integrationEnabled == true } } steps { script { currentBuild.displayName = "Integration Tests" currentBuild.description = "Running the Integration tests cases" } sh "docker run --rm tests:${env.GIT_COMMIT} mvn -s settings.xml -Dtest=\"*IT,*IntegrationTest\" -P jacoco test" } } } } ``` Upvotes: 2
2018/03/16
1,817
6,823
<issue_start>username_0: Title says the majority of whats going on. Basically I have two DropDownLists with one doing an SQL search based off the previous's value, which requires to update it every time it changes. This is my code: ``` protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { //Ship Model String str2 = "SELECT DISTINCT [Ship Model] FROM ShipMatrix WHERE ([Ship Make]='@ShipMake')"; SqlCommand qry2 = new SqlCommand(str2, Xebon); qry2.Parameters.Add("ShipMake", SqlDbType.VarChar).Value = DropDownList1.Text; Connection.Open(); qry2.ExecuteNonQuery(); SqlDataAdapter sda2 = new SqlDataAdapter(); sda2.SelectCommand = qry2; DataTable ds2 = new DataTable(); sda2.Fill(ds2); DropDownList2.DataSource = ds2; DropDownList2.DataTextField = "Ship Model"; DropDownList2.DataValueField = "Ship Model"; DropDownList2.DataBind(); Connection.Close(); } ``` Unfortunately it is not updating and the drop down remains about 2-3 characters long and has no values / texts.<issue_comment>username_1: After some research, calming down and thinking, I realized that Docker-in-Docker is not **really** so much "-in-", as it is rather "Docker-next-to-Docker". The trick to make a container able to run another container is sharing `/var/run/docker.sock` through a volume: `-v /var/run/docker.sock:/var/run/docker.sock` And then the `docker` client in the container actually calls Docker on the host. The volume source path (left of `:`) does not refer to the middle container, but to the host filesystem! After realizing that, the fix is to make the paths to the Jenkins `workspace` directory the same in the host filesystem and the Jenkins (middle) container: ``` docker run -d --network=host \ ... -v /var/jenkins_home:/var/jenkins_home ``` And voilá! It works. (I created a symlink instead of moving it, seems to work too.) It is a bit complicated if you're looking at colleague's Mac, because Docker is implemented a bit differently there - it is running in an Alpine Linux based VM but pretending not to. (Not 100 % sure about that.) On Windows, I read that the paths have another layer of abstraction - mapping from `C:/somewhere/...` to a Linux-like path. I hope I'll save someone hours of figuring out :) Upvotes: 6 [selected_answer]<issue_comment>username_2: A better approach is to use [Jenkins Docker plugin](https://wiki.jenkins.io/display/JENKINS/Docker+Plugin) and let it do all the mountings for you and just add `-v /var/run/docker.sock:/var/run/docker.sock` in its `inside` function arguments. E.g. ``` docker.build("bb/ci-jenkins") docker.image("bb/ci-jenkins").inside('-v /var/run/docker.sock:/var/run/docker.sock') { ... } ``` Upvotes: 2 <issue_comment>username_3: Alternative Solution with Docker cp =================================== I was facing the same problem of mounting volumes from a Build that runs in a Docker Container running in a Jenkins server in Kubernetes. As we use `docker-in-docker`, `dind`, I couldn't mount the volume in either ways proposed here. I'm still not sure what the reason is, but I found an alternative way: use `docker cp` to copy the build artifacts. [![enter image description here](https://i.stack.imgur.com/4euQN.png)](https://i.stack.imgur.com/4euQN.png) Multi-stage Docker Image for Tests ================================== I'm using the following Dockerfile stage for Unit + Integration tests. ``` # # Build stage to for building the Jar # FROM maven:3.2.5-jdk-8 as builder MAINTAINER <EMAIL> # Only copy the necessary to pull only the dependencies from registry ADD ./pom.xml /opt/build/pom.xml # As some entries in pom.xml refers to the settings, let's keep it same ADD ./settings.xml /opt/build/settings.xml WORKDIR /opt/build/ # Prepare by downloading dependencies RUN mvn -s settings.xml -B -e -C -T 1C org.apache.maven.plugins:maven-dependency-plugin:3.0.2:go-offline # Run the full packaging after copying the source ADD ./src /opt/build/src RUN mvn -s settings.xml install -P embedded -Dmaven.test.skip=true -B -e -o -T 1C verify # Building only this stage can be done with the --target builder switch # 1. Build: docker build -t config-builder --target builder . # When running this first stage image, just verify the unit tests # Overriden them by removing the "!" for integration tests # 2. docker run --rm -ti config-builder mvn -s settings.xml -Dtest="*IT,*IntegrationTest" test CMD mvn -s settings.xml -Dtest="!*IT,!*IntegrationTest" -P jacoco test ``` Jenkins Pipeline For tests ========================== * My Jenkins pipeline has a stage for running parallel tests (Unit + Integration). * What I do is to build the Test Image in a stage, and run the tests in parallel. * I use `docker cp` to copy the build artifacts from inside the test docker container that can be started after running the tests in a named container. + Alternatively, you can use Jenkins stash to carry the test results to a `Post` stage At this point, I solved the problem with a `docker run --name test:SHA` and then I use `docker start test:SHA` and then `docker cp test:SHA:/path .`, where `.` is the current workspace directory, which is similar to what we need with a docker volume mounted to the current directory. ``` stage('Build Test Image') { steps { script { currentBuild.displayName = "Test Image" currentBuild.description = "Building the docker image for running the test cases" } echo "Building docker image for tests from build stage ${env.GIT_COMMIT}" sh "docker build -t tests:${env.GIT_COMMIT} -f ${paas.build.docker.dockerfile.runtime} --target builder ." } } stage('Tests Execution') { parallel { stage('Execute Unit Tests') { steps { script { currentBuild.displayName = "Unit Tests" currentBuild.description = "Running the unit tests cases" } sh "docker run --name tests-${env.GIT_COMMIT} tests:${env.GIT_COMMIT}" sh "docker start tests-${env.GIT_COMMIT}" sh "docker cp tests-${env.GIT_COMMIT}:/opt/build/target ." // https://jenkins.io/doc/book/pipeline/jenkinsfile/#advanced-scripted-pipeline#using-multiple-agents stash includes: '**/target/*', name: 'build' } } stage('Execute Integration Tests') { when { expression { paas.integrationEnabled == true } } steps { script { currentBuild.displayName = "Integration Tests" currentBuild.description = "Running the Integration tests cases" } sh "docker run --rm tests:${env.GIT_COMMIT} mvn -s settings.xml -Dtest=\"*IT,*IntegrationTest\" -P jacoco test" } } } } ``` Upvotes: 2
2018/03/16
1,733
5,885
<issue_start>username_0: Here is the code example: ``` namespace A { int k; } void k(int,int){/*dosomething*/} int main() { using namespace A; k(1,1);//ooop!k is ambiguous! } ``` What happened? I thought it should not be ambiguous since they are different types. Why is it ambiguous? With `int k` it is not possible to do `k(1,1)`. So it has nothing to do with what the name actually is?Even if a name that is not a function type will also cause ambiguity when we use `k(1,1)` ,which is wrong in grammar because `int k` is not function?<issue_comment>username_1: Lookup of the name `k` is ambiguous because there are two matching declarations visible, `::k` and `::A::k` . The exact rule can be found in the C++ Standard (N4659 [basic.lookup]/1): > > Name lookup associates the use of a name with a set of declarations of that name. The declarations found by name lookup shall either all declare the same entity or shall all declare functions; in the latter case, the declarations are said to form a set of overloaded functions. > > > --- Looking up an unqualified name that is used for a function call has two stages: 1. Unqualified lookup of the name 2. Argument-dependent lookup of the name. **The unqualified name lookup rules, even when looking up a name that is being used for a function call, find any declaration of that name.** (The rule is NOT that it only searches for function declarations of that name). This stage finds both `::k` and `::A::k` regardless of whether those are functions, `int`s, or whatever. The argument-dependent lookup does have a rule that only function declarations are found for that part of the lookup. But that is not relevant to this code. --- The relevant behaviour of the `using` directive is covered by [basic.lookup.unqual]/2 (edited by me to just show the parts relevant to this question): > > For the purpose of the unqualified name lookup rules, the declarations from the namespace nominated by the using-directive are considered members of that enclosing namespace. > > > This clarifies that `using namespace A;` does not actually introduce the members of `A` into the scope of `main()`; but it means that when looking up a name in the global namespace (because that is the innermost enclosing namespace of the site of the using declaration), the names from `A` will also be found there. Upvotes: 4 [selected_answer]<issue_comment>username_2: There are three ways to resolve the ambiguity: 1st: ``` int main() { A::k = 5; ::k( 1, 1 ); } ``` 2nd: ``` int main() { using namespace A; A::k = 5; ::k(1, 1); } ``` 3rd: ``` namespace A { int k; } namespace B { void k( int, int ) { /* do something */ } } int main() { using namespace A or B but not both! if A then k = 5; okay && k(1,1); error if B then k(1, 1); okay && k = 5; error if both again ambiguous unless A::k = 5; || B::k(1,1); return 0; } ``` Due to the nature of ambiguity it doesn't truly pay to use `using namespace A`. And this is why it is considered bad practice to have `using namespace std;` either in the global scope or directly in the main function. It is okay to use it in a function or a member function of a class/struct as long as you don't conflict with any other library. I ran this in my IDE visual studio 2017 CE and here is the compiler error: ``` 1>------ Build started: Project: ChemLab, Configuration: Debug Win32 ------ 1>main.cpp 1>c:\...\visual studio 2017\projects\chemlab\chemlab\main.cpp(17): error C2872: 'k': ambiguous symbol 1>c:\...\visual studio 2017\projects\chemlab\chemlab\main.cpp(8): note: could be 'void k(int,int)' 1>c:\...\visual studio 2017\projects\chemlab\chemlab\main.cpp(6): note: or 'int A::k' 1>Done building project "ChemLab.vcxproj" -- FAILED. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== ``` When you use the `using namespace directive` it will take everything that is in that namespace and make it visible to main. So now in main you have both the `namespace A` and the `global namespace` visible within main. Since you have both visible you now have 2 identifiers or symbols in the look up table named `k`. And when you call `k(1, 1)` it doesn't know which one you intended to choose. This is no different than doing this: **main.cpp** ``` #include class string { public: char\* \_chars; }; int main() { using namespace std; string myString; // error ambiguous did you mean ::string or std::string? return 0; } ``` This might provide you with some more insight: When the `using directive` is being used, don't think of the `variable k` and the `function k` as being `declared` in the `same scope`. They were previously declared in their own scope. The variable `k` is in `::A::k` and the function `void k(int,int){}` is in `::k(int,int){}`. In the main function when you apply the `using namespace A;` what happens here it takes `every symbol` `after` `A::` and it kind of shifts it as if it were in the `global` `::` `scope` for visibility. Now the compiler has to make a choice on the available symbols and sees I have a `k` and a `k`. Did you mean `int k(){}` or `void k(int,int){}`... Upvotes: 2 <issue_comment>username_3: The ambiguity comes from the name. There is no way to overload a variable like you would a function/method, so there is a "clash" in the names. In order to get the "k" that you want, you need to specify the namespace. ``` namespace A { int k; } void k(int, int) {/*dosomething*/ } int main() { using namespace A; ::k(1, 1); // uses the global namespace A::k = 5; // uses the namespace A } ``` Or, to take the namespace out of the equation: ``` void k(int, int) {/*dosomething*/ } void k(int, int, float) {} int main() { int k; // all of these are now ambiguous k(1, 1); k(1, 2, 0.4); k = 5; } ``` Upvotes: -1
2018/03/16
295
851
<issue_start>username_0: By using numpy, I could index an array as below ``` x[mask==1] ``` Assuming `x` and `mask` are both numpy array and `mask` contains only `1` and `0`. Now I have both `x` and `mask` as `Tensor`s and want to mimic above behavior. What should I do?<issue_comment>username_1: Use `boolean_mask`. *Example*: ``` x = tf.constant([[1,2],[3,4]]) mask = tf.constant([[1,0],[0,1]]) tf.boolean_mask(x, tf.equal(mask, 1)).eval() # array([1, 4]) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: This will give you a bolean mask ``` import tensorflow as tf a = tf.Variable( [1,2,3,1] ) comparison = tf.equal( a, tf.constant( 1 ) ) start_op = tf.global_variables_initializer() with tf.Session() as session: session.run(tart_op) print(session.run(comparison)) [ True False False True] ``` Upvotes: 1
2018/03/16
370
1,030
<issue_start>username_0: I have the following code: ``` html = html + '![](img/loaded.gif)'; ``` which outputs ``` ![](img/loaded.gif) ``` If I move the variable over like this: ``` html = html + '' + arr[i].loc + '![](img/loaded.gif) ``` I get this: ``` 304-1477 West Pender Street, canada![](img/loaded.gif) ``` Why does the output change based on where the variable is? Why is > > ""= > > > Added to every space on the first output?<issue_comment>username_1: Use `boolean_mask`. *Example*: ``` x = tf.constant([[1,2],[3,4]]) mask = tf.constant([[1,0],[0,1]]) tf.boolean_mask(x, tf.equal(mask, 1)).eval() # array([1, 4]) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: This will give you a bolean mask ``` import tensorflow as tf a = tf.Variable( [1,2,3,1] ) comparison = tf.equal( a, tf.constant( 1 ) ) start_op = tf.global_variables_initializer() with tf.Session() as session: session.run(tart_op) print(session.run(comparison)) [ True False False True] ``` Upvotes: 1
2018/03/16
384
1,274
<issue_start>username_0: I have a custom UIView that consists of 9 equally-sized subviews. It essentially looks like a tic-tac-toe board. I've added a UIPanGestureRecognizer to this custom view. Each time the user pans over one of the subviews, I want to take an action. For example, the user could pan over the first 3 (of the 9) subviews in one gesture, and in this case I'd want to take 3 actions. I could try to do some fancy math and figure out the frame of each subview, then figure out when the gesture crosses from one subview to another. However, I feel like there should be a more elegant way to get a callback when a gesture touches a new UIView. Does a functionality like this exist?<issue_comment>username_1: Use `boolean_mask`. *Example*: ``` x = tf.constant([[1,2],[3,4]]) mask = tf.constant([[1,0],[0,1]]) tf.boolean_mask(x, tf.equal(mask, 1)).eval() # array([1, 4]) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: This will give you a bolean mask ``` import tensorflow as tf a = tf.Variable( [1,2,3,1] ) comparison = tf.equal( a, tf.constant( 1 ) ) start_op = tf.global_variables_initializer() with tf.Session() as session: session.run(tart_op) print(session.run(comparison)) [ True False False True] ``` Upvotes: 1
2018/03/16
1,940
6,314
<issue_start>username_0: I am trying to achieve this sample output from a small Perl project like this ``` content1 relatedcontent1 relatedcontent2 relatedcontent2 content2 relatedcontent1 relatedcontent2 ``` here is my code ``` #!C:/Perl64/bin/perl.exe use strict; use warnings; use v5.10; # for say() function use DBI; use HTML::Table; # MySQL database configurations my $dsn = "DBI:mysql:naxum"; my $username = "root"; my $password = ''; print "Content-Type:text/html\r\n\r\n"; # connect to MySQL database my %attr = ( PrintError=>0, # turn off error reporting via warn() RaiseError=>1 # report error via die() ); my $dbh = DBI->connect($dsn,$username,$password,\%attr); # query data from the sponsor table query_sponsor($dbh); query_person_by_target($dbh); sub query_sponsor{ # query from the table my ($dbh) = @_; my $sql = "SELECT name,id FROM sponsor"; my $sth = $dbh->prepare($sql); # execute the query $sth->execute(); print " \n"; print "\n"; print "|\n"; print " Id |\n"; print " Name |\n"; print " \n"; print "\n"; print "\n"; while(my @row = $sth->fetchrow\_array()){ print "|\n"; print " \n"; print $row['1']; sub query\_person\_by\_target{ my ($dbhPerson) = @\_; my $sqlPerson = "SELECT username, firstname FROM person WHERE sponsor\_id = ?"; my $sthPerson = $dbhPerson->prepare($sqlPerson); $sthPerson->execute($row['1']) or die "execution failed: $dbhPerson->errstr()"; while ( my @rowPerson = $sthPerson->fetchrow\_array()){ print "$rowPerson['0']\n"; } $sth->finish(); } print " |\n"; print " $row['0'] |\n"; print " \n"; } $sth->finish(); print "\n"; print " \n"; } $dbh->disconnect(); ``` However, I can't get the output what I am trying to achieve. Here is the result ``` content1 content2 content3 ..... relatedcontent1 ``` It will just print one related content outside contents. Every content and its own at least 3 relatedcontent each.<issue_comment>username_1: You have declared the two subroutines and you are calling one after one so it is executing like that for example consider the following one ``` sub1(); sub2(); sub sub1() { for(0..5) { print "hello\n"; sub sub2() { print "hi\n"; } } } #output hello hello hello hello hello hello hi ``` So you should remove the child `query_person_by_target` subroutine or call the child subroutine inside the parent subroutine `query_sponsor` and declare the child subroutine outside of the sub and loop, like below (not tested) ``` query_sponsor($dbh); sub query_sponsor { # query from the table my ($dbh) = @_; my $sql = "SELECT name,id FROM sponsor"; my $sth = $dbh->prepare($sql); # execute the query $sth->execute(); print " \n"; print "\n"; print "|\n"; print " Id |\n"; print " Name |\n"; print " \n"; print "\n"; print "\n"; while(my @row = $sth->fetchrow\_array()) { print "|\n"; print " \n"; print $row['1']; query\_person\_by\_target($dbh); print " |\n"; print " $row['0'] |\n"; print " \n"; } $sth->finish(); print "\n"; print " \n"; } sub query_person_by_target{ my ($dbhPerson) = @_; my $sqlPerson = "SELECT username, firstname FROM person WHERE sponsor_id = ?"; my $sthPerson = $dbhPerson->prepare($sqlPerson); $sthPerson->execute($row['1']) or die "execution failed: $dbhPerson->errstr()"; while ( my @rowPerson = $sthPerson->fetchrow_array()){ print "$rowPerson['0'] \n"; } $sth->finish(); } $dbh->disconnect(); ``` Upvotes: -1 <issue_comment>username_2: You define your subroutines in the middle of other code in your program. This makes me think you expect them to be executed as they are defined, but that's not the case - they are executed as you call them. And you call them like this: ``` query_sponsor($dbh); query_person_by_target($dbh); ``` So it should come as no surprise that you get all of the output from `query_sponsor()` followed by all of the output from `query_person_by_name()`. A far better approach would be to call `query_person_by_target()` from within `query_sponsor()`. I'd also split this into two phases - phase one to extract the data into a data structure and phase two to display that data. As I don't have your database, this code is untested. ``` #!/usr/bin/perl use strict; use warnings; use feature 'state'; # for state variables use feature 'say'; use CGI 'header'; sub get_dbh { # MySQL database configurations my $dsn = "DBI:mysql:naxum"; my $username = "root"; my $password = ''; # connect to MySQL database my %attr = ( PrintError=>0, # turn off error reporting via warn() RaiseError=>1, # report error via die() ); return DBI->connect($dsn, $username, $password, \%attr); } sub query_sponsor { state $dbh = get_dbh(); my $sql = 'select name, id from sponsor'; my $sth = $dbh->prepare($sql); $sth->execute; my @sponsors; while (my @row = $dbh->fetchrow_array) { push @sponsors, { name => $row[0], id => $row[1], people => get_people_for_sponsor($row[1]), }; } return @sponsors; } sub get_people_for_sponsor { my ($sponsor_id) = @_; state $dbh = get_dbh; my $sql = 'select username, firstname from person where sponsor_id = ?'; my $sth = $dbh->prepare; $sth->execute($sponsor_id); my @people; while (my @row = $sth->fetchrow_array) { push @people, { username => $row[0], firstname => $row[1], }; } return \@people; } my @sponsors = query_sponsor(); # Now you have all of your data in @sponsors. You simply need # to walk that array and use the data to build the output you # want. My example is plain text - it shouldn't be too hard to # convert it to HTML. print header('text/plain'); for my $s (@sponsors) { say "$s->{id}: $s->{name}"; for my $p (@{$s->{people}}) { say "* $p->{firstname} / $p->{username}"; } } ``` I'd also recommend that you look at using something like the Template Toolkit to produce your output. Putting raw HTML into your Perl program is a terrible idea - it is guaranteed to turn into an unmaintainable mess :-) Upvotes: 0
2018/03/16
1,855
5,904
<issue_start>username_0: With my select below, if blank string is passed in I get the following error: Null or empty full-text predicate in my DBAdapter when fetching rows from the database. If I provide a value, such as Well, I do not get results when I should as Well is in the r.[Desc] column. If I pass in Well One, I get: Syntax error near 'one' in the full-text search condition 'Well one'. If I pass in One, I get nothing. I've read similar questions here and have not seen a pattern where the value passed in can be nothing, the beginning of the column data, a word in the middle of the column data or more than one word in any order of the column data. I thought Contains returns the row if the column contains the value or part of the value passed in. What am I doing wrong? ``` if @Drawing = '' set @Drawing = null if @ItemName = '' set @ItemName = null if @CF3 = '' set @CF3 = null if @Desc = '' set @Desc = null if @Design = '' set @Design = null if @MaxPSI = 0 set @MaxPSI = null Select distinct ,r.[DRAWING] ,r.[DESC] ,r.[OP_PSI] ,r.[MAX_PSI] ,r.[MAX_TEMP] ,r.[Insulated] ,r.[DESIGN] From Ref r inner join Eng e on e.[DRAWING] = r.[DRAWING] where r.SurveyNumber = @SurveyNumber And (rtrim(@Drawing) is NUll or rtrim(r.DRAWING) like rtrim(@Drawing) + '%') And (rtrim(@Design) is NUll or rtrim(r.DESIGN) like rtrim(@Design) + '%') And (rtrim(@MaxPSI) is NUll or rtrim(r.MAX_PSI) like rtrim(@MaxPSI) + '%') And (rtrim(@CF3) is NUll or rtrim(e.CF3) like rtrim(@CF3) + '%') And (rtrim(@ItemName) is NUll or rtrim(e.ITEM_NAME) like rtrim(@ItemName) + '%') AND ((@Desc = '""') OR CONTAINS( (r.[Desc]), @Desc)) ```<issue_comment>username_1: You have declared the two subroutines and you are calling one after one so it is executing like that for example consider the following one ``` sub1(); sub2(); sub sub1() { for(0..5) { print "hello\n"; sub sub2() { print "hi\n"; } } } #output hello hello hello hello hello hello hi ``` So you should remove the child `query_person_by_target` subroutine or call the child subroutine inside the parent subroutine `query_sponsor` and declare the child subroutine outside of the sub and loop, like below (not tested) ``` query_sponsor($dbh); sub query_sponsor { # query from the table my ($dbh) = @_; my $sql = "SELECT name,id FROM sponsor"; my $sth = $dbh->prepare($sql); # execute the query $sth->execute(); print " \n"; print "\n"; print "|\n"; print " Id |\n"; print " Name |\n"; print " \n"; print "\n"; print "\n"; while(my @row = $sth->fetchrow\_array()) { print "|\n"; print " \n"; print $row['1']; query\_person\_by\_target($dbh); print " |\n"; print " $row['0'] |\n"; print " \n"; } $sth->finish(); print "\n"; print " \n"; } sub query_person_by_target{ my ($dbhPerson) = @_; my $sqlPerson = "SELECT username, firstname FROM person WHERE sponsor_id = ?"; my $sthPerson = $dbhPerson->prepare($sqlPerson); $sthPerson->execute($row['1']) or die "execution failed: $dbhPerson->errstr()"; while ( my @rowPerson = $sthPerson->fetchrow_array()){ print "$rowPerson['0'] \n"; } $sth->finish(); } $dbh->disconnect(); ``` Upvotes: -1 <issue_comment>username_2: You define your subroutines in the middle of other code in your program. This makes me think you expect them to be executed as they are defined, but that's not the case - they are executed as you call them. And you call them like this: ``` query_sponsor($dbh); query_person_by_target($dbh); ``` So it should come as no surprise that you get all of the output from `query_sponsor()` followed by all of the output from `query_person_by_name()`. A far better approach would be to call `query_person_by_target()` from within `query_sponsor()`. I'd also split this into two phases - phase one to extract the data into a data structure and phase two to display that data. As I don't have your database, this code is untested. ``` #!/usr/bin/perl use strict; use warnings; use feature 'state'; # for state variables use feature 'say'; use CGI 'header'; sub get_dbh { # MySQL database configurations my $dsn = "DBI:mysql:naxum"; my $username = "root"; my $password = ''; # connect to MySQL database my %attr = ( PrintError=>0, # turn off error reporting via warn() RaiseError=>1, # report error via die() ); return DBI->connect($dsn, $username, $password, \%attr); } sub query_sponsor { state $dbh = get_dbh(); my $sql = 'select name, id from sponsor'; my $sth = $dbh->prepare($sql); $sth->execute; my @sponsors; while (my @row = $dbh->fetchrow_array) { push @sponsors, { name => $row[0], id => $row[1], people => get_people_for_sponsor($row[1]), }; } return @sponsors; } sub get_people_for_sponsor { my ($sponsor_id) = @_; state $dbh = get_dbh; my $sql = 'select username, firstname from person where sponsor_id = ?'; my $sth = $dbh->prepare; $sth->execute($sponsor_id); my @people; while (my @row = $sth->fetchrow_array) { push @people, { username => $row[0], firstname => $row[1], }; } return \@people; } my @sponsors = query_sponsor(); # Now you have all of your data in @sponsors. You simply need # to walk that array and use the data to build the output you # want. My example is plain text - it shouldn't be too hard to # convert it to HTML. print header('text/plain'); for my $s (@sponsors) { say "$s->{id}: $s->{name}"; for my $p (@{$s->{people}}) { say "* $p->{firstname} / $p->{username}"; } } ``` I'd also recommend that you look at using something like the Template Toolkit to produce your output. Putting raw HTML into your Perl program is a terrible idea - it is guaranteed to turn into an unmaintainable mess :-) Upvotes: 0
2018/03/16
1,554
5,021
<issue_start>username_0: I have a multi-level XML file that needs to parse with python, I have xml or lxml. How do I parse? I could not find any useful solution.Please help me, thanks a lot! Ideally, I want to parse the XML file and convert to Python DataFrame. This for loop does not work. ``` for child in root: for element in child: for element in child: print(element.tag, element.attrib) ``` This is part of the result that I printed out with pretty print. ``` Amagansett NY 11930 4.12 2.13 No For Rent 120000 http://www.co.com/listing.aspx? Region=LI3&ListingID=122 122 2011-06-10 N Other Rental Registration #: the master suite has a lavish bath and its own terrace with small ocean views.. 5 4 4 0 5775 0.8 ```<issue_comment>username_1: You have declared the two subroutines and you are calling one after one so it is executing like that for example consider the following one ``` sub1(); sub2(); sub sub1() { for(0..5) { print "hello\n"; sub sub2() { print "hi\n"; } } } #output hello hello hello hello hello hello hi ``` So you should remove the child `query_person_by_target` subroutine or call the child subroutine inside the parent subroutine `query_sponsor` and declare the child subroutine outside of the sub and loop, like below (not tested) ``` query_sponsor($dbh); sub query_sponsor { # query from the table my ($dbh) = @_; my $sql = "SELECT name,id FROM sponsor"; my $sth = $dbh->prepare($sql); # execute the query $sth->execute(); print " \n"; print "\n"; print "|\n"; print " Id |\n"; print " Name |\n"; print " \n"; print "\n"; print "\n"; while(my @row = $sth->fetchrow\_array()) { print "|\n"; print " \n"; print $row['1']; query\_person\_by\_target($dbh); print " |\n"; print " $row['0'] |\n"; print " \n"; } $sth->finish(); print "\n"; print " \n"; } sub query_person_by_target{ my ($dbhPerson) = @_; my $sqlPerson = "SELECT username, firstname FROM person WHERE sponsor_id = ?"; my $sthPerson = $dbhPerson->prepare($sqlPerson); $sthPerson->execute($row['1']) or die "execution failed: $dbhPerson->errstr()"; while ( my @rowPerson = $sthPerson->fetchrow_array()){ print "$rowPerson['0'] \n"; } $sth->finish(); } $dbh->disconnect(); ``` Upvotes: -1 <issue_comment>username_2: You define your subroutines in the middle of other code in your program. This makes me think you expect them to be executed as they are defined, but that's not the case - they are executed as you call them. And you call them like this: ``` query_sponsor($dbh); query_person_by_target($dbh); ``` So it should come as no surprise that you get all of the output from `query_sponsor()` followed by all of the output from `query_person_by_name()`. A far better approach would be to call `query_person_by_target()` from within `query_sponsor()`. I'd also split this into two phases - phase one to extract the data into a data structure and phase two to display that data. As I don't have your database, this code is untested. ``` #!/usr/bin/perl use strict; use warnings; use feature 'state'; # for state variables use feature 'say'; use CGI 'header'; sub get_dbh { # MySQL database configurations my $dsn = "DBI:mysql:naxum"; my $username = "root"; my $password = ''; # connect to MySQL database my %attr = ( PrintError=>0, # turn off error reporting via warn() RaiseError=>1, # report error via die() ); return DBI->connect($dsn, $username, $password, \%attr); } sub query_sponsor { state $dbh = get_dbh(); my $sql = 'select name, id from sponsor'; my $sth = $dbh->prepare($sql); $sth->execute; my @sponsors; while (my @row = $dbh->fetchrow_array) { push @sponsors, { name => $row[0], id => $row[1], people => get_people_for_sponsor($row[1]), }; } return @sponsors; } sub get_people_for_sponsor { my ($sponsor_id) = @_; state $dbh = get_dbh; my $sql = 'select username, firstname from person where sponsor_id = ?'; my $sth = $dbh->prepare; $sth->execute($sponsor_id); my @people; while (my @row = $sth->fetchrow_array) { push @people, { username => $row[0], firstname => $row[1], }; } return \@people; } my @sponsors = query_sponsor(); # Now you have all of your data in @sponsors. You simply need # to walk that array and use the data to build the output you # want. My example is plain text - it shouldn't be too hard to # convert it to HTML. print header('text/plain'); for my $s (@sponsors) { say "$s->{id}: $s->{name}"; for my $p (@{$s->{people}}) { say "* $p->{firstname} / $p->{username}"; } } ``` I'd also recommend that you look at using something like the Template Toolkit to produce your output. Putting raw HTML into your Perl program is a terrible idea - it is guaranteed to turn into an unmaintainable mess :-) Upvotes: 0
2018/03/16
1,377
4,491
<issue_start>username_0: Hey guys I've been trying to get an array with the past 30 days in laravel. Trying to use Carbon to get the days now and want to get count it back 30 days any idea how i can get that done? Example 19,18,17,16,15,14 etc.<issue_comment>username_1: You have declared the two subroutines and you are calling one after one so it is executing like that for example consider the following one ``` sub1(); sub2(); sub sub1() { for(0..5) { print "hello\n"; sub sub2() { print "hi\n"; } } } #output hello hello hello hello hello hello hi ``` So you should remove the child `query_person_by_target` subroutine or call the child subroutine inside the parent subroutine `query_sponsor` and declare the child subroutine outside of the sub and loop, like below (not tested) ``` query_sponsor($dbh); sub query_sponsor { # query from the table my ($dbh) = @_; my $sql = "SELECT name,id FROM sponsor"; my $sth = $dbh->prepare($sql); # execute the query $sth->execute(); print " \n"; print "\n"; print "|\n"; print " Id |\n"; print " Name |\n"; print " \n"; print "\n"; print "\n"; while(my @row = $sth->fetchrow\_array()) { print "|\n"; print " \n"; print $row['1']; query\_person\_by\_target($dbh); print " |\n"; print " $row['0'] |\n"; print " \n"; } $sth->finish(); print "\n"; print " \n"; } sub query_person_by_target{ my ($dbhPerson) = @_; my $sqlPerson = "SELECT username, firstname FROM person WHERE sponsor_id = ?"; my $sthPerson = $dbhPerson->prepare($sqlPerson); $sthPerson->execute($row['1']) or die "execution failed: $dbhPerson->errstr()"; while ( my @rowPerson = $sthPerson->fetchrow_array()){ print "$rowPerson['0'] \n"; } $sth->finish(); } $dbh->disconnect(); ``` Upvotes: -1 <issue_comment>username_2: You define your subroutines in the middle of other code in your program. This makes me think you expect them to be executed as they are defined, but that's not the case - they are executed as you call them. And you call them like this: ``` query_sponsor($dbh); query_person_by_target($dbh); ``` So it should come as no surprise that you get all of the output from `query_sponsor()` followed by all of the output from `query_person_by_name()`. A far better approach would be to call `query_person_by_target()` from within `query_sponsor()`. I'd also split this into two phases - phase one to extract the data into a data structure and phase two to display that data. As I don't have your database, this code is untested. ``` #!/usr/bin/perl use strict; use warnings; use feature 'state'; # for state variables use feature 'say'; use CGI 'header'; sub get_dbh { # MySQL database configurations my $dsn = "DBI:mysql:naxum"; my $username = "root"; my $password = ''; # connect to MySQL database my %attr = ( PrintError=>0, # turn off error reporting via warn() RaiseError=>1, # report error via die() ); return DBI->connect($dsn, $username, $password, \%attr); } sub query_sponsor { state $dbh = get_dbh(); my $sql = 'select name, id from sponsor'; my $sth = $dbh->prepare($sql); $sth->execute; my @sponsors; while (my @row = $dbh->fetchrow_array) { push @sponsors, { name => $row[0], id => $row[1], people => get_people_for_sponsor($row[1]), }; } return @sponsors; } sub get_people_for_sponsor { my ($sponsor_id) = @_; state $dbh = get_dbh; my $sql = 'select username, firstname from person where sponsor_id = ?'; my $sth = $dbh->prepare; $sth->execute($sponsor_id); my @people; while (my @row = $sth->fetchrow_array) { push @people, { username => $row[0], firstname => $row[1], }; } return \@people; } my @sponsors = query_sponsor(); # Now you have all of your data in @sponsors. You simply need # to walk that array and use the data to build the output you # want. My example is plain text - it shouldn't be too hard to # convert it to HTML. print header('text/plain'); for my $s (@sponsors) { say "$s->{id}: $s->{name}"; for my $p (@{$s->{people}}) { say "* $p->{firstname} / $p->{username}"; } } ``` I'd also recommend that you look at using something like the Template Toolkit to produce your output. Putting raw HTML into your Perl program is a terrible idea - it is guaranteed to turn into an unmaintainable mess :-) Upvotes: 0
2018/03/16
321
1,275
<issue_start>username_0: Whenever I boot up emacs the packages that I installed on the previous session disapear and I have to reinstall them. I run this command to allow multiple terminals, if I close emacs and reopen it, this package and all others will have to be reinstalled. ``` package-install multi-term ``` What am I doing wrong?<issue_comment>username_1: You need to call `package-initialize`. You will probably want to add it to your init file and read its documentation about other applicable settings, eg. `M-x``describe-function` `package-initialize` Upvotes: 1 <issue_comment>username_2: It turns out because I was using Spacemacs for emacs, the dotspacemacs file that it uses for all its configurations and packages overwrites the emacs.d file. This causes the packages installed using: ``` package-install ``` to become orphaned and they get removed on reboot. To solve this I had to manually add the packages to the dotspacemacs-additional-packages function. This tells spacemacs on bootup to install/load those packages. When ever you add a new package add it here rather than using the package-install command. [![enter image description here](https://i.stack.imgur.com/qh3Ng.png)](https://i.stack.imgur.com/qh3Ng.png) Upvotes: 4 [selected_answer]
2018/03/16
487
1,905
<issue_start>username_0: I am refactoring a code base, which is something like a house. A house has walls, windows, doors, etc. Currently, everything is put inside house class, such as ``` class House { public: void setDoorColor(int color); void setDoorWidth(int width); void setWallColor(int color); void setWallWidth(int width); ... private: int doorColor; int doorWidth; int wallColor; int wallHeight; ... } ``` So, it is quite messy. What I can think about is using something like composition, for example, ``` class House { private: Wall wall; Window window; ... } ``` Where to put public APIs? In each component, say windows relevant APIs inside Window? The thing is `House` is passed to many other functions as an argument, such `void foo(const House& house, int, double)`. How to use `House` to access `door` and `wall`? such as `house.getDoor().getDoorColor()`? Any good ideas?<issue_comment>username_1: You need to call `package-initialize`. You will probably want to add it to your init file and read its documentation about other applicable settings, eg. `M-x``describe-function` `package-initialize` Upvotes: 1 <issue_comment>username_2: It turns out because I was using Spacemacs for emacs, the dotspacemacs file that it uses for all its configurations and packages overwrites the emacs.d file. This causes the packages installed using: ``` package-install ``` to become orphaned and they get removed on reboot. To solve this I had to manually add the packages to the dotspacemacs-additional-packages function. This tells spacemacs on bootup to install/load those packages. When ever you add a new package add it here rather than using the package-install command. [![enter image description here](https://i.stack.imgur.com/qh3Ng.png)](https://i.stack.imgur.com/qh3Ng.png) Upvotes: 4 [selected_answer]
2018/03/16
602
2,198
<issue_start>username_0: I am trying to setup kafka for messaging service. I am using kafka\_2.9.2-0.8.1.1 version, I have started zookeeper, kafka and created a topic with no partition and replication factor. Once I start my consumer, I get the following error ``` ./kafka-console-consumer.sh --zookeeper localhost:9092 --topic test --from-beginning Exception in thread "main" org.I0Itec.zkclient.exception.ZkTimeoutException: Unable to connect to zookeeper server within timeout: 6000 at org.I0Itec.zkclient.ZkClient.connect(ZkClient.java:880) at org.I0Itec.zkclient.ZkClient.(ZkClient.java:98) at org.I0Itec.zkclient.ZkClient.(ZkClient.java:84) at kafka.consumer.ZookeeperConsumerConnector.connectZk(ZookeeperConsumerConnector.scala:156) at kafka.consumer.ZookeeperConsumerConnector.(ZookeeperConsumerConnector.scala:114) at kafka.consumer.ZookeeperConsumerConnector.(ZookeeperConsumerConnector.scala:128) at kafka.consumer.Consumer$.create(ConsumerConnector.scala:89) at kafka.consumer.console Consumer$.main(ConsoleConsumer.scala:178) at kafka.consumer.ConsoleConsumer.main(ConsoleConsumer.scala) ``` My zookeeper is running, I have ensured that by netstat command!! Not sure what is going wrong here. Any inputs on this will be helpful<issue_comment>username_1: You need to call `package-initialize`. You will probably want to add it to your init file and read its documentation about other applicable settings, eg. `M-x``describe-function` `package-initialize` Upvotes: 1 <issue_comment>username_2: It turns out because I was using Spacemacs for emacs, the dotspacemacs file that it uses for all its configurations and packages overwrites the emacs.d file. This causes the packages installed using: ``` package-install ``` to become orphaned and they get removed on reboot. To solve this I had to manually add the packages to the dotspacemacs-additional-packages function. This tells spacemacs on bootup to install/load those packages. When ever you add a new package add it here rather than using the package-install command. [![enter image description here](https://i.stack.imgur.com/qh3Ng.png)](https://i.stack.imgur.com/qh3Ng.png) Upvotes: 4 [selected_answer]
2018/03/16
2,580
10,722
<issue_start>username_0: I read that a perfectly predicted branch has zero / almost-zero overhead. (For example in an answer on [Effects of branch prediction on performance?](https://stackoverflow.com/questions/289405/effects-of-branch-prediction-on-performance/289860#289860)) I don't quite understand what people mean by this. At least the branch condition has to be evaluated, which can be a simple bool or a function call, that takes time.<issue_comment>username_1: Branch prediction is predicting the OUTCOME of your condition at instruction level, which is the actual result in the C or C++ condition - if that is the result of a million character string comparison, it's probably not particularly useful, because that comparison is going to take a lot of time. If it's the end condition of a the for loop that iterates over the two strings with a million characters each, then it's highly useful, because it happens many times in that loop (assuming the strings are equal). It is NOT free to make a string comparison of two long strings. It is free to guess correctly that the string comparison will continue (until we either find the end of the string or a difference, at which point the branch prediction goes wrong). A "unpredictable" branch will lead to the processor not knowing where the code continues to. Modern CPUs have fairly long pipelines (15-30 steps), so if the pipeline isn't filled with the "right" code, the processor will have to wait for the "right" code to trickle through the pipeline. So to answer the actual queston: When the branch itself is well predicted, the processor has already got the RIGTH instructions in the pipeline, and there is no "pipeline bubble" to walk through the pipeline before we can execute the correct instructions for continuing the program. See below for an analogy. If the prediction is wrong, there will be something other than the right instructions in the pipeline, and the processor has to chew its way through those, throwing them away. Think of it as a car factory, making cars of models A and B, in a production line that first mounts the body onto a chassis, paints it (magic paint, it dries almost instantly), then fits the engine and gearbox, and then puts wheels on it, fits the lights, and finally the glass is fitted, and it's a complete car. Each step takes 20 minutes to perform, and the conveyor belt for the cars will move forward to the next position every 20 minutes [for this exercise, we ignore the fact that the move itself takes time]. You are in charge of the production line, and you have a bunch of A cars on the production line. Suddenly, the big boss says, "we've just got an order for B cars, change to making model B immediately". So, you start feeding B car parts onto the production line. But it will still take quite some time before the next B car comes out at the other end. The way branch prediction works is that it "guesses" whether the code will change direction or go to the next instruction. If it guesses right, it's like guessing when "big boss" comes down to tell you to change between A and B models of cars, so you can have the right car ready to pop off the production line when the boss wants it, rather than having to wait for the whole production line to When it works, it's great, because the expected stuff is ready to be done. If you guess wrong, you've still got to wait for the rest of the production line to run through the current set, and stash those into the "we don't have a customer for these" corner (or in terms of CPU instructions "discard the instruction"). Most modern CPU's also allow for "speculative execution". That means that the processor will start executing instructions BEFORE the condition is actually determined. So the processor will switch from A cars to working on B cars before the boss says so. If at that point, the boss says "no, you should keep working on A cars", you have a bunch of cars to discard, that you already started work on. You don't necessarily have to build all the cars, but you have to move them through the production line, one step every 20 minutes. Upvotes: 2 <issue_comment>username_2: Summary ------- Evaluating a branch condition always takes some *work*, even if perfectly predicted, but because of the internal parallelism in modern CPUs extra *work* doesn't necessary add to the *cost* of a particular instruction sequence. Details ------- I think part of the confusion lies in the mental performance model many people have for the execution of CPU instructions. Yes, every instruction requires some *work*, so that should imply that every instruction has some *cost*, however small, when measured in execution time, right? Well that would be true if the total cost of execution was simply additive in the work for each instruction - you just add together all the *work* and get the final *cost*. Because of the large about of parallelism in modern CPUs it doesn't work like that. Think of it like organizing a birthday party. You may have to buy flour which takes 10 minutes and then bake a cake which takes 60 minutes, and go pick up a special gift which is 30 minutes away. Those timings are all the "work" required for the activity. However, someone can go pick up the gift while the flour is being picked up and the cake is being being baked. You can't bake the cake without the flour, however. So you have two dependency chains: the 70 minute buy flour -> bake cake chain, and the 30 minute pickup gift chain. With unlimited parallelism, only the 70 minute cake related chain contributes to the time at which everything is ready. Picking up the gift 30 minutes of *work* but it ends up *costing* no time (not delaying completion of all the tasks), due to other work that takes longer (aka the critical path) and happens in parallel. More extra tasks can be done in parallel until you run out of people to assign to them. (At that point, execution throughput limits start to increase latency, and this is called a resource conflict. If a resource conflict delays the critical path, rather than one of the shorter dependency chains. CPUs don't know which dependency chain is / will be the critical path, so their scheduling doesn't prioritize it the way smart humans would in this planning analogy.) --- For a less abstract and more practical look at look at how this stuff applies directly to CPUs, see [A Whirlwind Introduction to Dataflow Graphs](https://fgiesen.wordpress.com/2018/03/05/a-whirlwind-introduction-to-dataflow-graphs/). Once we have this new mental model where the cost of an instruction sequence is often dominated by the some critical path though the sequence, we can start to see why well-predicted branches are often very low or zero cost: * Branch instructions have *no ouput register* and *no memory output*1. This means they can't participate in typical dependency chains except as the final node - they always *end* a dependency chain. So branches don't participate in the formation of long dependency chains and thus are in some sense "out of line" and free to be calculated in parallel with other results. * The actual execution of branch instructions generally needs very little *work*: on modern x86 they can execute on two ports, with 1 cycle latency. Furthermore, branch instructions can be *fused* with a previous ALU operation, and the resulting operation still executes in 1 cycle - so in some sense the branch can sometimes be folded into a prior operation *for no additional work at execution*2. This obvious helps the "near zero cost" argument, but also helps the "truly zero cost" argument, since needing fewer resources means that it is less likely to trigger a throughput bottleneck that would disturb a zero cost execution schedule. Those factors combine to make most predicted branch instructions zero cost or nearly zero cost. You don't have to take my word for it, let's look at a real example: ``` int mul1(int count, int x) { do { x *= 111; } while (--count); return x; } ``` Given a `count` and a starting value `x`, it multiplies `x` by 111 `count` times and returns the result. The loop [assembles](https://godbolt.org/g/KaCjJQ) to 3 instructions One for the multiply, one for the `--count` and a branch to check the `count` value: ``` .L2: imul eax, eax, 111 sub edi, 1 jne .L2 ``` Now here's the same loop, but with an additional branch: ``` int mul2(int count, int x) { do { x *= 111; if (x == 0) { abort(); } } while (--count); return x; } ``` This [assembles](https://godbolt.org/g/KaCjJQ) to 5 instructions. The extra two are for the test of `x` and the branch the test shows that `x` is zero: ``` .L7: imul eax, eax, 111 test eax, eax je .L12 ; ends up calling abort sub edi, 1 jne .L7 ``` So what is the cost of adding 60% more instructions, including a branch? Zero, at least to 4 significant digits3: ``` Running benchmarks groups using timer libpfc ** Running benchmark group stackoverflow tests ** Benchmark Cycles No branch 3.000 Added test-branch 3.000 ``` The look takes 3 cycles per iteration, because it is limited by the dependency chain involving 3-cycle multiply. The additional instructions and branch didn't cost anything because they didn't add to this dependency chain and were able to execute "out of line", hiding behind the latency of the critical path. --- 1 Conceptually, branch instructions write the "rip" register, but this isn't treated like the other registers at all: its progression is predicted ahead of time, so the dependency is broken by the predictor. 2 Of course, there is still additional work to decode and fuse the instruction in the first place, but this is often not the bottleneck so may be "free" in cost terms, and things like uop caches means that it may not even be performed frequently. Also, on x86, while a fused branch instruction has the same latency as an ALU op, it is less flexible in terms of which ports it can execute on, so depending on port pressure it may be the case that a fused instruction has some cost compared to the bare ALU op. 3 In fact, if you go to "infinite" significant digits and look at raw cycle counts, you see that additional iterations of this loop cost *exactly* 3 cycles in both cases. The no-branch case does usually end up 1 cycle shorter overall (a difference that goes to 0 in a relative sense as the iterations increase), perhaps because the initial non-steady-state iteration takes an additional cycle, or the misprediction recovery takes an additional cycle on the final iteration. Upvotes: 4 [selected_answer]
2018/03/16
812
2,140
<issue_start>username_0: I want to convert this ``` 1:a,b,c 2:d,e,f ``` into this ``` [[1, ['a', 'b', 'c']],[2, ['d', 'e', 'f']]] ``` My code ``` letters = open("letters.txt") alist = [] for line in favmovies: line = line.strip().split(":") line[0] = int(line[0]) alist.append(line) ``` but it gives this instead ``` [[1, 'a,b,c'], [2, 'd,e,f']] ``` Can anyone please offer a solution?<issue_comment>username_1: You can use `re` to condense the solution: ``` import re data = [re.split('\W+', i.strip('\n')) for i in open("letters.txt")] last_data = [[int(a), b] for a, *b in data] ``` Output: ``` [[1, ['a', 'b', 'c']], [2, ['d', 'e', 'f']]] ``` Upvotes: 0 <issue_comment>username_2: Just split the second part of the array by ",". ``` letters = open("letters.txt") alist = [] for line in favmovies: line = line.strip().split(":") line[0] = int(line[0]) line[1] = line[1].split(',') list.append(line) ``` This gives me, with your example: ``` [1, ['a', 'b', 'c']] [2, ['d', 'e', 'f']] ``` And it preserves the overarching format of your original code. Upvotes: 3 [selected_answer]<issue_comment>username_3: Here ``` letters=open("letters.txt").read().split("\n") output_list=[] for el in letters: output_list.append([el.split(":")[0],el.split(":")[1].split(",")]) ``` Upvotes: 0 <issue_comment>username_4: That can be done with a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) like: ### Code: ``` data = [[int(x[0]), [y.strip() for y in x[1].split(',')]] for x in (line.split(':') for line in letters)] ``` ### Test Code: ``` letters = ['1:a, b, c', '2: d, e, f'] data = [[int(x[0]), [y.strip() for y in x[1].split(',')]] for x in (line.split(':') for line in letters)] print(data) ``` ### Results: ``` [[1, ['a', 'b', 'c']], [2, ['d', 'e', 'f']]] ``` Upvotes: 1 <issue_comment>username_5: Here is one loop approach: ``` print([list(map(lambda x: x.split(','), i.strip().split(':'))) for i in open('file.txt','r')]) ``` output: ``` [[['1'], ['a', 'b', 'c']], [['2'], ['d', 'e', 'f']]] ``` Upvotes: 0
2018/03/16
1,018
4,476
<issue_start>username_0: Before I use Bcrypt on a custom implementation of UserDetailsService, I first want to see if I can use it in an in-memory database. ``` package com.patrick.Security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @EnableWebSecurity @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private UserDetailsService userDetailsService; @Autowired public WebSecurityConfig(UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests() .antMatchers("/").permitAll() .antMatchers(HttpMethod.POST, "/login").permitAll() .antMatchers(HttpMethod.POST, "/users").hasAuthority("ADMIN") .antMatchers(HttpMethod.POST, "/shifts").hasAnyAuthority("ADMIN", "SUPERVISOR") .anyRequest().authenticated() .and() .addFilter(new AuthenticationFilter(authenticationManager())) .addFilter(new AuthorizationFilter(authenticationManager())); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(passwordEncoder()) .withUser("admin").password("<PASSWORD>").roles("ADMIN"); } @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } } ``` With creating/exposing the PasswordEncoder bean this warning pops up which ultimately prevents me from accessing the login path: ``` o.s.s.c.bcrypt.BCryptPasswordEncoder : Encoded password does not look like BCrypt ``` Adding the Deprecated NoOpPasswordEncoder will temporarily solve the issue, but obviously wont encode the passwords: ``` @SuppressWarnings("deprecation") @Bean public static NoOpPasswordEncoder passwordEncoder() { return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance(); } ``` What's the correct way to add Bcrypt?<issue_comment>username_1: > > With creating/exposing the PasswordEncoder bean this warning pops up > which ultimately prevents me from accessing the login path: > > > ``` o.s.s.c.bcrypt.BCryptPasswordEncoder : Encoded password does not look like BCrypt ``` This is because the password you're providing is not encoded with BCrypt. Instead of passing `"password"` directly as the password it needs to be encoded first. For testing purposes, an easy way of doing this would be to just get a hold of your password encoder and encode it in your configure method like this ``` @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { String password = passwordEncoder().encode("<PASSWORD>"); auth.inMemoryAuthentication().withUser("admin").password(<PASSWORD>).roles("ADMIN"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: With [Spring Security 5](https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-storage-format) you can prefix password with `id` of selected `PasswordEncoder`. If you want to use plain password, then simply use `{noop}` prefix, this will delegate password encoder to `NoOpPasswordEncoder`. Example code: ``` @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("{<PASSWORD>").roles("ADMIN"); } ``` Upvotes: 2
2018/03/16
676
2,686
<issue_start>username_0: I just want to ask if it is possible to save/export the values/data in a html Select Tag using javascript or jquery into text file? This is my select tag. ``` ``` Then Im trying to use this javascript code, got it from the internet but it did'nt work. It creates a text file but it didnt get the values/data of the select tag. ``` function saveTextAsFile() { var textToWrite = document.getElementById('mySelect').value; var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'}); var fileNameToSaveAs = "directive.txt"; var downloadLink = document.createElement("a"); downloadLink.download = fileNameToSaveAs; downloadLink.innerHTML = "Download File"; if ($('#sel1').val() == '') { alert('Please select ACCOUNT NAME, SCHEDULE and TASK first.'); } else { window.webkitURL != null; downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob); } downloadLink.click(); } var button = document.getElementById('save'); button.addEventListener('click', saveTextAsFile); button.addEventListener('click', doClear); ```<issue_comment>username_1: > > With creating/exposing the PasswordEncoder bean this warning pops up > which ultimately prevents me from accessing the login path: > > > ``` o.s.s.c.bcrypt.BCryptPasswordEncoder : Encoded password does not look like BCrypt ``` This is because the password you're providing is not encoded with BCrypt. Instead of passing `"password"` directly as the password it needs to be encoded first. For testing purposes, an easy way of doing this would be to just get a hold of your password encoder and encode it in your configure method like this ``` @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { String password = passwordEncoder().encode("<PASSWORD>"); auth.inMemoryAuthentication().withUser("admin").password(<PASSWORD>).roles("ADMIN"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: With [Spring Security 5](https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-storage-format) you can prefix password with `id` of selected `PasswordEncoder`. If you want to use plain password, then simply use `{noop}` prefix, this will delegate password encoder to `NoOpPasswordEncoder`. Example code: ``` @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("{<PASSWORD>").roles("ADMIN"); } ``` Upvotes: 2
2018/03/16
977
2,782
<issue_start>username_0: I want to crawl score of university homepage. So I used selenium and succeed to login homepage. But I can't get "score board page" after login. What I can do? ``` var webdriver = require('selenium-webdriver'); var chrome = require('selenium-webdriver/chrome'); var driver = new webdriver.Builder().forBrowser('chrome').build(); var hisnet = "https://hisnet.handong.edu/login/login.php"; driver.get(hisnet); var By = webdriver.By; driver.findElement(By.name('id')).sendKeys('something'); driver.sleep(4000); driver.findElement(By.name('password')).sendKeys('<PASSWORD>'); driver.sleep(4000); driver.findElement(By.xpath('//input[@ src="/2012_images/intro/btn_login.gif"]')).click(); // below code is not working as my think. driver.sleep(10000); driver.get("https://hisnet.handong.edu/haksa/record/HREC110M.php"); ``` and the error message is below ``` (node:16184) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): NoSuchElementError: no such element: Unable to locate element: {"method":"css selector","selector":"*[name="id"]"} (Session info: chrome=65.0.3325.162) (Driver info: chromedriver=2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91),platform=Windows NT 10.0.16299 x86_64) (node:16184) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. (node:16184) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): NoSuchElementError: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@ src="/2012_images/intro/btn_login.gif"]"} (Session info: chrome=65.0.3325.162) (Driver info: chromedriver=2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91),platform=Windows NT 10.0.16299 x86_64) (node:16184) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): NoSuchElementError: no such element: Unable to locate element: {"method":"css selector","selector":"*[name="password"]"} (Session info: chrome=65.0.3325.162) (Driver info: chromedriver=2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91),platform=Windows NT 10.0.16299 x86_64) ```<issue_comment>username_1: You can use `driver.wait` instead of `driver.sleep` to try again. You can refer to this article [here](https://medium.freecodecamp.org/how-to-write-reliable-browser-tests-using-selenium-and-node-js-c3fdafdca2a9). Hope this can help you. Upvotes: -1 <issue_comment>username_2: Try this: ```js process.on('unhandledRejection', (reason, p) => { console.log('Unhandled Rejection at: Promise', p, 'reason:', reason); // application specific logging, throwing an error, or other logic here }); ``` Upvotes: 0
2018/03/16
280
932
<issue_start>username_0: In R, I have a dataframe with around 700 attributes and 6000 rows. Each cell holds a number between 0 and 5 for how many times something has happened. But instead of numbers, I would like to have yes/no. I know that for each attribute I can do ``` df$col <- ifelse(df$col>=1, "Yes", "No") ``` But what is the best way to do that for all columns without doing a loop?<issue_comment>username_1: You can use `driver.wait` instead of `driver.sleep` to try again. You can refer to this article [here](https://medium.freecodecamp.org/how-to-write-reliable-browser-tests-using-selenium-and-node-js-c3fdafdca2a9). Hope this can help you. Upvotes: -1 <issue_comment>username_2: Try this: ```js process.on('unhandledRejection', (reason, p) => { console.log('Unhandled Rejection at: Promise', p, 'reason:', reason); // application specific logging, throwing an error, or other logic here }); ``` Upvotes: 0
2018/03/16
979
3,685
<issue_start>username_0: While I am able to replace words using regex and here is my code: ``` public static string replacestring(string input) { var Words = "memory|buffer overflow|address space|stack overflow|call stack"; string cleanword = Regex.Replace(input, @"" + Words + "", "", RegexOptions.IgnoreCase); return cleanword; } ``` And here is the string value: > > In software, a stack overflow occurs if the call stack pointer exceeds the stack bound. The call stack may consist of a limited amount of address space, often determined at the start of the program. The size of the call stack depends on many factors, including the programming language, machine architecture, multi-threading, and amount of available memory. When a program attempts to use more space than is available on the call stack (that is, when it attempts to access memory beyond the call stack's bounds, which is essentially a buffer overflow), the stack is said to overflow, typically resulting in a program crash. > > > How do I pick up and display those words found in a string and count them? For example > > Found: stack overflow,address space,call stack,memory,buffer overflow > > Count:5 > > > A million thanks in advance an greatly appreciated and sorry for any inconvenience caused.<issue_comment>username_1: You could start with something like this: ``` string wordsToMatch = "memory|buffer overflow|address space|stack overflow|call stack"; string input = "In software, a stack overflow occurs if the call stack pointer exceeds the stack bound. The call stack may consist of a limited amount of address space, often determined at the start of the program. The size of the call stack depends on many factors, including the programming language, machine architecture, multi-threading, and amount of available memory. When a program attempts to use more space than is available on the call stack (that is, when it attempts to access memory beyond the call stack's bounds, which is essentially a buffer overflow), the stack is said to overflow, typically resulting in a program crash."; var wordsFound = new List(); foreach (string word in wordsToMatch.Split('|')) { foreach (Match match in Regex.Matches(input, word, RegexOptions.IgnoreCase)) { if (match.Value.Equals(word)) { wordsFound.Add(match.Value); } } } Console.WriteLine("Found: " + string.Join(",", wordsFound.Distinct())); Console.WriteLine("Count: " + wordsFound.Distinct().Count()); ``` Output: > > Found: memory,buffer overflow,address space,stack overflow,call stack > > > Count: 5 > > > <http://rextester.com/CYRL45262> Upvotes: 2 <issue_comment>username_2: You can use split function of the string like this: ``` var result = Words.split(new char[] {'|', ' '}) ; var wordCount = result.Length; ``` Upvotes: 0 <issue_comment>username_3: Here's a solution using linq as an alternative: This also addresses the implied uniqueness in the OP. ``` var toMatch = "memory|buffer overflow|address space|stack overflow|call stack"; Regex reg = new Regex(toMatch, RegexOptions.IgnoreCase); var result = reg.Matches(input) .OfType() .Where (m => m.Success) .GroupBy(m => m.Value) .Select (m => new { Word = m.First().Value, QtyFound = m.Count() }); var wordsFound = string.Join(",", result.Select(r => r.Word)); var totalFound = result.Sum(r => r.QtyFound); ``` Upvotes: 0 <issue_comment>username_4: You can use LINQ to remove duplicates and return the count number of the array. ``` var count = Regex.Matches(str, pattern).OfType().Select(m => m.Groups[0].Value).Distinct().ToArray().Count(); ``` Output: ``` 5 ``` [Code demo](https://ideone.com/SLZqVN) Upvotes: 1
2018/03/16
1,185
3,542
<issue_start>username_0: Below is example code: ``` List1 = [['a', 'b', 'c'], ['e', 'f', 'g'], ['1', '2', '3']] range_value = len(List1) * 2 for x in range(0, range_value): if x == 0 or x == 1: for y in List1[0]: print y print x if x == 2 or x == 3: for y in List1[1]: print y print x if x == 4 or x == 5: for y in List1[2]: print y print x ``` This code is looks manual steps defining if statement. In case I have big values like 100 or 1000 of sub lists. I have to write 100's or 1000's of if statement, if x value is 0 and 1 print List1[0] values and if x value is 2 and 3 print List1[1], if x value is 4 and 5 print List1[2] . print x value also like below print x is 0 and print y of List1[0], print x is 1 and print y of List1[0], print x is 2 and print y of List1[1], print x is 3 and print y of List2[1] and so on Help me here<issue_comment>username_1: You don't need use `if` statments. You can make your code mode dynamic by this way: ``` for x in List1: # Iterate over the list of lists for _ in range(2): # Do the process below two times like you want for y in x: # Iterate over each item of the sublist print(y) # Print the item ``` Another idea could be double the iterations of the first loop, and then use a floor division: ``` for x in range(len(List1) * 2): for y in List1[x//2]: # Floor division would turn 0//2 > 0, 1//2 > 0, 2//2 > 1, 3//2 > 1, 4//2 > 1... efectively doubling the loop print(y) ``` Note that my code is in python 3. In order to translate to python 2 I think you have to delete brakets of `print` and change `range` to `xrange` (better perfomance). Also, if you really want to use `if` statement, I would recomend use `elif` instead of `if` in the lines below the first one, that will make you code a bit faster since the another conditionals won't be checked if someone above of them is true. Upvotes: 0 <issue_comment>username_2: Since your indices are grouped by two's you can do the following such that the same operation will occur twice. ``` List1 = [['a', 'b', 'c'], ['e', 'f', 'g'], ['1', '2', '3']] for x in xrange(len(List1) * 2): print x for y in List1[x//2]: print y ``` --- In Python 3 =========== Since your indices are grouped by two's you can do the following such that the same operation will occur twice. ``` List1 = [['a', 'b', 'c'], ['e', 'f', 'g'], ['1', '2', '3']] for x in range(len(List1) * 2): print(x) for y in List1[x//2]: print(y) ``` Using list comprehensions you can also do ``` List1 = [['a', 'b', 'c'], ['e', 'f', 'g'], ['1', '2', '3']] [print(y) for x in range(len(List1) * 2) for y in List1[x//2]] ``` Upvotes: 1 <issue_comment>username_3: Basically your inner for loop runs based on value of x/2: This works: ``` def runMethod(x,List1): if x %2 == 0: for y in List1[int(x/2)]: print y print x List1 = [['a', 'b', 'c'], ['e', 'f', 'g'], ['1', '2', '3']] range_value = len(List1) * 2 for x in range(0, range_value): runMethod(x,List1) ``` Upvotes: 0 <issue_comment>username_4: you may want to use a variable to replace the first and second arguments. Then increase it incrementally. For example, ``` for x in range(0, range_value): if x == first_variable or x == second_variable: for y in List[first_variable]: print(y) first_variable += 2 second_variable += 2 ``` Upvotes: 0
2018/03/16
428
1,451
<issue_start>username_0: I write the code for couchbase view. follow this <https://blog.couchbase.com/understanding-grouplevel-view-queries-compound-keys/> ``` const mapDate = `function(doc, meta) { emit(dateToArray(doc.updatedAt), { _id: meta.id, _rev: meta.rev, updatedAt: doc.updatedAt }); }` ``` and when I call [http://localhost:4984/{db}/\_design/{ddoc}/\_view/{view}](http://localhost:4984/%7Bdb%7D/_design/%7Bddoc%7D/_view/%7Bview%7D) I got an error ``` Error running map function: ReferenceError: dateToArray is not defined ``` [error image](https://i.stack.imgur.com/FqQ9A.png) I use sync-gateway version 1.4 What should I do?<issue_comment>username_1: The blog post you're referring to is about Couchbase Server, not Sync Gateway. So, it looks like `dateToArray` is not a pre-defined function available on Sync Gateway. Upvotes: 1 [selected_answer]<issue_comment>username_2: In order to be able to query views via the Sync Gateway, you should be creating it through the [Sync Gateway REST interface](https://developer.couchbase.com/documentation/mobile/1.5/references/sync-gateway/admin-rest-api/index.html?v=1.4#/query/put__db___design__ddoc_). You cannot query for views directly created on Couchbase Server. This [link](https://developer.couchbase.com/documentation/mobile/1.4/guides/sync-gateway/views/index.html) should provide more insights into creating and querying views via Sync Gateway Upvotes: 1
2018/03/16
714
2,165
<issue_start>username_0: I have a JSON array ***conf=*** ``` [ { "fraudThreshold": 4, "fraudTTLSec": 60 }, { "fraudThreshold": 44, "fraudTTLSec": 60 } ] ``` I want to loop through its items. So I have done the following: ``` for configy in $(echo "${conf}" | jq -r ".[]"); do echo configy=$configy done ``` The results are:- ``` configy={ configy="fraudThreshold": configy=4, configy="fraudTTLSec": ``` *and so on.* It is splitting the string using spaces and giving the results one by one. Why is bash showing this weird behavior? Is there any solution to this? Also, it is giving proper values when I do : ``` configy=$(echo $conf | jq .[-1]) echo configy=$configy ``` Result: ``` configy={ "fraudThreshold": 44, "fraudTTLSec": 60 } ```<issue_comment>username_1: In order to loop through the items in the JSON array using bash, you could write: ``` echo "${conf}" | jq -cr ".[]" | while read -r configy do echo configy="$configy" done ``` This yields: ``` configy={"fraudThreshold":4,"fraudTTLSec":60} configy={"fraudThreshold":44,"fraudTTLSec":60} ``` However there is almost surely a better way to achieve your ultimate goal. Upvotes: 3 <issue_comment>username_2: ``` echo "${conf}" | jq -car '.[] | "configy=" + tojson' ``` produces: ``` configy={"fraudThreshold":4,"fraudTTLSec":60} configy={"fraudThreshold":44,"fraudTTLSec":60} ``` Upvotes: 1 <issue_comment>username_3: > > > ``` > for configy in $(echo "${conf}" | jq -r ".[]"); do > > ``` > > It is splitting the string using spaces and giving the results one by one. Why is bash showing this weird behavior? > > > This behavior is not weird at all. See the [**Bash Reference Manual: Word Splitting**](https://www.gnu.org/software/bash/manual/html_node/Word-Splitting.html): > > The shell scans the results of parameter expansion, command > substitution, and arithmetic expansion that did not occur within > double quotes for word splitting. > > > --- > > Is there any solution to this? > > > username_2 and username_1 presented working solutions; you can slightly optimize them by replacing `echo "${conf}" |` with `<<<"$conf"`. Upvotes: 0
2018/03/16
1,754
6,407
<issue_start>username_0: I read the documentation yesterday and done some coding with python to fetch data in the following way. It's working fine. ``` import logging as log import adal import requests import json import datetime from pprint import pprint # Details of workspace. Fill in details for your workspace. resource_group = 'Test' workspace = 'FirstMyWorkspace' # Details of query. Modify these to your requirements. query = "Type=*" end_time = datetime.datetime.utcnow() start_time = end_time - datetime.timedelta(hours=24) num_results = 2 # If not provided, a default of 10 results will be used. # IDs for authentication. Fill in values for your service principal. subscription_id = '{subscription_id}' tenant_id = '{tenant_id}' application_id = '{application_id}' application_key = '{application_key}' # URLs for authentication authentication_endpoint = 'https://login.microsoftonline.com/' resource = 'https://management.core.windows.net/' # Get access token context = adal.AuthenticationContext('https://login.microsoftonline.com/' + tenant_id) token_response = context.acquire_token_with_client_credentials('https://management.core.windows.net/', application_id, application_key) access_token = token_response.get('accessToken') # Add token to header headers = { "Authorization": 'Bearer ' + access_token, "Content-Type": 'application/json' } # URLs for retrieving data uri_base = 'https://management.azure.com' uri_api = 'api-version=2015-11-01-preview' uri_subscription = 'https://management.azure.com/subscriptions/' + subscription_id uri_resourcegroup = uri_subscription + '/resourcegroups/'+ resource_group uri_workspace = uri_resourcegroup + '/providers/Microsoft.OperationalInsights/workspaces/' + workspace uri_search = uri_workspace + '/search' # Build search parameters from query details search_params = { "query": query, "top": num_results } # Build URL and send post request uri = uri_search + '?' + uri_api response = requests.post(uri, json=search_params,headers=headers) # Response of 200 if successful if response.status_code == 200: # Parse the response to get the ID and status data = response.json() if data.get("__metadata", {}).get("resultType", "") == "error": log.warn("oms_fetcher;fetch_job;error: " + ''.join('{}={}, '.format(key, val) for key, val in data.get("error", {}).items())) else: print data["value"] search_id = data["id"].split("/") id = search_id[len(search_id)-1] status = data["__metadata"]["Status"] print status # If status is pending, then keep checking until complete while status == "Pending": # Build URL to get search from ID and send request uri_search = uri_search + '/' + id uri = uri_search + '?' + uri_api response = requests.get(uri, headers=headers) # Parse the response to get the status data = response.json() status = data["__metadata"]["Status"] print id else: # Request failed print (response.status_code) response.raise_for_status() ``` Today I went to the same webpage that I have followed yesterday but there is a different documentation today. So do I need to follow the new documentation? I tried new documentation too but got into an issue ``` url = "https://api.loganalytics.io/v1/workspaces/{workspace_id}/query" headers = { "X-Api-Key": "{api_key}", "Content-Type": 'application/json' } search_param = { } res = requests.post(url=url, json=search_param, headers=headers) print res.status_code print res.json() ``` > > {u'error': {u'innererror': {u'message': u'The given API Key is not > valid for the request', u'code': u'UnsupportedKeyError'}, u'message': > u'Valid authentication was not provided', u'code': > u'AuthorizationRequiredError'}} > > > Here is the link to [documentation](https://dev.loganalytics.io/)<issue_comment>username_1: The `api_key` is not oms primary key on Portal. You could check example in this [link](https://dev.loganalytics.io/documentation/Using-the-API/RequestFormat). The token should like below: ``` Authorization: Bearer ``` So, you need modify `X-Api-Key": "{api_key}` to `Authorization: Bearer` . You need create a service principal firstly, please check this [link](https://dev.loganalytics.io/documentation/Authorization/AAD-Setup). Then, you could use the sp to get token, please check this [link](https://dev.loganalytics.io/documentation/Authorization/OAuth2). Note: You could your code to get token, but you need modify the resource to `https://api.loganalytics.io`. Like below: ``` # Get access token context = adal.AuthenticationContext('https://login.microsoftonline.com/' + tenant_id) token_response = context.acquire_token_with_client_credentials('https://api.loganalytics.io', application_id, application_key) access_token = token_response.get('accessToken') # Add token to header headers = { "Authorization": 'Bearer ' + access_token, "Content-Type": 'application/json' } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Working Prototype to Query OMS or Log Analytic workspace. ``` import adal import requests import json import datetime from pprint import pprint # Details of workspace. Fill in details for your workspace. resource_group = 'xxx' workspace = 'xxx' workspaceid = 'xxxx' # Details of query. Modify these to your requirements. query = "AzureActivity | limit 10" # IDs for authentication. Fill in values for your service principal. subscription_id = 'xxxx' # subscription_id = 'xxxx' tenant_id = 'xxxx' application_id = 'xxxx' application_key = 'xxxxx' # Get access token context = adal.AuthenticationContext('https://login.microsoftonline.com/' + tenant_id) token_response = context.acquire_token_with_client_credentials('https://api.loganalytics.io', application_id, application_key) access_token = token_response.get('accessToken') # Add token to header headers = { "Authorization": 'Bearer ' + access_token, "Content-Type": 'application/json' } search_params = { "query": query } url = "https://api.loganalytics.io/v1/workspaces/{workspaceID}/query" res = requests.post(url=url, json=search_params, headers=headers) print (res.status_code) print (res.json()) ``` Upvotes: 0
2018/03/16
444
1,547
<issue_start>username_0: I have a select element ``` All One Two Three ``` Then in my component I have ``` methods:{ changeFilter(){ var that = this console.log(that.filter) // this gives me the value from the last select // If I then use Jquery that.filter = window.jQuery('#filter').val() console.log(that.filter) // This gives the correct up to date value } ``` } Why is it that I ahve to use Jquery to get the most recent value of this element? I thought Vue.js was supposed to be reactive? Why is it one tick behind then?? Why am I forced to use jQuery to get the currently chosen selection? Seems super counter intuitive to do that?<issue_comment>username_1: Your mistake is doing a two-way binding plus an event. The event is fired at the same time as the model update, therefore the change hasn't posted yet. You'd be better off using a watch here. First, remove the event: ``` All One Two Three ``` Then put the watch in your Vue object: ``` watch: { filter: function (val) { // use val here } } ``` More info here: <https://v2.vuejs.org/v2/guide/computed.html> Upvotes: 3 [selected_answer]<issue_comment>username_2: > > I was just replicating your code but it was just totally working fine. > > > Check the code below: ```js new Vue({ el: "#app", data: { filter: 'all' }, methods: { changeFilter: function() { alert(this.filter) } } }) ``` ```html All One Two Three ``` Upvotes: 0
2018/03/16
846
2,696
<issue_start>username_0: How do I return a single record from this scope? I tried both ways. ``` class Subscription < ApplicationRecord has_many :invoices, dependent: :destroy class Invoice < ApplicationRecord belongs_to :subscription scope :current, -> do # where(paid: nil).order(:created_at).last where(paid: nil).order(created_at: :desc).limit(1).first end ``` The first way correctly adds `order by ... desc limit 1`, but then it executes another query without the where condition! > > irb(main):004:0> s.invoices.current > >    Invoice Load (22.0ms) SELECT "invoices".\* FROM "invoices" WHERE "invoices"."subscription\_id" = $1 AND **"invoices"."paid" IS NULL** ORDER BY "invoices"."created\_at" **DESC LIMIT $2** [["subscription\_id", 16], ["LIMIT", 1]] > >    Invoice Load (2.0ms) SELECT "invoices".\* FROM "invoices" WHERE "invoices"."subscription\_id" = $1 [["subscription\_id", 16]] > > => #paid: "2018-03-15", created\_at: "2018-03-14 22:42:48">]> > > > The second way also does another query, obliterating the correct results. > > irb(main):007:0> s.invoices.current > > >    Invoice Load (2.0ms) SELECT "invoices".\* FROM "invoices" WHERE "invoices"."subscription\_id" = $1 AND "invoices"."paid" IS NULL > ORDER BY "invoices"."created\_at" DESC LIMIT $2 [["subscription\_id", 16], ["LIMIT", 1]] > > >    Invoice Load (2.0ms) SELECT "invoices".\* FROM "invoices" WHERE "invoices"."subscription\_id" = $1 [["subscription\_id", 16]] > > > => #paid: "2018-03-15", created\_at: "2018-03-14 22:42:48">]> > > > Also, how do I get just the record, not an `ActiveRecord::AssociationRelation`? Ruby 5.0.6<issue_comment>username_1: You might try something like: ``` class Invoice < ApplicationRecord belongs_to :subscription class << self def for_subscription(subscription) where(subscription: subscription) end def unpaid where(paid: nil) end def newest order(created_at: :desc).first end end end ``` Which, if you have an instance of `Subscription` called `@subscription` you could use like: ``` Invoice.unpaid.for_subscription(@subscription).newest ``` I believe that should fire only one query and should return an `invoice` instance. Upvotes: 1 <issue_comment>username_2: I replaced the scope with ``` def self.current where(paid: nil).order(:created_at).last end ``` And it worked. However I don't know why, as this method is in `Invoice` class, while the relation is `ActiveRecord::Associations::CollectionProxy` class. I wish I knew why it works. And I wish I knew why scope didn't work and performed two queries. Upvotes: -1 [selected_answer]
2018/03/16
790
2,836
<issue_start>username_0: [Here is a similar question](https://stackoverflow.com/questions/24384020/why-does-the-compiler-stops-the-name-lookup-on-overloads), but in this question it works, however, it fails in the following circumstance, why? ``` namespace A { int k; } namespace B { class test{}; void k(const test&){/*do something*/} } int main() { using namespace A; k(B::test());//compile error } ``` **Error message is:** "'A::k' cannot be used as a function" (gcc 6.3.0) That is to say, the compiler does not try to do **ADL** and never find the `void k(const test&)` in `namespace B` However, I think the **ADL should work in such situation** because the code above does not belong to the following circumstance: quoted from [cppref](http://en.cppreference.com/w/cpp/language/adl) > > First, the argument-dependent lookup is not considered if the lookup set produced by usual unqualified lookup contains any of the following: > > 1) a **declaration** of a class member > > 2) a **declaration** of a function at block scope (that's not a using-declaration) > > 3) any **declaration** that is not a function or a function template (e.g. a function object or another variable whose name conflicts with the name of the function that's being looked up) > > > To be more precise, here the `using namespace A` **does not introduce any declaration:** quoted from [cppref](http://en.cppreference.com/w/cpp/language/namespace) > > Using-directive does not add any names to the declarative region in which it appears (unlike the using-declaration), and thus does not prevent identical names from being declared. > > ><issue_comment>username_1: The name lookup for a function call has two parts: * normal unqualified lookup * ADL According to N4659 [basic.lookup.argdep]/3, the normal unqualified lookup happens first; and then ADL stage does not go ahead if the normal unqualified lookup found: > > * a declaration of a class member, or > * a block-scope function declaration that is not a using-declaration, or > * a declaration that is neither a function nor a function template. > > > In your code the normal unqualified lookup does find `A::k` as discussed in [your previous question](https://stackoverflow.com/questions/49312133/). So ADL does not happen for this code. Upvotes: 4 [selected_answer]<issue_comment>username_2: > > A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive. *During unqualified name lookup (6.4.1), the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace.* > > > So, unqualified name lookup will find A::k, that is the reason for the error. Upvotes: 2
2018/03/16
687
1,958
<issue_start>username_0: I am trying to make a basic layout with CSS grid and the responsive part with the new specification of [CSS level 4](https://www.w3.org/TR/mediaqueries-4/) , but it is not working for me when compiling the content of the sass, Am I failing in something? Do I miss any detail? **custom-media.scss** ``` *{ margin: 0 ; padding: 0} @custom-media --phone ( 320px < width < 480px); @custom-media --tablets (481px < width < 767px); @custom-media --ipad-landscape (768px < width < 1024px) and (orientation: landscape); @custom-media --ipad-normal (768px < width < 1024px); @custom-media --desktop (1025px < width < 1280px); @custom-media --large (width > 1281px); ``` **app.scss** ``` @import 'custom-media'; /** * * Login Page * */ .container{ width: 100vw; height: 100vh; display: grid; grid-template-columns: 60% 1fr; grid-row: 1fr; .presentation{ background:#CB3BBF; } .loginsection{ } @media (--desktop) { .container { grid-template-columns: 1fr; } .presentation{ background:blue; } } } ``` I try to have the width between 1025px and 1280 px the blue background color and it does not work **in Chrome Versión 64.0.3282.186**<issue_comment>username_1: you can use ``` @mixin responsive($size) { @if $size == large { /* 1920px / @media (max-width: 120em) { @content; } } @if $size == small { / 1199px */ @media (max-width: 74.938em) { @content; } } } @include responsive(large){ font-size: 42px; } @include responsive(small){ font-size: 22px; } ``` this will work. Upvotes: 2 [selected_answer]<issue_comment>username_2: As of now (Dec 2021), it appears that, while in the spec, @custom-media has not been implemented anywhere yet. Neither [caniuse](https://caniuse.com/?search=custom-media) nor [MDN](https://developer.mozilla.org/en-US/search?q=custom-media) know about @custom-media. Upvotes: 0
2018/03/16
2,052
7,027
<issue_start>username_0: How can I get the Cookies' `csrftoken` in `Axios.interceptors.request`'s config? ``` Axios.interceptors.request.use( config => { if ( config.method === "post" || config.method === "put" || config.method === "delete"|| config.method === "get" ) { } if (Cookies.get('token')!==undefined) { config.headers['Authorization']= 'Token '+Cookies.get('token'); } // there I try to get the `csrftoken` in the Cookies, but I can not get. if (Cookies.get('csrftoken')!==undefined) { config.headers['x-csrftoken']= Cookies.get('csrftoken'); // 'CSRFToken' } return config; }, error => { return Promise.reject(error.data.error.message); } ); ``` In the `Axios.interceptors.request`'s config I can not get Cookies's `csrftoken`: `Cookies.get('csrftoken')`. my AxiosConfig code is bellow: ``` AxiosConfig:{ baseURL: 'http://10.10.10.105:8001/', responseType: "json", withCredentials: true, // there will send the Cookie (with it there are: sessionid, csrftoken) xsrfCookieName: 'csrftoken', // default: XSRF-TOKEN xsrfHeaderName: 'x-csrftoken', // default: X-XSRF-TOKEN headers: { "Content-Type": "application/json;charset=utf-8" } } ``` --- **edit-1** There is the `csrftoken` in the Cookie. [![enter image description here](https://i.stack.imgur.com/buSZJ.jpg)](https://i.stack.imgur.com/buSZJ.jpg) --- **edit-2** And in the cookie, there is no `csrftoken` too. [![enter image description here](https://i.stack.imgur.com/CK5zt.jpg)](https://i.stack.imgur.com/CK5zt.jpg) --- **edit-3** if I get the `document.cookie` in console, I will get the `""`: ``` > > document.cookie > > < "" > ``` > > > --- **edit-4** in my Django backend, the `settings.py`: INSTALLED\_APPS: ``` ... 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_docs', 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', ... ``` I am not sure whether the `rest_auth` and `allauth` will affect the `csrftoken`.<issue_comment>username_1: First of all, always make sure that the cookie is not flagged as [httpOnly](https://www.owasp.org/index.php/HttpOnly). If it is, your `javascript` code won't be able to read / modify its content. You can check the cookies tab in your browser and you will see whether it's readable or not. In in your case though, `django` shouldn't be setting the flag as `httpOnly` as the [docs](https://docs.djangoproject.com/en/2.0/ref/csrf/#acquiring-the-token-if-csrf-use-sessions-is-false) describe how to read the value in `javascript` directly from the cookie. A few things I can point out by experience: * The config object might not yet be filled with the data when you receive it within an interceptor. Therefore setting `config.headers = ...;` might trigger an error. Make sure you write: ``` config.headers = config.headers || {}; ``` before setting the `headers` so no *'config.headers is undefined'* will be triggered. * Alternatively to directly reading the cookie, store the `csrf` value inside an hidden `input` as per default procedure. You can do something like this (syntax might be incorrect): ``` ``` and then send the token within the interceptor with: ``` config.headers['x-csrftoken'] = document.querySelector('input[name="csrftoken"]').value; ``` In such case, since you do not need to read the cookie, it would be a **huge plus** to set it as `httpOnly`. Upvotes: 2 <issue_comment>username_2: Axios has an [order of precedence](https://github.com/axios/axios#config-order-of-precedence) to config settings, so it could be possible that settings are overwritten by other code. For example in *Chrome* browser, you can open the dev tools pane, click the Applications tab, and then on the left-side, you can click Cookies to view those to make sure the correct ones exist: [![enter image description here](https://i.stack.imgur.com/WqlXq.png)](https://i.stack.imgur.com/WqlXq.png) If you have an Axios `request interceptor` that defines the `XSRF-TOKEN` header, it would be overwritten by this: ``` axios.post(route('logout'), undefined, { headers: { 'XSRF-TOKEN': 'bad', }, }); ``` If you have a file, such as you would in many Laravel/Vue projects, called `bootstrap.js` or `axios.js` that declares global config settings, that setting could be overwritten by an interceptor. For example: ``` // document head ... // axios.js or bootstrap.js (imported in SPA app's main.js file) window.axios = require('axios'); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; const token = document.head.querySelector('meta[name="csrf-token"]'); if (token) { // an interceptor would overwrite this due to right-to-left precedence window.axios.defaults.headers.common['XSRF-TOKEN'] = token.content; } else { console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token'); } ``` That last example there is very important because, that would be used for calling internal APIs. If you are calling an external API that utilizes CORS, such as Google, they can require specific headers and other headers can cause errors to be thrown. To temporarily overwrite headers, you can use a pattern such as this where you are calling the external API: ``` // temporarily wipe 'XSRF-TOKEN' header for Google CORS const instance = axios.create(); instance.defaults.headers.common = {}; instance.defaults.headers.common.accept = 'application/json'; const { data } = await instance.get('https://www.external.com/foobars'); ``` That would overwrite an interceptor as well because `instance` by design takes precedence over global defaults. Here is the `request interceptor` that I use: ``` import Cookies from 'js-cookie'; /** * Request interceptor: for each request to the server, * attach the CSRF token if it exists. * */ axios.interceptors.request.use(async (request) => { try { const csrf = Cookies.get('XSRF-TOKEN'); request.withCredentials = true; if (csrf) { request.headers.common['XSRF-TOKEN'] = csrf; } return request; } catch (err) { throw new Error(`axios# Problem with request during pre-flight phase: ${err}.`); } }); ``` Since CSRF requires to be accessible by JavaScript, it must **not** be `httpOnly`, so rather than using a library such as `js-cookie`, you can get the cookie using `document.cookie`, but that returns a semicolon-delimited string of key/value pairs, so you could exercise your mind by making a function that extracts the CSRF. ``` console.log('cookies', document.cookie) ``` Bonus reading: * <https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie> * <https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies/get> * <https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies/set> Upvotes: 0
2018/03/16
1,213
3,986
<issue_start>username_0: I need to make the background image in div tag and it has to change automatically, I already put the array of images inside the javascript, but the images is not showing when i'm run the site.The background should behind the menu header. This is the div ``` ``` below of the div is containing the logo, menu and nav part. ``` [![logo mazmida](images/logo.png)](index.html) ``` This is the javascript ``` ```<issue_comment>username_1: document.getElementID('home').src = imgArray[curIndex] You are targeting a div with an ID of home, but this is not an Image element (ie , But since you want to alter the background colour of the DIV, then you use querySelector using javascript and store it in a variable, then you can target the background property of this div (ie Background colour). I hope this helps. Upvotes: 0 <issue_comment>username_2: You are trying to change the src property of a div, but divs do not have such property. Try this: ``` document.getElementById('home').style.backgroundImage = "url('" + imgArray[curIndex] + "')" ``` This changes the style of the target div, more precisely the image to be used as background. Upvotes: 0 <issue_comment>username_3: As you want to change the background image of the `div`, instead of `document.getElementID('home').src = imgArray[curIndex]` use `document.getElementById("#home").style.backgroundImage = "url('imageArray[curIndex]')";` in JavaScript or `$('#home').css('background-image', 'url("' + imageArray[curIndex] + '")');` in jquery. Upvotes: 0 <issue_comment>username_4: You have a few issues with your script. I've made a live JSbin example here: <https://jsbin.com/welifusomi/edit?html,output> ``` var imgArray = [ 'https://upload.wikimedia.org/wikipedia/en/thumb/0/02/Homer\_Simpson\_2006.png/220px-Homer\_Simpson\_2006.png', 'https://upload.wikimedia.org/wikipedia/en/thumb/0/0b/Marge\_Simpson.png/220px-Marge\_Simpson.png', 'https://upload.wikimedia.org/wikipedia/en/a/aa/Bart\_Simpson\_200px.png' ]; var curIndex = 0; var imgDuration = 1000; var el = document.getElementById('home'); function slideShow() { el.style.backgroundImage = 'url(' + imgArray[curIndex % 3] + ')'; curIndex++; setTimeout("slideShow()", imgDuration); } slideShow(); ``` There are a few issues with your script: * On the element since it's a div not an img, you need to set style.backgroundImage instead of src. Look at <https://developer.mozilla.org/en-US/docs/Web/CSS/background> for other attributes to related to background image CSS * Also it's document.getElementById Optimizations * And you can use mod % trick to avoid zero reset * Use setInterval instead of setTimeout Further optimzations * Use requestAnimationFrame instead of setTimeout/setInterval I suggest getting familiar with your browser debugging tools which would help identify many of the issues you face. Upvotes: 1 <issue_comment>username_5: To achieve expected result, use below option of using setInterval Please correct below syntax errors 1. document.getElementID to **document.getElementById** 2. .src attribute is not available on div tags 3. Create img element and add src to it 4. Finally use setInterval instead of setTimeout outside slideShow function ```js var imgArray = [ 'http://www.w3schools.com/w3css/img_avatar3.png', 'https://tse2.mm.bing.net/th?id=OIP.ySEgAgJIlDQsIQTu_MeoLwHaHa&pid=15.1&P=0&w=300&h=300', 'https://tse4.mm.bing.net/th?id=OIP.wBAPnR04OfXaHuFI9Ny2bgHaE8&pid=15.1&P=0&w=243&h=163'], curIndex = 0; imgDuration = 2000; var home = document.getElementById('home') var image = document.createElement('img') function slideShow() { if(curIndex != imgArray.length-1) { image.src = imgArray[curIndex]; home.appendChild(image) curIndex++; }else{ curIndex = 0; } } setInterval(slideShow,2000) ``` ```html ``` code sample - <https://codepen.io/nagasai/pen/JLKvME> Upvotes: 0
2018/03/16
551
1,863
<issue_start>username_0: I am new to programming and stack overflow, so please forgive me if I am not formatting my question properly :) I'm trying to loop through an array containing three spans, and log the 'data-strength' attribute value. I am able to get the individual spans with `$el[i]`, and am also able to get the attribute value with `$el.attr('data-strength')`. When I combine the two however `$el[i].attr('data-strength')`, an error is returned. I assume this is a syntax error, but I'd love some guidance. I've also included the pen link below. Thanks!!! ``` Click Me var $trigger = $("#trigger"), $el = $("#strength span"), $counter = $el.length; $trigger.click(function(){ for(var i = 0; i < $counter; i++){ var $result = $el[i].attr('data-strength'); console.log($result); } }); ``` <https://codepen.io/joeylane/pen/dmGpdq><issue_comment>username_1: `$el[i]` is not a jQuery object. You have to `$($el[i])` to use `attr` ```js var $trigger = $("#trigger"), $el = $("#strength span"), $counter = $el.length; $trigger.click(function() { for (var i = 0; i < $counter; i++) { var $result = $($el[i]).attr('data-strength'); console.log($result); } }); ``` ```html Click Me ``` --- You can also use `each` to loop thru your array and use `this` as selector. ``` $trigger.click(function(){ $el.each(function(){ var $result = $(this).attr('data-strength'); console.log($result); }); }); ``` Upvotes: 1 <issue_comment>username_2: Just iterate ver the spans within the div and use $(this).() to get the data attribue of each. ```js $("#trigger").click(function(){ $("#strength span").each(function(){ var strength = $(this).attr('data-strength'); console.log(strength); }) }); ``` ```html Click Me ``` Upvotes: 1 [selected_answer]
2018/03/16
408
1,324
<issue_start>username_0: The website I want to go is pixiv.net, and after I ping it I found out it's ip, which is 192.168.3.11, but if I directly putting this ip as address in a browser, I got a access forbidden. But I can visit pixiv.net. And then I tried to bind this ip with pixiv.net in my host file. I can still get access to pixiv.net.<issue_comment>username_1: `$el[i]` is not a jQuery object. You have to `$($el[i])` to use `attr` ```js var $trigger = $("#trigger"), $el = $("#strength span"), $counter = $el.length; $trigger.click(function() { for (var i = 0; i < $counter; i++) { var $result = $($el[i]).attr('data-strength'); console.log($result); } }); ``` ```html Click Me ``` --- You can also use `each` to loop thru your array and use `this` as selector. ``` $trigger.click(function(){ $el.each(function(){ var $result = $(this).attr('data-strength'); console.log($result); }); }); ``` Upvotes: 1 <issue_comment>username_2: Just iterate ver the spans within the div and use $(this).() to get the data attribue of each. ```js $("#trigger").click(function(){ $("#strength span").each(function(){ var strength = $(this).attr('data-strength'); console.log(strength); }) }); ``` ```html Click Me ``` Upvotes: 1 [selected_answer]
2018/03/16
1,791
5,633
<issue_start>username_0: How can I print a tibble to the console along with a message? I want to write a function which outputs a tibble along with a verbose message that contains some information about the nature of that tibble. Here is a highly simplistic example of what I have in mind. In the first attempt, the function doesn't work. In the second attempt, it works but outputs some other unnecessary details. ```r # libraries needed library(crayon) library(tibble) # writing the function try.fn1 <- function() { # prepare the tibble x <- tibble::as.tibble(x = rnorm(1:10)) # output the associated message to the user of the function base::message( cat(crayon::blue("The tibble I prepared is-"), x) ) base::message(print(x)) } # using the function try.fn1() #> The tibble I prepared is- #> Error in cat(crayon::blue("The tibble I prepared is-"), x): argument 2 (type 'list') cannot be handled by 'cat' # another attempt try.fn2 <- function() { # prepare the tibble x <- tibble::as.tibble(x = rnorm(1:10)) # output the associated message to the user of the function base::message( cat(crayon::blue("The tibble I prepared is-")) ) base::message(print(x)) } # using the function try.fn2() #> The tibble I prepared is- #> #> # A tibble: 10 x 1 #> value #> #> 1 -0.00529 #> 2 0.562 #> 3 -0.511 #> 4 -0.260 #> 5 -0.232 #> 6 -1.92 #> 7 -0.698 #> 8 2.38 #> 9 1.59 #> 10 -0.585 #> c(-0.00528727617885923, 0.56168758575177, -0.510982641120654, -0.260458372988822, -0.231847890601322, -1.91514178853023, -0.697661618989503, 2.37722341810185, 1.5869372625472, -0.584576993642516) ``` Created on 2018-03-15 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0).<issue_comment>username_1: Capture standard output, which is where `cat()` and `print()` send output, then concatenate and pass to message: ``` message(paste(capture.output({ cat(crayon::blue("The tibble I prepared is-\n")) print(x) }), collapse = "\n")) ``` Upvotes: 1 <issue_comment>username_2: I suggest you either *use* or *mimic* the code within the unexported `print` functions from `tibble`. To access unexported functions, use triple-colons to access `tibble:::print.tbl_df` (and `.tbl`). Two things to know to know to look for these functions: 1. Many functions in R have different behaviors (even different arguments) based on the object(s) called in them. For instance, `summary` behaves differently if given an `lm` object, a `matrix, etc. To see all of the different`summary`functions, try`methods(summary)`. (A good reference for learning more about this, called "S3", can be seen in Hadley's [Advanced R](http://adv-r.had.co.nz/S3.html) online book.) If you bring this around to this question, running `methods("print")` presents (among others): ``` m <- methods("print") m[ grepl("tbl|frame",m) ] # [1] "print.data.frame" "print.frame" "print.tbl_cube" "print.tbl_df" # [5] "print.tbl_lazy" "print.tbl_sql" ``` These don't have to be *exported* by their respective packages to be made available to R. In fact, I seem to find more of them unexported. The fact that `print(my_new_object)` just simply *works* can be a huge convenience to users new and experienced. 2. You can always find the source for this function online (such as on GitHub, like this source [here](https://github.com/tidyverse/tibble/blob/35dfee5bb2bd0594588d20a2baf9220059247dcd/R/tbl-df.r#L23-L32)), but this is not always convenient, and if you aren't careful, it could be for a version of the package other than what you have installed. Most objects in R can be inspected (deeply or otherwise) just by typing the name on the console. This works just as well for variables as it does for functions. There are three ways to look at functions: 1. After `library(pkgname)` or `require(pkgname)`, just type the function name. This is how most people learn and interact with R. 2. Even before loading a package with `library` or `require`, you can view any package's functions with [double-colons](https://stat.ethz.ch/R-manual/R-devel/library/base/html/ns-dblcolon.html), for example `dplyr::filter`. This is also useful when a function name is shared between packages (possible "masking" or collisions), and you want to be clear which one to use. 3. If a function is not exported, no matter if you've called `library` or not, you can only access it with the triple-colons, such as `tibble:::print.tbl_df`. (Actually, there are ways to view the source without the colons such as in R's `browser`, but that's not important here.) There is a risk with using unexported functions. They are typically unexported for one of several reasons, including most importantly (a) not central to the function of the package, and (b) the author has no need or intention of maintaining that function's API (arguments, output) between releases. It is possible (and happens frequently) that an unexported function may disappear, change arguments dramatically, or change methods. Essentially an author has invested in maintaining some semblance of connsistency on exported functions, but not the unexported ones. So by suggesting you look at or use `tibble:::print.tbl_df`, there's risk: it is possible that they will change or remove that function. Having said that, the `print.*` functions are often unexported because they are intended to only be used using the generic S3 version, `print`. The only reason I would expect this specific function to change is if the authors changed the spelling or type of objects the package uses. And I don't see that happening any time soon. Upvotes: 3 [selected_answer]
2018/03/16
838
2,696
<issue_start>username_0: I'm having issues with the code below, why am I not able to check if "if(Person[i][0] < 18)" I get error stating "Incomparable types". I have found articles stating that I can use "if (Person[i][0].equals(18)), but how can I check if it is greater than? ``` Object[][] Person = new Object[2][2]; Person[0][0] = "John"; Person[0][1] = new Integer(18); Person[1][0] = "Mike"; Person[1][1] = new Integer(42); for(int i = 0; i < Person.length; i++) { System.out.print(Person[i][0]); System.out.print("\t" + Person[i][1] + "\t"); if(Person[i][0] < 18) { System.out.print("18 or over"); } System.out.println(); } ```<issue_comment>username_1: You have to type case your object to integer something like: ``` if((int)Person[i][1] > 18) ``` Upvotes: 2 <issue_comment>username_2: It's extended version could be something like below. You might want to avoid **string** check. Go for **Integer** comparison only. ``` import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { Object[][] Person = new Object[2][2]; Person[0][0] = "John"; Person[0][1] = new Integer(18); Person[1][0] = "Mike"; Person[1][1] = new Integer(42); for(int i = 0; i < Person.length; i++) { for(int j = 0; j < Person.length; j++) { System.out.print("\t" + Person[i][j] + "\t"); if(Person[i][j] instanceof Integer) { if((int)Person[i][j] > 18) System.out.print("18 or over"); } } System.out.println(); } } } ``` I would recommend you to use **Map** which could be the best solution for this. Check the code below. ``` import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { Map person = new HashMap<>(); person.put("John", 18); person.put("Tim", 32); person.put("Georges", 39); person.put("Mike", 45); person.put("Vikor", 17); //interate this map Iterator> itr = person.entrySet().iterator(); while(itr.hasNext()){ Map.Entry p = itr.next(); System.out.print(p.getKey() +" - "+p.getValue()); if(p.getValue() >= 32) System.out.print("\t 32 or over"); System.out.println(); } } } ``` Upvotes: 1 [selected_answer]
2018/03/16
536
1,991
<issue_start>username_0: Supposed that I have some xml input which contains something like this. Where `w15` maybe other things like `w`, `w1`. ``` ``` Does anybody know what is the best way to make the replacement? w15:userId="First Last" -> w15:userId="Something else" I don't want to use things like `sed` as I am afraid to replace something that is not supposed to replace. Does anybody know a solution in xslt? Does anybody know a solution in lxml (<http://lxml.de/>)? Any other solutions not using xslt/lxml? Which one is the best for solving this problem? (With `sed`, it is just one line to replace "First Last" with "Something else" (suppose that there is nothing in the input `xml` file that would not make `sed` not working.) Is there a solution that respects `xml` spec but as simple as one line code?<issue_comment>username_1: Let's start with the good news. You can replace value of an attribute with particular name, regardless of the namespace, using a template matching an attribute (`@*`) with particular `local-name()` in the predicate. The script given below has 2 such templates, for `providerId` and `userId`. But the bad news is that you can not totally "close eyes" to the namespaces used. Rules concerning namespace processing by XSLT require that the XSLT script must containt definitions of all used namespaces. Note that the script below contains such a definition: `xmlns:w15="urn:dummy_15"`, usually placed in the root tag of the script. ``` xml version="1.0" encoding="UTF-8" ? ``` For a working example see <http://xsltransform.net/gVrtEmW> So you can have a "sample" XSLT script, without namespaces, but in the last moment, before actual running of the script, you have to take a look at what namespaces contains your source XML file and add specifications of used namespaces to the script. Upvotes: 1 <issue_comment>username_2: In XSLT 3.0 it gets reasonably close to the one-liner you are looking for: ``` Something else ``` Upvotes: 2
2018/03/16
767
2,468
<issue_start>username_0: Trying to write a simple makefile to compile Markdown files to HTML with Pandoc. I don't want to have to add all the prerequisite `.md` files explicitly to the makefile, so I've tried to use a pattern rule along with a wildcard prerequisite: ``` all: www/*.html www/%.html: src/%.md pandoc -f markdown -t html $< > $@ ``` This is close, but only processes prerequisite `.md` files for which an `.html` target file already exists and is out of date. New `.md` files which don't already have an `.html` file get ignored (so if all the non-new files are built, I get `make: Nothing to be done for 'all'.`) What's the concept I'm missing? I'm not sure how to tell make to run on both the changed AND new `.md` files in `src/` and apply the pattern rule to each.<issue_comment>username_1: Try this: ``` $ cat Makefile input := foo.md bar.md baz.md output := $(input:%.md=www/%.html) .PHONY: all all: ${output} www/%.html: src/%.md pandoc -f markdown -t html $< > $@ $ make -n pandoc -f markdown -t html src/foo.md > www/foo.html pandoc -f markdown -t html src/bar.md > www/bar.html pandoc -f markdown -t html src/baz.md > www/baz.html ``` Upvotes: 1 <issue_comment>username_2: You could obtain a list of the `.html` files to be generated from the already existing `.md` files you have in the `src/` directory. --- First, the list of the existing `.md` files can be obtained with the [`wildcard`](https://www.gnu.org/software/make/manual/html_node/Wildcard-Function.html) built-in function: ``` md-files := $(wildcard src/*.md) ``` Then, apply a [substitution reference](https://www.gnu.org/software/make/manual/html_node/Substitution-Refs.html) to the `md-files` variable, so that the `src/` prefix is removed and the suffix `.md` is replaced by `.html` for each element of the list of the `.md` files: ``` $(md-files:src/%.md=%.html) ``` Finally, by applying the [`addprefix`](https://www.gnu.org/software/make/manual/html_node/File-Name-Functions.html) built-in function to the resulting list, the prefix `www/` can be added to each element of that list: ``` html-files := $(addprefix www/,$(md-files:src/%.md=%.html)) ``` Putting everything together, the resulting makefile would be: ``` md-files := $(wildcard src/*.md) html-files := $(addprefix www/,$(md-files:src/%.md=%.html)) .PHONY: all all: $(html-files) www/%.html: src/%.md pandoc -f markdown -t html $< > $@ ``` Upvotes: 3 [selected_answer]
2018/03/16
979
3,533
<issue_start>username_0: I am facing some difficulties in backtracking. 1. How do I define a global list to be used in the problems of backtracking? I saw a couple of answers and they have all suggested using 'global' keyword in front of the variable name, inside the function to use as global. However, it gives me an error here. 2. Is there any good general method that can be used to get the result, instead of a global variable? The code below is trying to solve the backtrack problem wherein, a list of numbers is given, and we have to find unique pairs (no permutations allowed) of numbers that add to the target. ``` For example, given candidate set [2, 3, 6, 7] and target 7, A solution set is: [ [7], [2, 2, 3] ] ///////////////////////////////CODE///////////////////////////// seen = [] res = [] def func(candidates, k, anc_choice): #k == target #global res -- gives me an error -- global name 'res' is not defined if sum(anc_choice) == k: temp = set(anc_choice) flag = 0 for s in seen: if s == temp: flag = 1 if flag == 0: seen.append(temp) print(anc_choice) #this gives me the correct answer res.append(anc_choice) #this doesn't give me the correct answer? print(res) else: for c in candidates: if c <= k: anc_choice.append(c) #choose and append if sum(anc_choice) <= k: func(candidates, k, anc_choice) #explore anc_choice.pop() #unchoose func(candidates, k, []) ``` Can someone please provide me answers/suggestions?<issue_comment>username_1: Try this: ``` $ cat Makefile input := foo.md bar.md baz.md output := $(input:%.md=www/%.html) .PHONY: all all: ${output} www/%.html: src/%.md pandoc -f markdown -t html $< > $@ $ make -n pandoc -f markdown -t html src/foo.md > www/foo.html pandoc -f markdown -t html src/bar.md > www/bar.html pandoc -f markdown -t html src/baz.md > www/baz.html ``` Upvotes: 1 <issue_comment>username_2: You could obtain a list of the `.html` files to be generated from the already existing `.md` files you have in the `src/` directory. --- First, the list of the existing `.md` files can be obtained with the [`wildcard`](https://www.gnu.org/software/make/manual/html_node/Wildcard-Function.html) built-in function: ``` md-files := $(wildcard src/*.md) ``` Then, apply a [substitution reference](https://www.gnu.org/software/make/manual/html_node/Substitution-Refs.html) to the `md-files` variable, so that the `src/` prefix is removed and the suffix `.md` is replaced by `.html` for each element of the list of the `.md` files: ``` $(md-files:src/%.md=%.html) ``` Finally, by applying the [`addprefix`](https://www.gnu.org/software/make/manual/html_node/File-Name-Functions.html) built-in function to the resulting list, the prefix `www/` can be added to each element of that list: ``` html-files := $(addprefix www/,$(md-files:src/%.md=%.html)) ``` Putting everything together, the resulting makefile would be: ``` md-files := $(wildcard src/*.md) html-files := $(addprefix www/,$(md-files:src/%.md=%.html)) .PHONY: all all: $(html-files) www/%.html: src/%.md pandoc -f markdown -t html $< > $@ ``` Upvotes: 3 [selected_answer]
2018/03/16
313
1,310
<issue_start>username_0: I installed VSCode, downloaded official Python 3.6.4. VSCode detected and set the environment right - I do see "python.pythonPath" user setting set correctly. But, when using VS Code using `Ctrl`+`F5`to run a Python file, I am always getting asked for "select environment" and it shows me two options - Python - Python Experimental What is this "Python Experimental"? How can I get rid of getting interrupted every time I try to run a script?<issue_comment>username_1: `Ctrl`+`F5` is a shortcut to `Start without Debugging` What you want is just running a file according to your post. To run a python file in the integrated terminal, right-click your editor window and `Run Python File in Terminal`. It should open up a terminal window within VS Code and run as normal. It also takes into account the environment you are currently using whenever you run it. To answer your other question about `Python Experimental`, it is an option to use the experimental debugger, an alternate version of a Python Debugger. You can read the instructions [here](https://github.com/Microsoft/vscode-python/issues/538) Upvotes: 2 <issue_comment>username_2: `Run > Add Configuration...` => Choose one of the two options. After doing this it will no longer prompt you. Upvotes: 7 [selected_answer]
2018/03/16
617
1,347
<issue_start>username_0: I want to use the `awk` utility to list the maximum score of individual player. This is my `cricketer.txt` file: ``` Virat Kohli:30 Suresh Raina:90 Shikhar Dhawan:122 Virat Kohli:33 Shikhar Dhawan:39 Suresh Raina:10 Suresh Raina:44 MS Dhoni:101 MS Dhoni:33 Virat Kohli:39 Virat Kohli:93 Virat Kohli:94 <NAME>:44 Steven Smith:32 Rohit Sharma:33 Rohit Sharma:18 Rohit Sharma:206 <NAME>:55 ``` This is my `max.awk` file: ``` awk -F ":" -v c=0 '{name[c]=$1;runs[c]=$2;c++;} END{ i=0 j=0 while(i max) { max=cruns[k1] k1=k1+1 } j=j+1 } print name[i],max i=i+1 } }' cricketer.txt | sort | uniq > max.txt ``` This is my `max.txt` file I am getting. ``` MS Dhoni 101 <NAME> 33 Sh<NAME> 122 <NAME> 44 Suresh Raina 90 Virat Kohli 30 ``` It looks like that it is printing only the first score of each individual player. Is the code of `max.awk` file is wrong?<issue_comment>username_1: Following `awk` may help you on same, to get the maximum score for each cricketer :) ``` awk -F":" '{a[$1]=a[$1]>$NF?a[$1]:$NF} END{for(i in a){print i,a[i]}}' Input_file ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: ``` $ sort -t: -k2rn file | awk -F':' '!seen[$1]++' <NAME>:206 <NAME>:122 MS Dhoni:101 V<NAME>:94 <NAME>:90 <NAME>:55 ``` Upvotes: 1
2018/03/16
638
2,102
<issue_start>username_0: I am looking for a way on how to implement file download functionality using gRPC but I can't find in the documentation how this is done. What is an optimal way to do this? I wanted to have a gRPC server that holds files and a gRPC client to request something from gRPC. I have looked at the examples in Java but could not figure out a way on how to do this. I just started reading about gRPC today.<issue_comment>username_1: There are a few possible approaches. If your file size is small enough, you can define a proto file with a single String field, and dump the entire text content into that field. If your file size is too large to do this, you might want to chunk the file and use the streaming API to send the file chunk by chunk. Below is a good guide for getting started with gRPC. <https://grpc.io/docs/tutorials/basic/java.html> Upvotes: 0 <issue_comment>username_2: You must define a specific `message` as data container and you must transfer it to the client in chunks using a `stream`. Example of proto Message and RPC service: ``` message DataChunk { bytes data = 1; } rpc DownloadProductImage(DownloadProductImageRequest) returns(stream DataChunk){} ``` In java you can use `BufferedInputStream` to stream the resource to the client. [protobuf / grpc](https://github.com/nddipiazza/grpc-java/blob/be3616f4ecedab73a513c09678c7c319a863b40d/examples/src/main/proto/file_download.proto) [server side code](https://github.com/nddipiazza/grpc-java/blob/be3616f4ecedab73a513c09678c7c319a863b40d/examples/src/main/java/io/grpc/examples/filedownload/FileDownloadServer.java) [client side code](https://github.com/nddipiazza/grpc-java/blob/be3616f4ecedab73a513c09678c7c319a863b40d/examples/src/main/java/io/grpc/examples/filedownload/FileDownloadClient.java) Upvotes: 4 <issue_comment>username_3: I have taken the working example from username_2 and have created a PR with a full example: <https://github.com/grpc/grpc-java/pull/5126> Hopefully they will merge this then everyone can have a working example of this common use-case for GRPC. Upvotes: 0
2018/03/16
730
2,579
<issue_start>username_0: First off, forgive me on the title. Not really sure how to ask this question: I have an application that I need to convert to a console application (note the application runs fine as a VCL style windows app). The app uses a few 3rd party widgets that have callback functions. However, when I attempt to compile it, I get 'cannot convert ...' errors, like this: > > Cannot convert 'void(Tobject \*, TErrorEventParams \*)' to 'TErrorEvent' > > > `TErrorEvent` is defined as: ``` typedef void __fastcall (__closure* TErrorEvent)(System::TObject* Sender, TErrorEventParams *e); ``` The line causing the error is: ``` handler->OnError = errorHandler; ``` The code for errorHandler is: ``` void __fastcall errorHandler(System::TObject* Sender, TErrorEventParams *e) { memoLine = e->Description; updateLog(); } ```<issue_comment>username_1: Have a look at this documentation: <http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Closure> In short: `TErrorEvent` is defined as a pointer to a class member function. So `errorHandler` has to be declared as a class member function. The implementation could look somewhat like this: ```cpp class TMyClass { private: TMyHandler* handler; void __fastcall errorHandler(System::TObject* Sender, TErrorEventParams *e); public: __fastcall TMyClass(); } my_dummy_class; __fastcall TMyClass::MyClass() { //handler has to be created handler->OnError = errorHandler; } void __fastcall TMyClass::errorHandler(System::TObject* Sender, TErrorEventParams *e) { memoLine = e->Description; updateLog(); } ``` Upvotes: 1 <issue_comment>username_2: A `__closure` type is a pointer to a non-static class method. The compiler does not allow you to assign a standalone non-class function where a `__closure` is expected. It requires a pointer to a method of a class object. Karem's answer shows you one way to accomplish that. However, there *IS* a way to use a non-class function, using the helper [`TMethod`](http://docwiki.embarcadero.com/Libraries/en/System.TMethod) struct (which is how a `__closure` is implemented behind the scenes). First, add an explicit 'this' parameter to your event handler: ``` void __fastcall errorHandler(void *This, TObject* Sender, TErrorEventParams *e) { memoLine = e->Description; updateLog(); } ``` And then assign the event handler like this: ``` TMethod m; m.Code = &errorHandler m.Data = NULL; // any value you want to pass to the 'This' parameter... handler->OnError = reinterpret_cast(m); ``` Upvotes: 3 [selected_answer]
2018/03/16
862
2,644
<issue_start>username_0: I am trying to write a SQL query on finding if two people went to the same place on the same days. For example, if John went to Walmart on 15/03/2018, 10/02/2018, and 03/01/2018 and if Doe went to Walmart on those same days the show the results. But if Doe went to Walmart on 15/03/2018, 10/02/2018, and not 03/01/2018, then don't show this record. Here is the schema of the table. `visitation (username, name, place, date);` ``` john, John, Walmart, '15/03/2018' john, John, Walmart, '10/02/2018' john, John, Walmart, '03/01/2018' doe, Doe, Walmart, '15/03/2018' doe, Doe, Walmart, '10/02/2018' doe, Doe, BestBuy, '11/13/2018' ``` The output for the above should be zero. I know I'll have to self join on the place and day and username not equal username2, but how would I check if the 2nd person went to the same place on the same days and the other person? Any help would be great.<issue_comment>username_1: Have a look at this documentation: <http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Closure> In short: `TErrorEvent` is defined as a pointer to a class member function. So `errorHandler` has to be declared as a class member function. The implementation could look somewhat like this: ```cpp class TMyClass { private: TMyHandler* handler; void __fastcall errorHandler(System::TObject* Sender, TErrorEventParams *e); public: __fastcall TMyClass(); } my_dummy_class; __fastcall TMyClass::MyClass() { //handler has to be created handler->OnError = errorHandler; } void __fastcall TMyClass::errorHandler(System::TObject* Sender, TErrorEventParams *e) { memoLine = e->Description; updateLog(); } ``` Upvotes: 1 <issue_comment>username_2: A `__closure` type is a pointer to a non-static class method. The compiler does not allow you to assign a standalone non-class function where a `__closure` is expected. It requires a pointer to a method of a class object. Karem's answer shows you one way to accomplish that. However, there *IS* a way to use a non-class function, using the helper [`TMethod`](http://docwiki.embarcadero.com/Libraries/en/System.TMethod) struct (which is how a `__closure` is implemented behind the scenes). First, add an explicit 'this' parameter to your event handler: ``` void __fastcall errorHandler(void *This, TObject* Sender, TErrorEventParams *e) { memoLine = e->Description; updateLog(); } ``` And then assign the event handler like this: ``` TMethod m; m.Code = &errorHandler m.Data = NULL; // any value you want to pass to the 'This' parameter... handler->OnError = reinterpret_cast(m); ``` Upvotes: 3 [selected_answer]
2018/03/16
4,907
16,684
<issue_start>username_0: I have a Scroll Progress Bar to let the user know how long a post is. The first approach was to calculate the height of the entire site with $(document).height and it works. ``` $(window).scroll(function(){ var wintop = $(window).scrollTop(); var docheight = $(document).height(); var winheight = $(window).height(); var scrolled = (wintop/(docheight-winheight))*100; $('.scroll-line').css('width', (scrolled + '%')); }); ``` Now I'm trying to get it work only with a specific div, not with the entire site scroll. I've tried replacing **$(window)** or **$(document)** with my container, but it doesn't work. In the next demo, you can see the bar working fine to measure the entire site scroll progress, but I only want to measure the progress of *scroll-progress-begins-here* div. Any help would be great. [DEMO](https://codepen.io/iEbyGeek/pen/PRZdpV)<issue_comment>username_1: Change your javascript to this ``` //capture scroll any percentage $(window).scroll(function(){ var pos = $(".scroll-progress-begins-here").offset(); var wintop = $(window).scrollTop() - pos.top; var dvHeight = $(".scroll-progress-begins-here").height(); var scrolled = (wintop/(dvHeight))*100; $('.scroll-line').css('width', (scrolled + '%')); }); ``` Upvotes: 2 <issue_comment>username_2: Try this code to insert scrollbar at specific div ```css .container { width: 100px; height: 100px; overflow: scroll; } ``` Upvotes: 0 <issue_comment>username_3: use [pace js](http://github.hubspot.com/pace/docs/welcome/) library for progress bar <http://github.hubspot.com/pace/docs/welcome/> this is best way to implement progress bar in our website Upvotes: 0 <issue_comment>username_4: ```js //capture scroll any percentage $(window).scroll(function(){ var wintop = $(window).scrollTop(); var docheight = $(document).height(); var winheight = $(window).height(); var scrolled = (wintop/(docheight-winheight))*100; $('.scroll-line').css('width', (scrolled + '%')); }); ``` ```css body{ overflow:hidden; } header{ position: fixed; top: 0; left: 0; z-index: 1; width: 100%; background: #fff; border-bottom: 1px solid #ccc; } .header-proper{ width: 80%; overflow:hidden; margin: 0 auto; .logo{ font-family: "HelveticaNeueBlack", "HelveticaNeue-Black", "Helvetica Neue Black", "HelveticaNeue", "Helvetica Neue", 'TeXGyreHerosBold', "Arial Black", sans-serif; font-weight:bold; .blue{ color: blue; } } } .scroll-line{ height: 2px; margin-bottom: -2px; background: blue; width: 0%; } .main{ overflow:auto; height:75vh; position:absolute; top:80px; } .content{ padding: 100px 0; margin: 0 auto; width: 80%; } .headline{ font-size: 60px; line-height: 66px; } .scroll-progress-begins-here { background-color: rgba(245,166,35,0.50); } ``` ```html Scroll Progress Bar =================== ### Tristique Aenean Etiam Cras Donec id elit non mi porta gravida at eget metus. Donec ullamcorper nulla non metus auctor fringilla. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. Scroll Progress must begins here ================================ * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. ### Bibendum Aenean Dapibus Tristique Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec ullamcorper nulla non metus auctor fringilla. Sed posuere consectetur est at lobortis. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean lacinia bibendum nulla sed consectetur. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. ---------------------------------------------------------------------- Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Donec id elit non mi porta gravida at eget metus. Aenean lacinia bibendum nulla sed consectetur. ### Tristique Aenean Etiam Cras Donec id elit non mi porta gravida at eget metus. Donec ullamcorper nulla non metus auctor fringilla. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec ullamcorper nulla non metus auctor fringilla. Sed posuere consectetur est at lobortis. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean lacinia bibendum nulla sed consectetur. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. ### Bibendum Aenean Dapibus Tristique Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec ullamcorper nulla non metus auctor fringilla. Sed posuere consectetur est at lobortis. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean lacinia bibendum nulla sed consectetur. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. ### Tristique Aenean Etiam Cras Donec id elit non mi porta gravida at eget metus. Donec ullamcorper nulla non metus auctor fringilla. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec ullamcorper nulla non metus auctor fringilla. Sed posuere consectetur est at lobortis. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean lacinia bibendum nulla sed consectetur. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. ### Bibendum Aenean Dapibus Tristique Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec ullamcorper nulla non metus auctor fringilla. Sed posuere consectetur est at lobortis. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean lacinia bibendum nulla sed consectetur. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. ---------------------------------------------------------------------- Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Donec id elit non mi porta gravida at eget metus. Aenean lacinia bibendum nulla sed consectetur. ### Tristique Aenean Etiam Cras Donec id elit non mi porta gravida at eget metus. Donec ullamcorper nulla non metus auctor fringilla. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec ullamcorper nulla non metus auctor fringilla. Sed posuere consectetur est at lobortis. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean lacinia bibendum nulla sed consectetur. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. ### Bibendum Aenean Dapibus Tristique Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec ullamcorper nulla non metus auctor fringilla. Sed posuere consectetur est at lobortis. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean lacinia bibendum nulla sed consectetur. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. ``` ***Is your problem solved?*** Upvotes: 0
2018/03/16
4,762
16,146
<issue_start>username_0: I have a table in which `labels` are not unique with unique ids, How to select unique `labels` with any ids associated with it. ``` @questionnaireload = Questionnaire.select("DISTINCT label","id") ``` but this gives me ``` #, #, #, #]> ``` I want either or not both, I looked upon pluck, but this also not helpful<issue_comment>username_1: Change your javascript to this ``` //capture scroll any percentage $(window).scroll(function(){ var pos = $(".scroll-progress-begins-here").offset(); var wintop = $(window).scrollTop() - pos.top; var dvHeight = $(".scroll-progress-begins-here").height(); var scrolled = (wintop/(dvHeight))*100; $('.scroll-line').css('width', (scrolled + '%')); }); ``` Upvotes: 2 <issue_comment>username_2: Try this code to insert scrollbar at specific div ```css .container { width: 100px; height: 100px; overflow: scroll; } ``` Upvotes: 0 <issue_comment>username_3: use [pace js](http://github.hubspot.com/pace/docs/welcome/) library for progress bar <http://github.hubspot.com/pace/docs/welcome/> this is best way to implement progress bar in our website Upvotes: 0 <issue_comment>username_4: ```js //capture scroll any percentage $(window).scroll(function(){ var wintop = $(window).scrollTop(); var docheight = $(document).height(); var winheight = $(window).height(); var scrolled = (wintop/(docheight-winheight))*100; $('.scroll-line').css('width', (scrolled + '%')); }); ``` ```css body{ overflow:hidden; } header{ position: fixed; top: 0; left: 0; z-index: 1; width: 100%; background: #fff; border-bottom: 1px solid #ccc; } .header-proper{ width: 80%; overflow:hidden; margin: 0 auto; .logo{ font-family: "HelveticaNeueBlack", "HelveticaNeue-Black", "Helvetica Neue Black", "HelveticaNeue", "Helvetica Neue", 'TeXGyreHerosBold', "Arial Black", sans-serif; font-weight:bold; .blue{ color: blue; } } } .scroll-line{ height: 2px; margin-bottom: -2px; background: blue; width: 0%; } .main{ overflow:auto; height:75vh; position:absolute; top:80px; } .content{ padding: 100px 0; margin: 0 auto; width: 80%; } .headline{ font-size: 60px; line-height: 66px; } .scroll-progress-begins-here { background-color: rgba(245,166,35,0.50); } ``` ```html Scroll Progress Bar =================== ### Tristique Aenean Etiam Cras Donec id elit non mi porta gravida at eget metus. Donec ullamcorper nulla non metus auctor fringilla. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. Scroll Progress must begins here ================================ * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. ### Bibendum Aenean Dapibus Tristique Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec ullamcorper nulla non metus auctor fringilla. Sed posuere consectetur est at lobortis. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean lacinia bibendum nulla sed consectetur. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. ---------------------------------------------------------------------- Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Donec id elit non mi porta gravida at eget metus. Aenean lacinia bibendum nulla sed consectetur. ### Tristique Aenean Etiam Cras Donec id elit non mi porta gravida at eget metus. Donec ullamcorper nulla non metus auctor fringilla. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec ullamcorper nulla non metus auctor fringilla. Sed posuere consectetur est at lobortis. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean lacinia bibendum nulla sed consectetur. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. ### Bibendum Aenean Dapibus Tristique Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec ullamcorper nulla non metus auctor fringilla. Sed posuere consectetur est at lobortis. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean lacinia bibendum nulla sed consectetur. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. ### Tristique Aenean Etiam Cras Donec id elit non mi porta gravida at eget metus. Donec ullamcorper nulla non metus auctor fringilla. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec ullamcorper nulla non metus auctor fringilla. Sed posuere consectetur est at lobortis. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean lacinia bibendum nulla sed consectetur. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. ### Bibendum Aenean Dapibus Tristique Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec ullamcorper nulla non metus auctor fringilla. Sed posuere consectetur est at lobortis. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean lacinia bibendum nulla sed consectetur. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egest<NAME> Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. ---------------------------------------------------------------------- Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Donec id elit non mi porta gravida at eget metus. Aenean lacinia bibendum nulla sed consectetur. ### Tristique Aenean Etiam Cras Donec id elit non mi porta gravida at eget metus. Donec ullamcorper nulla non metus auctor fringilla. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec ullamcorper nulla non metus auctor fringilla. Sed posuere consectetur est at lobortis. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean lacinia bibendum nulla sed consectetur. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. ### Bibendum Aenean Dapibus Tristique Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Etiam porta sem malesuada magna mollis euismod. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec ullamcorper nulla non metus auctor fringilla. Sed posuere consectetur est at lobortis. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Aenean lacinia bibendum nulla sed consectetur. Nulla vitae elit libero, a pharetra augue. Donec sed odio dui. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Cras mattis consectetur purus sit amet fermentum. Maecenas sed diam eget risus varius blandit sit amet non magna. * Ullamcorper Aenean Ornare * Ridiculus Lorem Malesuada Consectetur * Aenean Tristique Sit Lorem Purus * Vehicula Egestas Mollis Cursus Nibh Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Sed posuere consectetur est at lobortis. Sed posuere consectetur est at lobortis. Maecenas faucibus mollis interdum. Nullam id dolor id nibh ultricies vehicula ut id elit. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. ``` ***Is your problem solved?*** Upvotes: 0
2018/03/16
481
1,469
<issue_start>username_0: floating point numbers need to be formatted and displayed in grid. eg 123,456,567.82. Data from backend is 123456567.82. How can this be formatted in ag grid and have other features like sorting, filter work too. i did find a link in stack overflow to use Math. floor (num). tostring and applying some regex, but that truncates decimal points and not sortable.<issue_comment>username_1: ```html Price = {{ price | currency }} var app = angular.module('myApp', []); app.controller('costCtrl', function($scope) { $scope.price = 123456567.82; }); The currency filter formats a number to a currency format. ``` You can use currency filter for and look example may hope it will helps you Upvotes: 2 [selected_answer]<issue_comment>username_2: ``` CellRendererUSD(params: any) { var inrFormat = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2 }); return inrFormat.format(params.value); } columnDefs = [ { headerName: 'A/c No', field: 'accountNo', width: 100 }, { headerName: 'A/c Name', field: 'accountName' }, { headerName: 'NAV', field: 'nav', cellRenderer: this.CellRendererUSD } ]; rowData = [ { accountNo: '4', accountName: 'Janhavee', nav: 10000.49 }, { accountNo: '5', accountName: 'Vignesh', nav: 100000.50 }, { accountNo: '6', accountName: 'Upesh', nav: 1000000.51 } ]; ``` [![Output](https://i.stack.imgur.com/eOuBZ.png)](https://i.stack.imgur.com/eOuBZ.png) Upvotes: 0
2018/03/16
467
1,370
<issue_start>username_0: I have a `List>`. I want to remove it from the list if the key exist in List For example: Input: `List,Map,Map>` (here is a Map) , `List` Explanation: Since, key in map exists in the `List`, I want to remove Map from the `List,Map,Map>` Output: `List,Map>`<issue_comment>username_1: ```html Price = {{ price | currency }} var app = angular.module('myApp', []); app.controller('costCtrl', function($scope) { $scope.price = 123456567.82; }); The currency filter formats a number to a currency format. ``` You can use currency filter for and look example may hope it will helps you Upvotes: 2 [selected_answer]<issue_comment>username_2: ``` CellRendererUSD(params: any) { var inrFormat = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2 }); return inrFormat.format(params.value); } columnDefs = [ { headerName: 'A/c No', field: 'accountNo', width: 100 }, { headerName: 'A/c Name', field: 'accountName' }, { headerName: 'NAV', field: 'nav', cellRenderer: this.CellRendererUSD } ]; rowData = [ { accountNo: '4', accountName: 'Janhavee', nav: 10000.49 }, { accountNo: '5', accountName: 'Vignesh', nav: 100000.50 }, { accountNo: '6', accountName: 'Upesh', nav: 1000000.51 } ]; ``` [![Output](https://i.stack.imgur.com/eOuBZ.png)](https://i.stack.imgur.com/eOuBZ.png) Upvotes: 0
2018/03/16
1,069
3,914
<issue_start>username_0: I'm trying to grab and drag the scroller canvas horizontally. I can scroll left & right with my mouse (Apple Magic Mouse), but have not been able to figure out how to implement the grab and drag left & right. I tried to follow the instructions on the link below, but the pageX & clientX seems to cancel out bringing me straight to the beginning. ``` $('.fc-scroller-canvas').on('mousedown', function(e) { console.log('pageX:::', e.pageX) $('.fc-scroller-canvas').on('mousemove', function(evt) { console.log('clientX:::', evt.clientX) $('.fc-scroller').stop(false, true).animate({ scrollLeft: e.pageX - evt.clientX }); }); }); $('.fc-scroller-canvas').on('mouseup', function() { $('.fc-scroller-canvas').off('mousemove'); }); ``` [jQuery Grab Content and Scroll page horizontally](https://stackoverflow.com/questions/13926640/jquery-grab-content-and-scroll-page-horizontally) Any clue? Can someone help?<issue_comment>username_1: Here is what I did to allow panning around the calendar both vertically and horizontally. You should be able to easily modify it to only work horizontally if that's what you want. I've only tested this with timeline view but it should work with all of the views. ``` var pageX_Drag, pageY_Drag; var disableDragSelector = '.fc-event,.some-other-class-here-maybe'; calendarElement.on('mousedown', '.fc-scroller', function (e) { // prevent drag from happening if we click on certain things var dragDisabledElms = $(e.target).parents(disableDragSelector).addBack(disableDragSelector); if (dragDisabledElms.length) return; pageX_Drag = e.pageX; pageY_Drag = e.pageY; $(window).off("mousemove", __mouseMove_Drag); $(window).on("mousemove", __mouseMove_Drag); }); $(window).on('mouseup', __mouseUp_Drag); function __mouseUp_Drag() { $(window).off("mousemove", __mouseMove_Drag); } function __mouseMove_Drag(evt) { var offsetX = pageX_Drag - evt.pageX; var offsetY = pageY_Drag - evt.pageY; $('.fc-scroller', calendarElement).each(function () { var scroller = $(this); var newX = scroller.scrollLeft() + offsetX; var newY = scroller.scrollTop() + offsetY; scroller.scrollLeft(newX); scroller.scrollTop(newY); }); pageX_Drag = evt.pageX; pageY_Drag = evt.pageY; } ``` Upvotes: 0 <issue_comment>username_2: Thanks @username_1! Code worked like a charm! I've made some modifications to mine so the scrolling activated when clicking and dragging on the .fc-time ``` let pageX_Drag, pageY_Drag; let disableDragSelector = '.fc-event,.some-other-class-here-maybe'; $('.fc-time-area').on('mousedown', '.fc-scroller', function (e) { // prevent drag from happening if we click on certain things let dragDisabledElms = $(e.target).parents(disableDragSelector).addBack(disableDragSelector); if (dragDisabledElms.length) return; pageX_Drag = e.pageX; pageY_Drag = e.pageY; $(window).off("mousemove", __mouseMove_Drag); $(window).on("mousemove", __mouseMove_Drag); }); $(window).on('mouseup', __mouseUp_Drag); function __mouseUp_Drag() { $(window).off("mousemove", __mouseMove_Drag); } function __mouseMove_Drag(evt) { let offsetX = pageX_Drag - evt.pageX; let offsetY = pageY_Drag - evt.pageY; $('.fc-scroller', '.fc-time-area').each(function () { let scroller = $(this); let newX = scroller.scrollLeft() + offsetX; let newY = scroller.scrollTop() + offsetY; scroller.scrollLeft(newX); scroller.scrollTop(newY); }); pageX_Drag = evt.pageX; pageY_Drag = evt.pageY; } ``` Upvotes: 1
2018/03/16
1,877
5,304
<issue_start>username_0: I'm working on an assignment for my programming I class. I'm brand new to C++. What we're trying to do is take year, month, and day arguments provided by the user at the time of execution and calculate the difference between them and the current date. In my main function, I have the following code to grab those arguments from the user: ``` int main(int argc, char** argv) ``` My understanding is that this creates a character array and stores the user's arguments in it. Next, I am assigning the arguments stored in this array to new char variables so that I can pass them to a function, like so: ``` int main(int argc, char** argv) { int year, month, day; char arg1 = argv[1]; string arg2 = argv[2]; char arg3 = argv[3]; argumentChange(argc, arg1, arg2, arg3, year, month, day); blablabla other code } ``` Where `argumentChange` is the function I'm sending them to. The issue is when I try to compile this, I receive the following errors: > > Error: invalid conversion from 'char\*' to 'char' [-fpermissive] > > > charArg1 = argv[1]; > > > Error: invalid conversion from 'char\*' to 'char' [-fpermissive] > > > charArg3 = argv[3]; > > > I've tried searching this issue, and I can't really make heads or tails of the explanations given elsewhere. I've seen a lot of people mention "pointers", which we haven't yet covered in class and which I know nothing about. What have I done wrong? How do I make this work? Here is the complete code for my entire program: ``` #include #include #include using namespace std; void argumentChange(int numArg, char chArg1, string sArg2, char chArg3, int year, int month, int day) { cout << "Starting birth date: " << chArg1 << " " << sArg2 << " " << chArg3 << endl; if (numArg < 4 || numArg > 4) { cout << "Correct Usage: ./cl " << endl; cout << "Try again, dude." << endl; } else if (numArg == 4) { year = chArg1 - '0'; day = chArg3 - '0'; if ((sArg2 == "january") || (sArg2 == "January")) { month = 0; } else if ((sArg2 == "february") || (sArg2 == "February")) { month = 1; } else if ((sArg2 == "march") || (sArg2 == "March")) { month = 2; } else if ((sArg2 == "april") || (sArg2 == "April")) { month = 3; } else if ((sArg2 == "may") || (sArg2 == "May")) { month = 4; } else if ((sArg2 == "june") || (sArg2 == "June")) { month = 5; } else if ((sArg2 == "july") || (sArg2 == "July")) { month = 6; } else if ((sArg2 == "august") || (sArg2 == "August")) { month = 7; } else if ((sArg2 == "september") || (sArg2 == "September")) { month = 8; } else if ((sArg2 == "october") || (sArg2 == "October")) { month = 9; } else if ((sArg2 == "november") || (sArg2 == "November")) { month = 10; } else if ((sArg2 == "december") || (sArg2 == "December")) { month = 11; } else { cout << "Error: You have entered an invalid term for month. Please type "; cout << "the complete name of a valid month." << endl; } } } struct tm bday(int year, int month, int day) { struct tm r {0}; r.tm\_year = year - 1900; r.tm\_mon = month; r.tm\_mday = day; return r; } int main(int argc, char\*\* argv) { int year, month, day; char arg1 = argv[1]; string arg2 = argv[2]; char arg3 = argv[3]; argumentChange(argc, arg1, arg2, arg3, year, month, day); struct tm a = bday(year, month, day); time\_t x = mktime(&a); time\_t y = time(0); if ( x != (time\_t)(-1) && y != (time\_t)(-1) ) { double difference = difftime(y, x) / (60 \* 60 \* 24); cout << ctime(&x); cout << ctime(&y); cout << "difference = " << difference << " days" << endl; } return 0; } ```<issue_comment>username_1: As pointed out, the type of argv[x] is a `char*`, which is a pointer to an array of chars. So `char**` is a pointer to an array of arrays. (Really \* doesn't automatically mean it's a pointer to an array, it just does in this case) ``` // argv is an array of char*'s int main(int argc, char** argv) // firstParam is an array of char's char* firstParam = argv[1]; // firstLetter is the first char of the array char firstLetter = firstParam[0] ``` Really, you should skip all the `char` arrays and just use `std::string`'s. eg ``` int main(int argc, char** argv) { std::string param = argv[1]; if (param == "january") { // Something ... } } ``` You should also really check how many arguments are being passed in, so you don't access outside the range of the array. That's what `argc` is for. Upvotes: 2 [selected_answer]<issue_comment>username_2: When storing an bunch of variables in type `T`, we may have a `dynamic array` to store it. Usually we use the pointer to the array, its type will be `T*` For `int` as example: ``` int* ary1 = new int[3]; ary1[0] = 10; // ary1 + 0 store 10, a int ary1[1] = 11; // ary1 + 1 store 11, a int ary1[2] = 12; // ary1 + 2 store i2, a int ``` Same as `char*` string ``` char** argv= new char*[4]; argv[0] = "cl.exe" // ary2 + 0 stores "cl.exe", a `char*` string argv[1] = "2018"" // ary2 + 1 stores "2018" , a `char*` string argv[2] = "3" // ary2 + 2 stores "3" , a `char*` string argv[3] = "16" // ary2 + 3 stores "16" , a `char*` string ``` So this is why you cannot assign the `argv[1]`, (a `char*` string), to `arg1`, (a `char` character). Upvotes: 0
2018/03/16
1,235
3,123
<issue_start>username_0: I've got a head-scratcher that I'm not sure can be solved in one or two lines of code, which I'm trying. I can more or less do it without a dataframe (e.g., if the data is simply .txt), but I want to see if it can be done with pandas. Below is the `df.head(10)`, and I want to create a dictionary in which the **keys** are the parsed unique `day_of_week` numericals (1-7, for Sunday-Saturday) and the **values** are the ***sum*** of the `births` that occur on each of the individual `day_of_week` values. ``` year month date_of_month day_of_week births 0 1994 1 1 6 8096 1 1994 1 2 7 7772 2 1994 1 3 1 10142 3 1994 1 4 2 11248 4 1994 1 5 3 11053 5 1994 1 6 4 11406 6 1994 1 7 5 11251 7 1994 1 8 6 8653 8 1994 1 9 7 7910 9 1994 1 10 1 10498 ``` I can create the SUM for respective `day_of_week` values easily with: ``` df.groupby[df['day_of_week'] == 1, 'births'].sum() ``` which sums all the births that occur on `day_of_week == 1`. And I can create a dictionary of the `day_of_week` values with: ``` d = {i : 0 for i in df['day_of_week']} ``` which yeilds a dictionary, `d`: ``` {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0} ``` But I cannot connect the two so that I can parse the `day_of_week` numbers, assign those numbers to the **key** of a dictionary, then sum the `births` that occur on each respective `day_of_week`, then assign those sum values to their respective keys. If anyone has suggestions! I've created a dummy dataframe below that replicates the conditions, if that helps, since the `day_of_week` values do repeat in my dataframe (though you can't tell from `df.head()`). ``` d = {'day_of_week' : pd.Series([1, 6, 6, 5, 3, 2, 6, 4, 4, 7, 1]), 'births' : pd.Series([5544, 23456, 473, 34885, 3498, 324, 6898, 83845, 959, 8923, 39577])} df_dummy = pd.DataFrame(d) ```<issue_comment>username_1: This can definitely be answered in one line with pandas. Simply use the groupby construct to groupby your parsed day of week and then sum the number of births. Pandas has built in functionality to turn this into a dictionary, where your keys are the day of the week and the values are the sum: ``` import pandas as pd day_of_week = [6, 7, 1, 2, 3, 4, 5, 6, 7, 1] births = [8096, 7772, 10142, 11248, 11053, 11406, 11251, 8653, 7910, 10498] df = pd.DataFrame({'day_of_week': day_of_week, 'births': births}) df.groupby('day_of_week')['births'].sum().to_dict() # output: {1: 20640, 2: 11248, 3: 11053, 4: 11406, 5: 11251, 6: 16749, 7: 15682} ``` Upvotes: 0 <issue_comment>username_2: Seems like you need ``` df_dummy.set_index('day_of_week').births.sum(level=0).to_dict() Out[30]: {1: 45121, 2: 324, 3: 3498, 4: 84804, 5: 34885, 6: 30827, 7: 8923} ``` Upvotes: 2 [selected_answer]
2018/03/16
520
1,184
<issue_start>username_0: I just installed angular 4 and generated the project, it is compiled correctly but it is not displayed in the browser ![1](https://i.stack.imgur.com/2Gcn3.png) this is what my browser shows ![2](https://i.stack.imgur.com/VYBSv.png)<issue_comment>username_1: This can definitely be answered in one line with pandas. Simply use the groupby construct to groupby your parsed day of week and then sum the number of births. Pandas has built in functionality to turn this into a dictionary, where your keys are the day of the week and the values are the sum: ``` import pandas as pd day_of_week = [6, 7, 1, 2, 3, 4, 5, 6, 7, 1] births = [8096, 7772, 10142, 11248, 11053, 11406, 11251, 8653, 7910, 10498] df = pd.DataFrame({'day_of_week': day_of_week, 'births': births}) df.groupby('day_of_week')['births'].sum().to_dict() # output: {1: 20640, 2: 11248, 3: 11053, 4: 11406, 5: 11251, 6: 16749, 7: 15682} ``` Upvotes: 0 <issue_comment>username_2: Seems like you need ``` df_dummy.set_index('day_of_week').births.sum(level=0).to_dict() Out[30]: {1: 45121, 2: 324, 3: 3498, 4: 84804, 5: 34885, 6: 30827, 7: 8923} ``` Upvotes: 2 [selected_answer]
2018/03/16
542
2,204
<issue_start>username_0: I know the query below is not supported in DynamoDB since you must use an equality expression on the HASH key. `query({ TableName, IndexName, KeyConditionExpression: 'purchases >= :p', ExpressionAttributeValues: { ':p': 6 } });` How can I organize my data so I can efficiently make a query for all items purchased >= 6 times? Right now I only have 3 columns, `orderID` (Primary Key), `address`, `confirmations` (GSI). Would it be better to use a different type of database for this type of query?<issue_comment>username_1: You dont need to reorganise your data, just use a [scan](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html) instead of a query ``` scan({ TableName, IndexName, FilterExpression: 'purchases >= :p', ExpressionAttributeValues: { ':p': 6 } }); ``` Upvotes: -1 <issue_comment>username_2: You would probably want to use the DynamoDB streams feature to perform aggregation into another DynamoDB table. The streams feature will publish events for each change to your data, which you can then process with a Lambda function. I'm assuming in your primary table you would be tracking each purchase, incrementing a counter. A simple example of the logic might be on each update, you check the purchases count for the item, and if it is >= 6, add the item ID to a list attribute `itemIDs` or similar in another DynamoDB table. Depending on how you want to query this statistic, you might create a new entry every day, hour, etc. Bear in mind DynamoDB has a 400KB limit per attribute, so this may not be the best solution depending on how many items you would need to capture in the `itemIDs` attribute for a given time period. You would also need to consider how you reset your purchases counter (this might be a scheduled batch job where you reset purchase count back to zero every x time period). Alternatively you could capture the time period in your primary table and create a GSI that is partitioned based upon time period and has purchases as the sort key. This way you could efficiently query (rather than scan) based upon a given time period for all items that have purchase count of >= 6. Upvotes: 0
2018/03/16
524
2,187
<issue_start>username_0: I have a question about using them, so i don't know how can i explain the question but i'll use a scenario so you can understand me. I started a repository and my partner told me we have to use branches so we can work without any problem(replacing any code using git add --all) and we will working with a base "copy" of the project. So if he adds for example a folder with php files, he must do it in the master branch? or i can access to his branch and get those files? Thank you<issue_comment>username_1: You dont need to reorganise your data, just use a [scan](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html) instead of a query ``` scan({ TableName, IndexName, FilterExpression: 'purchases >= :p', ExpressionAttributeValues: { ':p': 6 } }); ``` Upvotes: -1 <issue_comment>username_2: You would probably want to use the DynamoDB streams feature to perform aggregation into another DynamoDB table. The streams feature will publish events for each change to your data, which you can then process with a Lambda function. I'm assuming in your primary table you would be tracking each purchase, incrementing a counter. A simple example of the logic might be on each update, you check the purchases count for the item, and if it is >= 6, add the item ID to a list attribute `itemIDs` or similar in another DynamoDB table. Depending on how you want to query this statistic, you might create a new entry every day, hour, etc. Bear in mind DynamoDB has a 400KB limit per attribute, so this may not be the best solution depending on how many items you would need to capture in the `itemIDs` attribute for a given time period. You would also need to consider how you reset your purchases counter (this might be a scheduled batch job where you reset purchase count back to zero every x time period). Alternatively you could capture the time period in your primary table and create a GSI that is partitioned based upon time period and has purchases as the sort key. This way you could efficiently query (rather than scan) based upon a given time period for all items that have purchase count of >= 6. Upvotes: 0
2018/03/16
1,165
3,462
<issue_start>username_0: I would like to transpose a square matrix, the following is my code. ``` #include #define SIZE 10 void transpose2D(int ar[][SIZE], int rowSize, int colSize); void display(int ar[][SIZE], int rowSize, int colSize); int main() { int ar[SIZE][SIZE], rowSize, colSize; int i,j; printf("Enter row size of the 2D array: \n"); scanf("%d", &rowSize); printf("Enter column size of the 2D array: \n"); scanf("%d", &colSize); printf("Enter the matrix (%dx%d): \n", rowSize, colSize); for (i=0; i ``` Given an input as such, ``` Enter row size of the 2D array: 4 Enter column size of the 2D array: 4 Enter the matrix (4x4): 1 2 3 4 1 1 2 2 3 3 4 4 4 5 6 7 transpose2D(): 1 2 3 4 1 1 2 2 3 3 4 4 4 5 6 7 ``` This is the result that i get. However, what I am supposed to get is ``` transpose2D(): 1 1 3 4 2 1 3 5 3 2 4 6 4 2 4 7 ``` Is there a mistake in my code that I am unable to identify? My guess would be that my 2D array transpose[][] is not defined properly, but i am unable to point out any mistakes. Any help is greatly appreciated edit: code above now works with changes highlighted<issue_comment>username_1: In `transpose2D` ``` ar[i][j] = transpose[i][j] ; ``` Here you are copying out of bound element of `transpose` to `ar` thats likely to invite undefined behavior You need to start another loop and copy elements of `transpose` back to `ar` Upvotes: 3 [selected_answer]<issue_comment>username_2: Before we write any code, we should investigate what it is exactly that we should accomplish. Let's consider a 4×4 array and its transpose. For illustration, I shall use letters A to P to describe the values: ``` A B C D A E I M E F G H transposed is B F J N I J K L C G K O M N O P D H L P ``` Note how the diagonal entries, `A`, `F`, `K`, and `P` do not change. Also note how `E` and `B` are swapped; as are `I` and `C`, `J` and `G`, `M` and `D`, and so on. So, a transpose is, in fact, possible to implement in place, by swapping pairs of elements. For a 4×4 matrix, there are six pairs to swap: ``` Original Transpose A B C D A E C D A E I D A E I M A E I M A E I M A E I M E F G H B F G H B F G H B F G H B F J H B F J N B F J N I J K L I J K L C J K L C J K L C G K L C G K L C G K O M N O P M N O P M N O P D N O P D N O P D H O P D H L P No swaps B-E C-I D-M G-J H-N L-O ``` Essentially, we swap each one in the lower triangle with the corresponding one in the upper triangle. For illustration, using `L` for lower triangle elements, `U` for upper triangle elements, and `D` for diagonal elements: ``` D U U U L D U U L L D U L L L D ``` We can now write our pseudo-code algorithm: ``` Let T[N][N] be the matrix to be transposed Let C be the column number in the lower triangular part, and the row number in the upper triangular part Let R be the row number in the lower triangular part and the column number in the upper triangular part For C = 0 to N-1, inclusive: For R = C+1 to N-1, inclusive: Swap T[C][R] and T[R][C] End For End For ``` The most common error new programmers make, is swap the entry pairs twice. That does two transposes to the same data, which obviously leads to no observable changes, and confuses many a new programmer! Upvotes: 1
2018/03/16
2,608
9,489
<issue_start>username_0: I know it should be simple, but I couldn't find a way to do it and I have a feeling that is simple but I am stuck. I am trying to display a message every time a checkbox is checked. I have the code below but I can only display the message for the first checkbox. I am just starting with Javascript. ```js function myFunction() { var checkBox = document.getElementById("myCheck"); var text = document.getElementById("text"); if (checkBox.checked == true){ text.style.display = "block"; } else { text.style.display = "none"; } } ``` ```html Display some text when the checkbox is checked: Checkbox: Checkbox is CHECKED! Checkbox2: Second checkbox is checked Checkbox3: Third checkbox is checked ```<issue_comment>username_1: You have multiple elements with the same ID. Try changing two ID's to have either a number on the end (myCheck 1 or myCheck2), or change it to something else completely. Here's my suggestion: ```js function myFunction(idCheck, idText) { var checkBox = document.getElementById(idCheck); var text = document.getElementById(idText); if (checkBox.checked == true){ text.style.display = "block"; } else { text.style.display = "none"; } } ``` ```html Display some text when the checkbox is checked: Checkbox: Checkbox is CHECKED! Checkbox2: Second checkbox is checked Checkbox3: Third checkbox is checked ``` Upvotes: 0 <issue_comment>username_2: First you need to have input type checkbox with uniq id. ``` ``` Then in script, call your function ``` $("#uniq_id").click( function(){ if( $(this).is(':checked') ){ //call your function here myFunction(this); } }); ``` Upvotes: 0 <issue_comment>username_3: id need to be unique. Pass the `id` through the `onclick` handler using `this.id` ```js function myFunction(id) { var checkBox = document.getElementById(id); var text = document.getElementById("text"); if (checkBox.checked === true) { text.style.display = "block"; } else { text.style.display = "none"; } } ``` ```html Display some text when the checkbox is checked: Checkbox: Checkbox is CHECKED! Checkbox2: Second checkbox is checked Checkbox3: Third checkbox is checked ``` Upvotes: 0 <issue_comment>username_4: Well, since id is unique identifier your function always selects first checkbox. ``` document.getElementById("myCheck"); ``` You need to modify it to smth. like this ``` Display some text when the checkbox is checked: Checkbox: Checkbox is CHECKED! Checkbox2: Second checkbox is checked Checkbox3: Third checkbox is checked function myFunction(event) { var checkBox = event.target, id = checkBox.id, text = document.getElementById("text\_" + id); if (checkBox.checked == true) { text.style.display = "block"; } else { text.style.display = "none"; } } ``` Upvotes: 0 <issue_comment>username_5: `id` must be unique, You can pass `id` of both `checkbox` and `p` as parameter to function as follows, ```js function myFunction(id,pid) { var checkBox = document.getElementById(id); var text = document.getElementById(pid); if (checkBox.checked == true){ text.style.display = "block"; } else { text.style.display = "none"; } } ``` ```html Display some text when the checkbox is checked: Checkbox: Checkbox is CHECKED! Checkbox2: Second checkbox is checked Checkbox3: Third checkbox is checked ``` Upvotes: 1 <issue_comment>username_6: Indeed you have to use different IDs, also you don't need several `p` elements for that and lastly to avoid unnecessary queries, you could pass the clicked element to the function since you are calling it via the `onclick` attr. ```js function myFunction(elem) { var checkBox = elem; var p = document.getElementsByTagName('p')[1]; if (checkBox.checked == true){ p.innerHTML = "Checkbox **" + checkBox.id + "** is CHECKED!" p.style.display = "block"; } else { p.style.display = "none"; } } ``` ```html Display some text when the checkbox is checked: Checkbox: Checkbox2: Checkbox3: ``` HIH Upvotes: 0 <issue_comment>username_7: You don't need javascript or jquery at all - this can be achieved using CSS alone - using the direct sibling selector and the :checked pseudo selector you can set the display or visibility property on the next p. You did have multiple id's so that needs to be corrected - but CSS is all you need to toggle the next p after the checked checkbox. ```css p{display: none} input[type="checkbox"]:checked + p {display: block} ``` ```html Display some text when the checkbox is checked: Checkbox: First Checkbox is CHECKED! Checkbox2: Second checkbox is checked Checkbox3: Third checkbox is checked ``` Upvotes: 0 <issue_comment>username_8: Not going to go on about the importance of [why #IDs need to be unique](https://www.deque.com/blog/unique-id-attributes-matter/) and how that hobbles the expected behavior of the checkboxes. There are 2 demos: **Demo 1** uses JavaScript which is IMO overkill for a simple task. 1. For event handling, try to avoid using [on-event attribute event handlers](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers): `**onclick="func();"**`>`` Try **[`addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)** instead, follow the links for details. 2. [**Event Delegation**](https://www.kirupa.com/html5/handling_events_for_many_elements.htm) is used in **Demo 1** so only the added element is used as the eventListener instead of multiple checkboxes. 3. An alternate way of referencing form controls (ex. `input`, `textarea`, etc) is by using the [**HTMLFormControlsCollection** API](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormControlsCollection). Wrapping inputs into an actual tag and giving them `#id` and/or `[name]` attributes we can use a simple and short syntax. In this demo it really isn't needed but here's an example of a conventional way vs. **event delegation/HTMLFCC**: **Normal way:** ``` var chxs = document.querySelectorAll('[type=checkbox]'); for (let i = 0; i < chxs.length; i++) { chxs[i].addEventListener('change', message); } ``` **Event Delegation/HTMLFormControlsCollection** ``` var form = document.forms.formID; form.addEventListener('change', message); ``` --- **Demo 2** uses CSS only. * Using two pseudo-classes: + [**`:checked`**](https://developer.mozilla.org/en-US/docs/Web/CSS/:checked) gives us two states to change styles like `display:none/block`. + `+` **[Adjacent Sibling Combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors)** allows us fine grain control of elements that immediately follow the checkbox (as well as additional siblings and descendant nodes if needed). --- **Details commented in Demos** Demo 1 ------ ```js // Reference the form - see HTMLFormControlsCollection var chxGrp = document.forms.checkGroup; /* Register the change event to form. || Call message() function when a change event happens on or || within the form. || A change event occurs when the user enters data (*input*) || within a form control like an input (*focus*) then clicks onto || another (*unfocus*). || change event is different than most of the events because it || involves multple steps from the user, but it is very effective || for form controls. */ chxGrp.addEventListener('change', message); /* The Event Object is passed through, you might've seen it as || "e" or "evt". How it's labelled doesn't matter because Event || Object is always available when you deal with the DOM. */ function message(event) { // if the node clicked is a checkbox see if it's... if (event.target.type === 'checkbox') { // ... checked then... if (event.target.checked) { // ...find the node that follows it (i.e. **)... event.target.nextElementSibling.className = "message"; } else { /\* Otherwise remove any class on it. (there's a more modern || method: classList that can be used instead) \*/ event.target.nextElementSibling.className = ""; } } return false; }** ``` ```css b { display: none } label { display: table } [type=checkbox] { display: table-cell; } .message { display: table-cell; } ``` ```html Display some text when the checkbox is checked: Checkbox 1: **Checkbox is CHECKED!** Checkbox 2: **Second checkbox is checked** Checkbox 3: **Third checkbox is checked** ``` Demo 2 - CSS Only ----------------- ```css /* Default state of message tag */ b { display: none } /* Using label as a container that acts like a table */ label { display: table } /* Checkboxes are normally set as a component that sits inline with their siblings. Acting as a table-cell does that and has additional advantages as well. When the checkbox is :checked... The adjacent sibling + **behaves as a table-cell as well, thereby being shown/hidden by the corresponding checkbox being toggled. \*/ [type=checkbox], [type=checkbox]:checked + b { display: table-cell; }** ``` ```html Display some text when the checkbox is checked: Checkbox 1: **Checkbox is CHECKED!** Checkbox 2: **Second checkbox is checked** Checkbox 3: **Third checkbox is checked** ``` Upvotes: 1
2018/03/16
2,874
10,654
<issue_start>username_0: I want to add all properties values assigned during instantiation of Course class into text File. ``` CourseManager courseMng = new CourseManager(); Course prog1 = new Course(); Console.WriteLine(prog1.GetInfo()); Console.WriteLine(); prog1.CourseCode = "COMP100"; prog1.Name = "Programming 1"; prog1.Description = "Programming1 description"; prog1.NoOfEvaluations = 3; Console.WriteLine(prog1.GetInfo()); Course prog2 = new Course("COMP123", "Programming2") { Description = "prog 2 desc", NoOfEvaluations = 2 }; Console.WriteLine(prog2.GetInfo()); courseMng.AddCourse(prog1); courseMng.AddCourse(prog2); ``` This was my main and this is my CourseManager class ``` Course[] courses; int numberOfCourses; public int NumberOfCourses { get { return numberOfCourses; } set { numberOfCourses = value; } } public Course[] Courses { get { return courses; } set { courses = value; } } public CourseManager() { Courses = new Course[100]; } public void AddCourse(Course aCourse) { Courses[numberOfCourses] = aCourse; numberOfCourses++; aCourse.Manager = this; } public void ExportCourses(string fileName, char Delim) { FileStream stream = null; StreamWriter writer; try { stream = new FileStream(fileName, FileMode.Create, FileAccess.Write); writer = new StreamWriter(stream); Course aCourse = new Course(); for(int i =0; i ``` So the problem is when i try to writeline it just prints empty values. I want CourseCode,Name,Descrpition and NumberOfEvaluations to be written in .txt file. If u need any other code please let me know Thanks in advance<issue_comment>username_1: You have multiple elements with the same ID. Try changing two ID's to have either a number on the end (myCheck 1 or myCheck2), or change it to something else completely. Here's my suggestion: ```js function myFunction(idCheck, idText) { var checkBox = document.getElementById(idCheck); var text = document.getElementById(idText); if (checkBox.checked == true){ text.style.display = "block"; } else { text.style.display = "none"; } } ``` ```html Display some text when the checkbox is checked: Checkbox: Checkbox is CHECKED! Checkbox2: Second checkbox is checked Checkbox3: Third checkbox is checked ``` Upvotes: 0 <issue_comment>username_2: First you need to have input type checkbox with uniq id. ``` ``` Then in script, call your function ``` $("#uniq_id").click( function(){ if( $(this).is(':checked') ){ //call your function here myFunction(this); } }); ``` Upvotes: 0 <issue_comment>username_3: id need to be unique. Pass the `id` through the `onclick` handler using `this.id` ```js function myFunction(id) { var checkBox = document.getElementById(id); var text = document.getElementById("text"); if (checkBox.checked === true) { text.style.display = "block"; } else { text.style.display = "none"; } } ``` ```html Display some text when the checkbox is checked: Checkbox: Checkbox is CHECKED! Checkbox2: Second checkbox is checked Checkbox3: Third checkbox is checked ``` Upvotes: 0 <issue_comment>username_4: Well, since id is unique identifier your function always selects first checkbox. ``` document.getElementById("myCheck"); ``` You need to modify it to smth. like this ``` Display some text when the checkbox is checked: Checkbox: Checkbox is CHECKED! Checkbox2: Second checkbox is checked Checkbox3: Third checkbox is checked function myFunction(event) { var checkBox = event.target, id = checkBox.id, text = document.getElementById("text\_" + id); if (checkBox.checked == true) { text.style.display = "block"; } else { text.style.display = "none"; } } ``` Upvotes: 0 <issue_comment>username_5: `id` must be unique, You can pass `id` of both `checkbox` and `p` as parameter to function as follows, ```js function myFunction(id,pid) { var checkBox = document.getElementById(id); var text = document.getElementById(pid); if (checkBox.checked == true){ text.style.display = "block"; } else { text.style.display = "none"; } } ``` ```html Display some text when the checkbox is checked: Checkbox: Checkbox is CHECKED! Checkbox2: Second checkbox is checked Checkbox3: Third checkbox is checked ``` Upvotes: 1 <issue_comment>username_6: Indeed you have to use different IDs, also you don't need several `p` elements for that and lastly to avoid unnecessary queries, you could pass the clicked element to the function since you are calling it via the `onclick` attr. ```js function myFunction(elem) { var checkBox = elem; var p = document.getElementsByTagName('p')[1]; if (checkBox.checked == true){ p.innerHTML = "Checkbox **" + checkBox.id + "** is CHECKED!" p.style.display = "block"; } else { p.style.display = "none"; } } ``` ```html Display some text when the checkbox is checked: Checkbox: Checkbox2: Checkbox3: ``` HIH Upvotes: 0 <issue_comment>username_7: You don't need javascript or jquery at all - this can be achieved using CSS alone - using the direct sibling selector and the :checked pseudo selector you can set the display or visibility property on the next p. You did have multiple id's so that needs to be corrected - but CSS is all you need to toggle the next p after the checked checkbox. ```css p{display: none} input[type="checkbox"]:checked + p {display: block} ``` ```html Display some text when the checkbox is checked: Checkbox: First Checkbox is CHECKED! Checkbox2: Second checkbox is checked Checkbox3: Third checkbox is checked ``` Upvotes: 0 <issue_comment>username_8: Not going to go on about the importance of [why #IDs need to be unique](https://www.deque.com/blog/unique-id-attributes-matter/) and how that hobbles the expected behavior of the checkboxes. There are 2 demos: **Demo 1** uses JavaScript which is IMO overkill for a simple task. 1. For event handling, try to avoid using [on-event attribute event handlers](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers): `**onclick="func();"**`>`` Try **[`addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)** instead, follow the links for details. 2. [**Event Delegation**](https://www.kirupa.com/html5/handling_events_for_many_elements.htm) is used in **Demo 1** so only the added element is used as the eventListener instead of multiple checkboxes. 3. An alternate way of referencing form controls (ex. `input`, `textarea`, etc) is by using the [**HTMLFormControlsCollection** API](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormControlsCollection). Wrapping inputs into an actual tag and giving them `#id` and/or `[name]` attributes we can use a simple and short syntax. In this demo it really isn't needed but here's an example of a conventional way vs. **event delegation/HTMLFCC**: **Normal way:** ``` var chxs = document.querySelectorAll('[type=checkbox]'); for (let i = 0; i < chxs.length; i++) { chxs[i].addEventListener('change', message); } ``` **Event Delegation/HTMLFormControlsCollection** ``` var form = document.forms.formID; form.addEventListener('change', message); ``` --- **Demo 2** uses CSS only. * Using two pseudo-classes: + [**`:checked`**](https://developer.mozilla.org/en-US/docs/Web/CSS/:checked) gives us two states to change styles like `display:none/block`. + `+` **[Adjacent Sibling Combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors)** allows us fine grain control of elements that immediately follow the checkbox (as well as additional siblings and descendant nodes if needed). --- **Details commented in Demos** Demo 1 ------ ```js // Reference the form - see HTMLFormControlsCollection var chxGrp = document.forms.checkGroup; /* Register the change event to form. || Call message() function when a change event happens on or || within the form. || A change event occurs when the user enters data (*input*) || within a form control like an input (*focus*) then clicks onto || another (*unfocus*). || change event is different than most of the events because it || involves multple steps from the user, but it is very effective || for form controls. */ chxGrp.addEventListener('change', message); /* The Event Object is passed through, you might've seen it as || "e" or "evt". How it's labelled doesn't matter because Event || Object is always available when you deal with the DOM. */ function message(event) { // if the node clicked is a checkbox see if it's... if (event.target.type === 'checkbox') { // ... checked then... if (event.target.checked) { // ...find the node that follows it (i.e. **)... event.target.nextElementSibling.className = "message"; } else { /\* Otherwise remove any class on it. (there's a more modern || method: classList that can be used instead) \*/ event.target.nextElementSibling.className = ""; } } return false; }** ``` ```css b { display: none } label { display: table } [type=checkbox] { display: table-cell; } .message { display: table-cell; } ``` ```html Display some text when the checkbox is checked: Checkbox 1: **Checkbox is CHECKED!** Checkbox 2: **Second checkbox is checked** Checkbox 3: **Third checkbox is checked** ``` Demo 2 - CSS Only ----------------- ```css /* Default state of message tag */ b { display: none } /* Using label as a container that acts like a table */ label { display: table } /* Checkboxes are normally set as a component that sits inline with their siblings. Acting as a table-cell does that and has additional advantages as well. When the checkbox is :checked... The adjacent sibling + **behaves as a table-cell as well, thereby being shown/hidden by the corresponding checkbox being toggled. \*/ [type=checkbox], [type=checkbox]:checked + b { display: table-cell; }** ``` ```html Display some text when the checkbox is checked: Checkbox 1: **Checkbox is CHECKED!** Checkbox 2: **Second checkbox is checked** Checkbox 3: **Third checkbox is checked** ``` Upvotes: 1
2018/03/16
246
1,019
<issue_start>username_0: Can a developer tell fork/join pool to create certain number of threads? If yes then is it guaranteed that those many number of threads will be created by pool?<issue_comment>username_1: Source : <https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ForkJoinPool.html> > > A ForkJoinPool is constructed with a given target parallelism level; by default, equal to the number of available processors. The pool attempts to maintain enough active (or available) threads by dynamically adding, suspending, or resuming internal worker threads, even if some tasks are stalled waiting to join others > > > Upvotes: 2 [selected_answer]<issue_comment>username_2: basically a fork join pool is ThreadPool which works on work-stealing algorithm. There are api to specify parallelism (max number of active threads - (0-2^15-1)) Specifying parallelism doesn't mean pool will create those many threads at start, but it will create threads if required when work is submitted to pool. Upvotes: 0
2018/03/16
1,066
4,224
<issue_start>username_0: When I use django to design a website and delopy, I find I have some trouble if I use MySQL that the **Binlog** is activate( format:**STATEMENT**). There are my settings for this deployment: * Django based website * uwsgi * Ningx * MySQL The first step, I need to migrate my models to databese, so I input like this: ``` python manage.py migrate ``` And traceback like this: ``` django.db.utils.OperationalError: (1665, 'Cannot execute statement: impossible to write to binary log since BINLOG_FORMAT = STATEMENT and at least one table uses a storage engine limited to row-based logging. InnoDB is limited to row- logging when transaction isolation level is READ COMMITTED or READ UNCOMMITTED.') ``` After searching in Internet, I know the one way to fix it is to change the Binlog format, which works perfectly for me. But I still want to know how to fix it if I don't want to change my Binlog configuration. I think Django can support this format for Binlog.<issue_comment>username_1: Can you try to set **Binlog** format as **ROW** for setting the format please use this, ``` mysql> SET GLOBAL binlog_format = 'ROW'; ``` After that use below query for confirming ``` mysql> show variables like 'binlog_format'; ``` Upvotes: 1 <issue_comment>username_2: After my searching yesterday, I have get a summery solutions for this problem. > > * First solution: Change the Binlog format. > > As Hariprakash said, we can change the Binlog format and fix this problem. In most of cases, it is the best way to fix it. > > You can change the setting in two ways: > 1. Hariprakash ways, but it only influences the settings in session. When you shut down the session, the seetings will be lost. > 2. You can revise Mysql settings file `my.cnf` > > In `my.cnf`, you need to add `log_bin=mysql-bin` and set the `bin_format=ROW` or `binformat=MIXED` which based on your choice. And then, you need to restart Mysql service. That will be effective forever. > > > --- > > * Second solution: Change the default storage engine for Mysql > > Before you revise default storage engine, you need to check how many kinds of your supporting engine. > > `show engines;` > > And you can change the default storage engine. > + In settings file `my.cnf`, you should insert `default-storage-engine=INNODB` after `[mysqld]`, and remember you **must** insert `server-id=1`, this number is used for recognize your host. **Do not** make other host have same number. > + Also you can use the Mysql version for 5.5.4 or older, which uses MyISAM as default storage engine according to [Django document](https://docs.djangoproject.com/en/2.0/ref/databases/). > > > --- Although there are two ways to fix the problem, but I think there are not the best solution. If someone have an better answer which do not revise `my.cnf`, please tell me. Upvotes: 0 <issue_comment>username_3: I ran into a similar problem and fixed it by changing the isolation level to "repeatable read". You really only need it to apply the migrations then you can probably(?) remove it. In settings.py I changed my DATABASES setting to: ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'db_user', 'PASSWORD': '<PASSWORD>', 'HOST': 'db_host', 'PORT': 'db_port', 'CONN_MAX_AGE': db_conn_max_age, 'OPTIONS': { 'isolation_level': "repeatable read", }, } } ``` then ran `python manage migrate`, then remove the `OPTIONS` entry. Pay attention to [these risks](https://docs.djangoproject.com/en/2.1/releases/2.0/#default-mysql-isolation-level-is-read-committed). Upvotes: 2
2018/03/16
2,745
7,526
<issue_start>username_0: I am using a `query` to generate a count. Below is my query ``` SELECT COUNT(DISTINCT sur.`customer_id`) AS 'Survey Done' ,COUNT(CASE WHEN sn.operator_name LIKE '%Zong%' AND sn.`signal_strength` = 'No Signal' THEN 1 ELSE NULL END) AS 'Zong No Signal' ,COUNT(CASE WHEN sn.operator_name LIKE '%Mobilink%' AND sn.`signal_strength` = 'No Signal' THEN 1 ELSE NULL END) AS 'Mobilink No Signal' ,COUNT(CASE WHEN sn.operator_name LIKE '%Ufone%' AND sn.`signal_strength` = 'No Signal' THEN 1 ELSE NULL END) AS 'Ufone No Signal' ,COUNT(CASE WHEN sn.operator_name LIKE '%Telenor%' AND sn.`signal_strength` = 'No Signal' THEN 1 ELSE NULL END) AS 'Telenor No Signal' ,COUNT(CASE WHEN sur.`pole_type` LIKE '%Wall%' THEN 1 ELSE NULL END) AS 'Wall' ,COUNT(CASE WHEN sur.`pole_type` LIKE '%PC Pole%' THEN 1 ELSE NULL END) AS 'PC Pole' ,COUNT(CASE WHEN sur.`pole_type` LIKE '%Structure Pole%' THEN 1 ELSE NULL END) AS 'Structure pole' ,COUNT(CASE WHEN sur.`pole_type` LIKE '%Spon pole%' THEN 1 ELSE NULL END) AS 'Spon pole' ,sd.`sub_div_code` AS 'SD Code', sd.`name` AS 'SD Name', sd.`circle_name` AS 'Circle Name', sd.`division_name` AS 'Division Name' FROM `survey` sur INNER JOIN `survey_hesco_subdivision` sd ON sur.`sub_division` = sd.`sub_div_code` INNER JOIN `survey_networks` sn ON sur.`id` = sn.`survey_id` WHERE sur.`customer_id` IN ('37010185878', '37010718785', '37010718759', '37010357911', '37010673539', '37010673796', '37010672166', '37010672162') GROUP BY sd.`name` ``` All the counts are correct but for the below part the values are incorrect ``` ,COUNT(CASE WHEN sur.`pole_type` LIKE '%Wall%' THEN 1 ELSE NULL END) AS 'Wall' ,COUNT(CASE WHEN sur.`pole_type` LIKE '%PC Pole%' THEN 1 ELSE NULL END) AS 'PC Pole' ,COUNT(CASE WHEN sur.`pole_type` LIKE '%Structure Pole%' THEN 1 ELSE NULL END) AS 'Structure pole' ,COUNT(CASE WHEN sur.`pole_type` LIKE '%Spon pole%' THEN 1 ELSE NULL END) AS 'Spon pole' ``` The output for them is `10`,`4`,`24` and `0`. But the actual count is `4`,`1`,`7` and `0` The sample output is [![enter image description here](https://i.stack.imgur.com/oMXor.png)](https://i.stack.imgur.com/oMXor.png) The last value `spon pole` is `0` for some records but not for all, hence it's count is also not correct. How can I get the correct count of these values? I have also tried `=` sign in replace of `LIKE` but still it won't gives me the correct result. I have also seen this [solution](https://stackoverflow.com/a/17975288/8919244) Any help would be highly appreciated<issue_comment>username_1: You might use `SUM` instead of `Count` and `ELSE` set `0` ``` SELECT COUNT(DISTINCT sur.`customer_id`) AS 'Survey Done' ,SUM(CASE WHEN sur.`pole_type` LIKE '%Wall%' THEN 1 ELSE 0 END) AS 'Wall' ,SUM(CASE WHEN sur.`pole_type` LIKE '%PC Pole%' THEN 1 ELSE 0 END) AS 'PC Pole' ,SUM(CASE WHEN sur.`pole_type` LIKE '%Structure Pole%' THEN 1 ELSE 0 END) AS 'Structure pole' ,SUM(CASE WHEN sur.`pole_type` LIKE '%Spon pole%' THEN 1 ELSE 0 END) AS 'Spon pole' ,sur.`sub_division` FROM `survey` sur ``` if you want to distinguish on `sur.sub_division` just add `group by by sur.sub_division` ``` SELECT COUNT(DISTINCT sur.`customer_id`) AS 'Survey Done' ,SUM(CASE WHEN sur.`pole_type` LIKE '%Wall%' THEN 1 ELSE 0 END) AS 'Wall' ,SUM(CASE WHEN sur.`pole_type` LIKE '%PC Pole%' THEN 1 ELSE 0 END) AS 'PC Pole' ,SUM(CASE WHEN sur.`pole_type` LIKE '%Structure Pole%' THEN 1 ELSE 0 END) AS 'Structure pole' ,SUM(CASE WHEN sur.`pole_type` LIKE '%Spon pole%' THEN 1 ELSE 0 END) AS 'Spon pole' ,sur.`sub_division` FROM `survey` sur GROUP BY sur.`sub_division` ``` **Edit** I guess the problem is on `Group by filed` you can try this. ``` SELECT COUNT(DISTINCT sur.`customer_id`) AS 'Survey Done' ,SUM(CASE WHEN sn.operator_name LIKE '%Zong%' AND sn.`signal_strength` = 'No Signal' THEN 1 ELSE 0 END) AS 'Zong No Signal' ,SUM(CASE WHEN sn.operator_name LIKE '%Mobilink%' AND sn.`signal_strength` = 'No Signal' THEN 1 ELSE 0 END) AS 'Mobilink No Signal' ,SUM(CASE WHEN sn.operator_name LIKE '%Ufone%' AND sn.`signal_strength` = 'No Signal' THEN 1 ELSE 0 END) AS 'Ufone No Signal' ,SUM(CASE WHEN sn.operator_name LIKE '%Telenor%' AND sn.`signal_strength` = 'No Signal' THEN 1 ELSE 0 END) AS 'Telenor No Signal' ,SUM(CASE WHEN sur.`pole_type` LIKE '%Wall%' THEN 1 ELSE 0 END) AS 'Wall' ,SUM(CASE WHEN sur.`pole_type` LIKE '%PC Pole%' THEN 1 ELSE 0 END) AS 'PC Pole' ,SUM(CASE WHEN sur.`pole_type` LIKE '%Structure Pole%' THEN 1 ELSE 0 END) AS 'Structure pole' ,SUM(CASE WHEN sur.`pole_type` LIKE '%Spon pole%' THEN 1 ELSE 0 END) AS 'Spon pole' ,sd.`sub_div_code` AS 'SD Code', sd.`name` AS 'SD Name', sd.`circle_name` AS 'Circle Name', sd.`division_name` AS 'Division Name' FROM `survey` sur INNER JOIN `survey_hesco_subdivision` sd ON sur.`sub_division` = sd.`sub_div_code` INNER JOIN `survey_networks` sn ON sur.`id` = sn.`survey_id` WHERE sur.`customer_id` IN ('37010185878', '37010718785', '37010718759', '37010357911', '37010673539', '37010673796', '37010672166', '37010672162') GROUP BY sd.`sub_div_code`, sd.`name`, sd.`circle_name`, sd.`division_name` ``` [SQLFiddle](http://sqlfiddle.com/#!9/59132/9) Upvotes: 1 <issue_comment>username_2: So, after a lot of searching, I am able to figure out the correct query which is giving me correct results ``` SELECT SUM(z.Survey_Done) AS 'Survey Done',SUM(Zong) AS 'Zong No Signal',SUM(Mobilink) AS 'Mobilink No Signal',SUM(Ufone) AS 'Ufone No Signal',SUM(Telenor) AS 'Telenor No Signal' ,SUM(Wall) AS Wall,SUM(PC_Pole) AS 'PC Pole',SUM(Structure_pole) AS 'Structure Pole',SUM(Spon_pole) AS 'Spon Pole',SDCode ,sd.`name` AS 'SD Name' ,sd.`circle_name` AS 'Circle Name' ,sd.`division_name` AS 'Division Name' FROM ( SELECT COUNT(DISTINCT sur.`customer_id`) AS 'Survey_Done', 0 AS 'Zong', 0 AS 'Mobilink', 0 AS 'Ufone', 0 AS 'Telenor' ,SUM(CASE WHEN sur.`pole_type` LIKE '%Wall%' THEN 1 ELSE 0 END) AS 'Wall' ,SUM(CASE WHEN sur.`pole_type` LIKE '%PC Pole%' THEN 1 ELSE 0 END) AS 'PC_Pole' ,SUM(CASE WHEN sur.`pole_type` LIKE '%Structure Pole%' THEN 1 ELSE 0 END) AS 'Structure_pole' ,SUM(CASE WHEN sur.`pole_type` LIKE '%Spon pole%' THEN 1 ELSE 0 END) AS 'Spon_pole' ,sd.`sub_div_code` AS 'SDCode' FROM `survey` sur INNER JOIN `survey_hesco_subdivision` sd ON sur.`sub_division` = sd.`sub_div_code` WHERE sur.`customer_id` IN () GROUP BY sd.`sub_div_code`, sd.`name`, sd.`circle_name`, sd.`division_name` UNION SELECT 0 AS 'Survey_Done', SUM(CASE WHEN sn.operator_name LIKE '%Zong%' AND sn.`signal_strength` = 'No Signal' THEN 1 ELSE 0 END) AS 'Zong' ,SUM(CASE WHEN sn.operator_name LIKE '%Mobilink%' AND sn.`signal_strength` = 'No Signal' THEN 1 ELSE 0 END) AS 'Mobilink' ,SUM(CASE WHEN sn.operator_name LIKE '%Ufone%' AND sn.`signal_strength` = 'No Signal' THEN 1 ELSE 0 END) AS 'Ufone' ,SUM(CASE WHEN sn.operator_name LIKE '%Telenor%' AND sn.`signal_strength` = 'No Signal' THEN 1 ELSE 0 END) AS 'Telenor' ,0 AS 'Wall' ,0 AS 'PC Pole' ,0 AS 'Structure pole' ,0 AS 'Spon pole' ,sd.`sub_div_code` AS 'SDCode' FROM `survey_networks` sn INNER JOIN `survey` sur ON sur.`id` = sn.`survey_id` INNER JOIN `survey_hesco_subdivision` sd ON sur.`sub_division` = sd.`sub_div_code` WHERE sur.`customer_id` IN () GROUP BY sd.`sub_div_code` ) z INNER JOIN `survey_hesco_subdivision` sd ON sd.`sub_div_code`=SDCode GROUP BY sd.`name` ``` I have used `UNION` in the above query. Upvotes: 1 [selected_answer]
2018/03/16
552
1,994
<issue_start>username_0: I want to use the same `onChange` handler for a series of inputs. ``` ``` so I am attempting to use this html data attribute to store the input's name. When I go to pull the attribute off in JavaScript, I am unable to access it. ``` handleInputChange = (event) => { this.setState([event.target.inputName]: event.target.value}) } ``` I've tried a few permutations to no avail, and it seems difficult to debug since when I log the `event.target` I just see an html element in the JavaScript console. Any advice on how to better debug this or where my syntax is going wrong?<issue_comment>username_1: You could pass the input name as an argument instead of having it as a property, like so: ``` this.handleInputChange(e,"someValue")} type="text" value={this.state.name}/> ``` and then ``` handleInputChange = (event, name) => { this.setState([name]: event.target.value}) } ``` Upvotes: 2 <issue_comment>username_2: I was also able to find a somewhat dirty solution to pulling the value off of the event object. ``` event.target.attributes['data-input-name'].value ``` Upvotes: 1 <issue_comment>username_3: I've noticed that you have missed an opening curly brace in your `setState` call. And that will throw a syntax error when you run it. It should be fixed like this: ``` handleInputChange = (event) => { this.setState({[event.target.inputName]: event.target.value}) } ``` For accessing your data attribute from the `handleInputChange`, you can do it like this: ``` handleInputChange = event => { this.setState({ [event.target.getAttribute('data-input-name')]: event.target.value, }); }; ``` And also, you can use the default name attributes that comes with these inputs like this: ``` handleInputChange = event => { this.setState({ [event.target.name]: event.target.value, }); }; // in your render fucntion ``` This will work as the same as using data attributes. Hope this help! Upvotes: 3 [selected_answer]
2018/03/16
254
874
<issue_start>username_0: [![enter image description here](https://i.stack.imgur.com/qlicx.png)](https://i.stack.imgur.com/qlicx.png) I am new to opencv. I found the following code swaps red and blue channel when I fed sRGB png to it. Which function should I blame, imread or fromarray?<issue_comment>username_1: Yes, OpenCV follows BGR color convention internally. However, you may either use [`cv2.cvtColor(img, cv2.COLOR_BGR2RGB)`](https://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor) before displaying your image using a **third party function**(`display()` in this case). Or you can also use `cv2.imshow()` method to debug images, which doesn't require `cv2.cvtColor()` Upvotes: 4 [selected_answer]<issue_comment>username_2: Rather simple option would be swapping the R and B channels: ``` img = img[:, :, ::-1] ``` Upvotes: 2
2018/03/16
788
2,614
<issue_start>username_0: I am trying to get all combinations of a list. The result for `[1,2,3]` should be `[(1,2),(1,3),(2,3)]`. My implementation below, however, gives `[(1,2),(2,3)]`. ``` parings [d] = [] parings (y:ys) = (y, head ys): parings ys ```<issue_comment>username_1: I don't know why you're opposed to list comprehensions; with them, the solution is trivial: ``` pairwise :: [a] -> [(a, a)] pairwise [] = [] pairwise (x:xs) = [(x, y) | y <- xs] ++ pairwise xs ``` You can factor out the comprehension into a separate function with explicit tail recursion if you want. (The whole thing can be made tail-recursive, too, by keeping parameters for both sides of the `++` and having an accumulator parameter.) Upvotes: 1 [selected_answer]<issue_comment>username_2: The list comprehension mentioned in username_1's answer can be trivially factored into a `map` call. ``` pairwise :: [a] -> [(a, a)] pairwise [] = [] pairwise (x:xs) = map (\y -> (x, y)) xs ++ pairwise xs ``` Every list comprehension can be factored into some combination of `map`, `filter`, and `concatMap`, possibly with some `let` bindings interspersed. Doing so is a good exercise for learning how to manipulate functions. Upvotes: 2 <issue_comment>username_3: Here is one implementation using `tails` from `Data.List`: ``` import Data.List pairings :: [a] -> [(a, a)] pairings = concatMap makePairs . tails where makePairs [] = [] makePairs (x:xs) = fmap ((,) x) xs ``` Notes: * I don't know whether `tails` counts as a "special import" for you -- though it is not in the Prelude, it can be found in the *base* library, which is always available. * To see what `tails` does, try `tails [1..3]`. * `((,) x)` is just a compact way of writing `(\y -> (x, y))`. If you find it ugly, you can write the longer version instead, or enable the `TupleSections` extension and spell it as `(x,)`. * `makePairs` might be written without explicit recursion as... ``` makePairs = maybe [] (\(x, xs) -> fmap ((,) x) xs) . uncons ``` ... with `uncons` also being found in `Data.List`. * All the implementations in the answers here have a not insignificant problem: they retain consumed list segments in memory. To see what I'm talking about, watch the memory usage as you run `head . drop 8000000 $ pairings [1..]` in GHCi. I'm not confident about there being a workaround for that -- a simple `concat . tails`, for instance, appears to run into the same issue, while `fmap makePairs . tails` doesn't (even `head . drop (10^9) . head . drop (10^9) . fmap makePairs . tails $ [1..]` won't eat up all your memory). Upvotes: 1
2018/03/16
501
1,603
<issue_start>username_0: **ERROR Message** > > Order\_ID could refer to more than one table in the FROM clause of the SQL statement > > > ``` SELECT Customer_ID, o.Order_ID, o.Order_Date, p.Product_Description, p.Product_Finish FROM Order_T AS o, Order_Line_T AS ol, Product_T AS p WHERE o.Order_ID=ol.Order_ID AND ol.Product_ID = p.Product_ID AND ol.Ordered_Quantity > 3 ORDER BY Order_ID; ``` I keep getting an error stating Order\_ID could refer to more than one table in the FROM clause of the SQL statement, can someone help me with this I have no idea whats wrong.<issue_comment>username_1: ``` FROM Order_T AS o, Order_Line_T AS ol, Product_T AS p WHERE o.Order_ID=ol.Order_ID .... ``` looking at the above query, you can see that there are at least two columns `Order_ID` in 2 tables: * o.Order\_ID * ol.Order\_ID There is also `Order_ID` column in this clause `ORDER BY Order_ID;` without an alias. The database doesn't know which order\_id column should use here - o.Order\_ID or ol.Order\_ID , and reports an error. Just use an alias in the order by clause: `ORDER BY o.Order_ID;`, this should fix the problem. Upvotes: 1 <issue_comment>username_2: You are missing the `JOIN`. While `WHERE` clauses can be acceptable, it is preferred in Access to use the `ON` keyword. Additionally, Access requires parentheses around multiple joins within the same statement. Try: ``` FROM (Order_T AS o INNER JOIN Order_Line_T AS ol ON o.Order_ID=ol.Order_ID) INNER JOIN Product_T AS p ON ol.Product_ID = p.Product_ID WHERE ol.Ordered_Quantity > 3 ORDER BY o.Order_ID; ``` Upvotes: 0
2018/03/16
469
1,579
<issue_start>username_0: ``` if (isset($_SESSION['cart'])) { foreach($_SESSION['cart'] as $key => $value) { $sql = "SELECT product_name, image, price, sum(price) AS subtotal FROM items WHERE id = '$key' "; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { $item = mysqli_fetch_assoc($result); extract($item); } } } ``` Im trying to get the sum of my cart but when I echo the $subtotal what im getting is not the sum but the price of only one item<issue_comment>username_1: ``` FROM Order_T AS o, Order_Line_T AS ol, Product_T AS p WHERE o.Order_ID=ol.Order_ID .... ``` looking at the above query, you can see that there are at least two columns `Order_ID` in 2 tables: * o.Order\_ID * ol.Order\_ID There is also `Order_ID` column in this clause `ORDER BY Order_ID;` without an alias. The database doesn't know which order\_id column should use here - o.Order\_ID or ol.Order\_ID , and reports an error. Just use an alias in the order by clause: `ORDER BY o.Order_ID;`, this should fix the problem. Upvotes: 1 <issue_comment>username_2: You are missing the `JOIN`. While `WHERE` clauses can be acceptable, it is preferred in Access to use the `ON` keyword. Additionally, Access requires parentheses around multiple joins within the same statement. Try: ``` FROM (Order_T AS o INNER JOIN Order_Line_T AS ol ON o.Order_ID=ol.Order_ID) INNER JOIN Product_T AS p ON ol.Product_ID = p.Product_ID WHERE ol.Ordered_Quantity > 3 ORDER BY o.Order_ID; ``` Upvotes: 0
2018/03/16
584
2,446
<issue_start>username_0: I am creating a practice SQL Server database project, and I'm trying to enter text into a SQL Server database through a Windows Form. I'm not sure if my text data was really entered to my database. How do I view if it was entered? I'm a beginner so please try to use beginner SQL and VS vocabulary. I've tried going to show table data but that shows that no data was entered so I'm assuming its not working. Whenever I hit the button it just gives me no response so I'm not sure. ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; namespace DBHotel { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\<NAME>\\source\\repos\\DBHotel\\DBHotel\\Hotel.mdf;Integrated Security=True"; private void instBttn_Click(object sender, EventArgs e) { string nameQuery = textInst.Text; using(SqlConnection conn = new SqlConnection(connectionString)) { using(SqlCommand cmd = new SqlCommand(nameQuery, conn)) { conn.Open(); cmd.CommandText = "INSERT INTO Customers(name) VALUES(@nameQuery)"; cmd.Parameters.AddWithValue("nameQuery", nameQuery); cmd.ExecuteNonQuery(); } } } } } ``` Help is very much appreciated, thanks!<issue_comment>username_1: I know this is nonintuitive but try using the @ inside your AddWithValue: ``` cmd.Parameters.AddWithValue("@nameQuery", nameQuery); ``` Upvotes: 2 <issue_comment>username_2: ***EDIT: WARNING The below solution is at risk of sql injection, and is highly discouraged.*** As you are using direct query in instead of using stored procedure, you can't pass parameter to SQL. Instead of passing parameter try using `cmd.CommandText = "INSERT INTO Customers(name) VALUES('" + nameQuery + "')";` this means we are just concatenating the value of variable "nameQuery" in the query itself. so no need of below statement `cmd.Parameters.AddWithValue("nameQuery", nameQuery);` Upvotes: -1
2018/03/16
702
2,321
<issue_start>username_0: ``` * Smokey * Teddy ``` how do I change those class names here? I tried; ``` document.querySelectorAll('li').className = "corgitype" ``` and `document.querySelectorAll('li').classList = "corgitype"` but nothing changes. `corgitype` is the new class name that I want to overwrite on `bearname`<issue_comment>username_1: You need to iterate over the results of the query which returns a node list - note that if you are setting more than one class on the li's then this will overwrite all classes. Incidentally - if its only stylnig you are trying to do - then you can get to the li's without a class at all in the css - ul > li {//css style rules} so classes may not even be needed. EDIT - I have added a bit of extra fluff into this to allow toggling of the classes and styles -a bit more verbose - but easier to see the effect of the class name change. ```js function changeClass(value){ var listItems = document.querySelectorAll('li'); var index = parseInt(value); var type; index%2 == 0 ? type = "corgitype" : type = "bearname" for(i=0;i ``` ```css .bearname {color:blue} .corgitype {color: red} ``` ```html * Smokey * Teddy --- Click to toggle classes ``` Upvotes: 1 <issue_comment>username_2: querySelectorAll returns a static collection. You need to iterate this collection and can use `className` which will replace the existing one ```js document.querySelectorAll('li').forEach(function(item) { item.className = 'corgitype'; }) ``` ```css .corgitype { color: green; } ``` ```html * Smokey * Teddy ``` Upvotes: 2 <issue_comment>username_3: You can use jQuery to accomplish this. You must include jQuery in your project or page to utilize its functionality. A tutorial for doing that exists [here](https://www.w3schools.com/jquery/jquery_get_started.asp). Once you have jQuery added, the easiest way to accomplish what you're after would be: ``` $('.bearname').addClass('corgitype').removeClass('bearname'); ``` Upvotes: -1 <issue_comment>username_4: ``` .classa { color:red; } .classb { color:blue; } function change() { var list = document.getElementsByTagName("li"); for (var i=0; i<list.length; i++) { var el = list[i]; el.classList.remove('classa') ; el.classList.add('classb') ; } } - aaa - bbb change ``` Upvotes: 0
2018/03/16
1,189
3,653
<issue_start>username_0: My goal is to create a nav bar, perfectly centered horizontally at the top of a screen, with some text in the left hand corner. I have seen a lot of questions/solutions to horizontal centering, but I'd like to understand how I can 'ignore' the elements to the left or right of what I'm trying to center rather than using the remaining available space. [![Here is what it looks like right now](https://i.stack.imgur.com/Rz1BS.png)](https://i.stack.imgur.com/Rz1BS.png) ```css body { font-size: 1rem; margin: 0; } .centerable { float: left; position: relative; top: .5rem; width: 80%; } h3 { color: darkslategray; display: inline; float: left; font-size: 2rem; margin: 5px 0; } li { background-color: slategray; border: slategray solid .2rem; border-radius: .1rem; color: white; float: left; list-style-type: none; margin: -.1rem; padding: .5rem .5rem; position: relative; right: 50%; } ul { float: left; left: 50%; margin: 0; padding: 0; position: relative; } #topbar { background-color: #fff2ee; box-shadow: 1px 2px #DBCFCB;; font-family: 'IBM Plex Mono', monospace; overflow: auto; padding: 10px 5px; text-align: center; } ``` ```html See Your Code ### Code Writer * HTML * CSS * JavaScript * Display ```<issue_comment>username_1: Hope this will help you ```css body { font-size: 1rem; margin: 0; } .centerable { position: relative; top: .5rem; overflow: hidden; } ul { margin: 0; padding: 0; position: relative; display: inline-block; } li { background-color: slategray; border: slategray solid .2rem; border-radius: 0; color: white; float: left; list-style-type: none; padding: .5rem .5rem; position: relative; } h3 { color: darkslategray; display: inline; float: left; font-size: 2rem; margin: 5px 0; } #topbar { background-color: #fff2ee; box-shadow: 1px 2px #DBCFCB;; font-family: 'IBM Plex Mono', monospace; overflow: auto; padding: 10px 5px; text-align: center; } ``` ```html See Your Code ### Code Writer * HTML * CSS * JavaScript * Display ``` Upvotes: 0 <issue_comment>username_2: I hope this answer will be helpful for you ```css body { font-size: 1rem; margin: 0; } .centerable { float: left; position: relative; top: .5rem; width: 80%; } h3 { color: darkslategray; display: inline; float: left; font-size: 2rem; margin: 5px 0; } li { background-color: slategray; border: slategray solid .2rem; border-radius: .1rem; color: white; float: left; list-style-type: none; margin: -.1rem; padding: .5rem .5rem; position: relative; right: 50%; } ul { float: left; left: 50%; margin: 0; padding: 0; position: relative; } #topbar { background-color: #fff2ee; box-shadow: 1px 2px #DBCFCB;; font-family: 'IBM Plex Mono', monospace; overflow: auto; padding: 10px 5px; text-align: center; } .centerable{ position:fixed; margin: auto; width: 100%; } ``` ```html See Your Code ### Code Writer * HTML * CSS * JavaScript * Display ``` Upvotes: 0 <issue_comment>username_3: You can take the h3 element out of the document flow by using position absolute. If it is not in the document flow, it will not have any impact on the centering of the rest of the elements. Upvotes: 1
2018/03/16
901
2,615
<issue_start>username_0: I'm new to python can anyone help me with this. For example, I have a data frame of ``` data = pd.DataFrame({'a': [1,1,2,2,2,3], 'b': [12,22,23,34,44,55], 'c'['a','','','','c',''], 'd':['','b','b','a','a','']}) ``` I want to sum a and ignore the different in b ``` data = ({'a':[1,2,3],'c':['a','c',''],'d':['b','baa','']}) ``` How can I do this?<issue_comment>username_1: Hope this will help you ```css body { font-size: 1rem; margin: 0; } .centerable { position: relative; top: .5rem; overflow: hidden; } ul { margin: 0; padding: 0; position: relative; display: inline-block; } li { background-color: slategray; border: slategray solid .2rem; border-radius: 0; color: white; float: left; list-style-type: none; padding: .5rem .5rem; position: relative; } h3 { color: darkslategray; display: inline; float: left; font-size: 2rem; margin: 5px 0; } #topbar { background-color: #fff2ee; box-shadow: 1px 2px #DBCFCB;; font-family: 'IBM Plex Mono', monospace; overflow: auto; padding: 10px 5px; text-align: center; } ``` ```html See Your Code ### Code Writer * HTML * CSS * JavaScript * Display ``` Upvotes: 0 <issue_comment>username_2: I hope this answer will be helpful for you ```css body { font-size: 1rem; margin: 0; } .centerable { float: left; position: relative; top: .5rem; width: 80%; } h3 { color: darkslategray; display: inline; float: left; font-size: 2rem; margin: 5px 0; } li { background-color: slategray; border: slategray solid .2rem; border-radius: .1rem; color: white; float: left; list-style-type: none; margin: -.1rem; padding: .5rem .5rem; position: relative; right: 50%; } ul { float: left; left: 50%; margin: 0; padding: 0; position: relative; } #topbar { background-color: #fff2ee; box-shadow: 1px 2px #DBCFCB;; font-family: 'IBM Plex Mono', monospace; overflow: auto; padding: 10px 5px; text-align: center; } .centerable{ position:fixed; margin: auto; width: 100%; } ``` ```html See Your Code ### Code Writer * HTML * CSS * JavaScript * Display ``` Upvotes: 0 <issue_comment>username_3: You can take the h3 element out of the document flow by using position absolute. If it is not in the document flow, it will not have any impact on the centering of the rest of the elements. Upvotes: 1
2018/03/16
707
2,506
<issue_start>username_0: I want to set the same weight for parts of positive samples. However,`tf.nn.weighted_cross_entropy_with_logits` can only set the weight for all positive samples in my opinion. for example, in the ctr predicition, I want set 10 weights for the order samples, and the weight of click samples and the unclick sample is still 1. Here is my unweighted code ``` def my_model(features, labels, mode, params): net = tf.feature_column.input_layer(features, params['feature_columns']) for units in params['hidden_units']: net = tf.layers.dense(net, units=units, activation=params["activation"]) logits = tf.layers.dense(net, params['n_classes'], activation=None) predicted_classes = tf.argmax(logits, 1) if mode == tf.estimator.ModeKeys.PREDICT: predictions = { 'class_ids': predicted_classes, #predicted_classes[:, tf.newaxis], 'probabilities': tf.nn.softmax(logits), 'logits': logits, } return tf.estimator.EstimatorSpec(mode, predictions=predictions) loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits) metrics = {'auc': tf.metrics.auc(labels=labels, predictions=tf.nn.softmax(logits)[:,1])} if mode == tf.estimator.ModeKeys.EVAL: return tf.estimator.EstimatorSpec(mode, loss=loss, eval_metric_ops=metrics) assert mode == tf.estimator.ModeKeys.TRAIN optimizer = tf.train.AdagradOptimizer(learning_rate=0.1) train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step()) return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op) ``` Train ----- ``` train_input_fn = tf.estimator.inputs.pandas_input_fn(x=data_train, y=data_train_click, batch_size = 1024, num_epochs=1, shuffle=False) classifier.train(input_fn=train_input_fn) ``` Here `data_train_click` is a Series, which the click samples are 1 and the unclicked samples are 0. And I have a Series named `data_train_order`, which the order samples are 1 and the others are 0<issue_comment>username_1: The easiest way to do this is by using keras <https://keras.io/models/model/> The fit function has a sample\_weight parameter. Upvotes: 1 <issue_comment>username_2: You can weigh each samples differently by passing a weight parameter to the loss function which is a tensor of shape [batch\_size] containing corresponding weights for each samples. ``` loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits, weights=weights) ``` Upvotes: 0
2018/03/16
1,127
3,960
<issue_start>username_0: So I was following a simple react/firebase chat room on youtube: <https://www.youtube.com/watch?v=or3Gp29o6fE> as a reference to what I'm doing with my project. I am making a bug/issue tracker, so that a user can enter a station #, bug/issue, then a description of it. I keep getting an error: > > Error: Reference.set failed: First argument contains undefined in property 'bugs.0.station' > > > And I'm not sure how it's undefined if it's just an id number. My end goal at this point in time is to be able to add and remove a bug/issue by id. ``` import React, { Component } from 'react'; import { Button } from "react-bootstrap"; import withAuthorization from './withAuthorization'; import * as firebase from 'firebase'; class HomePage extends Component { constructor(props,context) { super(props,context); this.stationBug = this.stationBug.bind(this) this.issueBug = this.issueBug.bind(this) this.descBug = this.descBug.bind(this) this.submitBug = this.submitBug.bind(this) this.state = { station: '', bug: '', desc: '', bugs: [] } } componentDidMount() { firebase.database().ref('bugs/').on ('value', (snapshot) => { const currentBugs = snapshot.val() if (currentBugs != null) { this.setState({ bugs: currentBugs }) } }) } stationBug(event) { this.setState({ station: event.target.value }); } issueBug(event) { this.setState({ bug: event.target.value }); } descBug(event) { this.setState({ desc: event.target.value }); } submitBug(event) { const nextBug = { id: this.state.bugs.length, station: this.state.title, bug: this.state.bug, desc: this.state.desc } firebase.database().ref('bugs/'+nextBug.id).set(nextBug) } render() { return ( { this.state.bugs.map((bug, i) => { return ( - {bug.station} ) }) } Enter Bug ); } } export default withAuthorization()(HomePage); ```<issue_comment>username_1: The error is quite explicit: > > Reference.set failed: First argument contains undefined in property 'bugs.0.station' > > > Since there's only one call to `Reference.set()` in your code, the problem must be here: ``` submitBug(event) { const nextBug = { id: this.state.bugs.length, station: this.state.title, bug: this.state.bug, desc: this.state.desc } firebase.database().ref('bugs/'+nextBug.id).set(nextBug) } ``` So it seems that `this.state.title` is `undefined`. Most likely you wanted to use `station: this.state.station`. Upvotes: 1 <issue_comment>username_2: Just looks like a typo. You're referencing `this.state.title` instead of `this.state.station` in your `submitBug` method. ``` class HomePage extends Component { constructor(props) { super(props); this.state = { station: '', bug: '', desc: '', bugs: [] } } componentDidMount() { firebase.database().ref('bugs/').on ('value', (snapshot) => { const currentBugs = snapshot.val() if (currentBugs != null) { this.setState({ bugs: currentBugs }) } }) } stationBug=(event)=>{ this.setState({ station: event.target.value }); } issueBug=(event)=>{ this.setState({ bug: event.target.value }); } descBug=(event)=>{ this.setState({ desc: event.target.value }); } submitBug=(event)=>{ const nextBug = { id: this.state.bugs.length, station: this.state.title, bug: this.state.bug, desc: this.state.desc } firebase.database().ref('bugs/'+nextBug.id).set(nextBug) } render() { return ( {this.state.bugs.map(bug => - {bug.station} )} Enter Bug ); } } export default withAuthorization()(HomePage); ``` Upvotes: 3 [selected_answer]
2018/03/16
905
3,162
<issue_start>username_0: I am new to coding & I am taking ruby on rails online class. I have followed the lecture and documented everything but I am getting "NonMethod" error. Here what I have in my file **Controller** ``` class CoursesController < ApplicationController def index @search_term = 'jhu' @courses = Coursera.for(@search_term) end end ``` **Model** ``` class Coursera include HTTParty base_uri 'https://api.coursera.org/api/catalog.v1/courses' default_params fields: "smallIcon,shortDescription", q: "search" format :[enter image description here][1]json def self.for term get("", query: { query: term})["elements"] end end ``` **Views** ``` Searching for - <%= @search\_term %> ==================================== | Image | Name | Description | | --- | --- | --- | <% @courses.each do |course| %> |> <%= image\_tag(course["smallIcon"])%> | <%= course["name"] %> | <%= course["shortDescription"] %> | <% end %> ``` These are the messages I am getting NoMethodError in Courses#index Showing /Users/Dohe/my\_app/app/views/courses/index.html.erb where line #11 raised: undefined method `each' for nil:NilClass Can any help me with what I am doing wrong Ruby 2.2.9 and Rails 4.2.3<issue_comment>username_1: The error is quite explicit: > > Reference.set failed: First argument contains undefined in property 'bugs.0.station' > > > Since there's only one call to `Reference.set()` in your code, the problem must be here: ``` submitBug(event) { const nextBug = { id: this.state.bugs.length, station: this.state.title, bug: this.state.bug, desc: this.state.desc } firebase.database().ref('bugs/'+nextBug.id).set(nextBug) } ``` So it seems that `this.state.title` is `undefined`. Most likely you wanted to use `station: this.state.station`. Upvotes: 1 <issue_comment>username_2: Just looks like a typo. You're referencing `this.state.title` instead of `this.state.station` in your `submitBug` method. ``` class HomePage extends Component { constructor(props) { super(props); this.state = { station: '', bug: '', desc: '', bugs: [] } } componentDidMount() { firebase.database().ref('bugs/').on ('value', (snapshot) => { const currentBugs = snapshot.val() if (currentBugs != null) { this.setState({ bugs: currentBugs }) } }) } stationBug=(event)=>{ this.setState({ station: event.target.value }); } issueBug=(event)=>{ this.setState({ bug: event.target.value }); } descBug=(event)=>{ this.setState({ desc: event.target.value }); } submitBug=(event)=>{ const nextBug = { id: this.state.bugs.length, station: this.state.title, bug: this.state.bug, desc: this.state.desc } firebase.database().ref('bugs/'+nextBug.id).set(nextBug) } render() { return ( {this.state.bugs.map(bug => - {bug.station} )} Enter Bug ); } } export default withAuthorization()(HomePage); ``` Upvotes: 3 [selected_answer]
2018/03/16
394
1,333
<issue_start>username_0: Here is my code ``` ``` Here mat-error-0 will change to mat-error-1 on page refresh and mat-error-1 will change to mat-error-2 and so on.. There is no unique class or role attribute here that i can take here. Please advise.<issue_comment>username_1: As long as innerHTML stays consistent after refreshing the page, you can use Xpath to find the element. e.g. the following Xpath can locate *To date* webElement. ``` //mat-error[contains(.,'valid To date')] ``` Upvotes: 0 <issue_comment>username_2: Use the following xpath ``` //mat-error[text()='Please enter a valid To date'] //mat-error[text()='Please enter a valid From date'] ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: Use Following Xpath for dynamically changing id. ``` //mat-error[starts-with(@id,'mat-error')] ``` Upvotes: 0 <issue_comment>username_4: As per the *HTML* you have shared, as the `id` keeps changing so you have to construct dynamic *xpath* to identify both the elements as follows : * Element with text as **Please enter a valid To date** : ``` //mat-error[@class='mat-error' and starts-with(@id,'mat-error') and contains(.,'To')] ``` * Element with text as **Please enter a valid From date** : ``` //mat-error[@class='mat-error' and starts-with(@id,'mat-error') and contains(.,'From')] ``` Upvotes: 0
2018/03/16
360
1,234
<issue_start>username_0: I'm developing a drop-down form with values from a database. My question is how can I display values from the database to the `drop-down` without displaying the same values. I have 2 data in my database which consist of the same value `(Paid)` but when I display it on my dropdown it shows 2 "Paid" values instead of one. Thank you Here is my Model : ``` public function getLiveEvents(){ $query = $this->db->get('live_events'); return $query->result(); } ``` Here is my View : ``` Ticket type: php foreach ($sort as $sorts) { echo '<option value="' . $sorts-live\_type . '">' . $sorts->live\_type.''; } ?> ```<issue_comment>username_1: One solution is that you could filter the data on the query : ``` public function getLiveEvents(){ $this->db->distinct(); $this->db->select('live_type'); $query = $this->db->get('live_events'); return $query->result(); } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: This should work - ``` public function getLiveEvents(){ $this->db->distinct(); $this->db->select('live_type'); $this->db->group_by('live_type'); $query = $this->db->get('live_events'); return $query->result(); } ``` Upvotes: 1
2018/03/16
416
1,289
<issue_start>username_0: I have a table as below : [![Table](https://i.stack.imgur.com/8Tpum.png)](https://i.stack.imgur.com/8Tpum.png) How can I craft a SQL `select` statement so that `MIN AND MAX EVENT DATE` groups results by `FLAG (0,1)`? So the result would be: [![Result](https://i.stack.imgur.com/wJIEs.png)](https://i.stack.imgur.com/wJIEs.png)<issue_comment>username_1: Just do conditional aggregation with use of *window function* ``` SELECT card_no, descr_reader, max(CASE WHEN flag = 0 THEN event_date END) date_in, max(CASE WHEN flag = 1 THEN event_date END) date_out FROM ( SELECT *, COUNT(flag) OVER (PARTITION BY flag ORDER BY id) Seq FROM table t )t GROUP BY card_no, descr_reader, Seq ``` Upvotes: 2 <issue_comment>username_2: An alternative if Window function does not work: ``` SELECT t1.card_no, t1.descr_reader, t1.event_date date_in, (select top 1 event_date from test t2 where t2.card_no = t1.card_no and t2.reader_no = t1.reader_no and t2.descr_reader = t1.descr_reader and t2.event_date > t1.event_date and t2.flag = 1 order by t2.event_date ) as date_out FROM test t1 WHERE t1.flag = 0 ``` Upvotes: 2 [selected_answer]
2018/03/16
536
1,575
<issue_start>username_0: I want to merge 2 csv file with a similar column but different header name. a.csv: ``` id name country 1 Cyrus MY 2 May US ``` b.csv: ``` user_id gender 1 female 2 male ``` What I need is, c.csv: ``` id name country gender 1 Cyrus MY female 2 May US male ``` But the result I get when I use the below code ``` import csv import pandas as pd df1 = pd.read_csv('a.csv') df2 = pd.read_csv('b.csv') df3 = pd.merge(df1,df2, left_on=['id'],right_on=['user_id'], how='outer') df3.to_csv('c.csv',index=False) ``` The result I get: ``` id name country user_id gender 1 Cyrus MY 1 female 2 May US 2 male ```<issue_comment>username_1: Just do conditional aggregation with use of *window function* ``` SELECT card_no, descr_reader, max(CASE WHEN flag = 0 THEN event_date END) date_in, max(CASE WHEN flag = 1 THEN event_date END) date_out FROM ( SELECT *, COUNT(flag) OVER (PARTITION BY flag ORDER BY id) Seq FROM table t )t GROUP BY card_no, descr_reader, Seq ``` Upvotes: 2 <issue_comment>username_2: An alternative if Window function does not work: ``` SELECT t1.card_no, t1.descr_reader, t1.event_date date_in, (select top 1 event_date from test t2 where t2.card_no = t1.card_no and t2.reader_no = t1.reader_no and t2.descr_reader = t1.descr_reader and t2.event_date > t1.event_date and t2.flag = 1 order by t2.event_date ) as date_out FROM test t1 WHERE t1.flag = 0 ``` Upvotes: 2 [selected_answer]
2018/03/16
2,013
6,689
<issue_start>username_0: I am trying to store information for the delivery object on the truck itself. I can't seem to access the delivery, even though the foreign key is set on the belongs\_to attribute of the model. Thereafter, I should be able to access the delivery\_order nested attribute inside of the rails view. What I want to do is plot on Google maps, the distance between the truck object itself and the delivery\_order object. The code that I wrote is below. Error: ``` >> @truck.delivery NoMethodError: undefined method `delivery' for # Did you mean? delivery\_id from (irb):51 ``` UPDATE 2 After setting the truck model to has\_one :delivery, I get the error below. ``` #]> >> @truck = Truck.find(3) # Truck Load (1.0ms) SELECT "trucks".\* FROM "trucks" WHERE "trucks"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]] >> @truck.delivery Delivery Load (1.0ms) SELECT "deliveries".\* FROM "deliveries" WHERE "deliveries"."truck\_id" = $1 LIMIT $2 [["truck\_id", 3], ["LIMIT", 1]] nil ``` delivery.rb ``` class Delivery < ApplicationRecord belongs_to :truck, class_name: 'Truck', foreign_key: :delivery_id, optional: true has_one :delivery_order has_one :order_tracker has_many :breads after_create :build_order_tracker # after_create :decrement_bread_stock accepts_nested_attributes_for :delivery_order end ``` truck.rb ``` class Truck < ApplicationRecord belongs_to :warehouse, optional: true has_many :deliveries has_paper_trail on: [:update, :destroy] geocoded_by :truck_location, :latitude => :lat, :longitude => :lon after_validation :geocode, if: -> (obj) {obj.current_street_address.present? && obj.current_street_address_changed?} def truck_location [current_street_address, current_state, current_country].compact.join(', ') end end ``` truck schema ``` create_table "trucks", force: :cascade do |t| t.datetime "loaded_date" t.string "delivery_total" t.string "lon" t.string "lat" t.bigint "warehouse_id" t.bigint "delivery_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "current_street_address" t.string "current_city" t.string "current_state" t.string "current_country" t.string "truck_driver_name" t.string "current_location_title" t.index ["delivery_id"], name: "index_trucks_on_delivery_id" t.index ["warehouse_id"], name: "index_trucks_on_warehouse_id" end ``` trucks\_controller.rb ``` class TrucksController < ApplicationController before_action :set_truck, only: %i[show edit update destroy] before_action :authenticate_manager! # GET /trucks # GET /trucks.json def index @trucks = Truck.all end # GET /trucks/1 # GET /trucks/1.json def show; end # GET /trucks/new def new @truck = Truck.new @deliveries = Delivery.all end # GET /trucks/1/edit def edit; end # POST /trucks # POST /trucks.json def create @truck = current_manager.warehouse.trucks.build(truck_params) respond_to do |format| if @truck.save format.html { redirect_to @truck, notice: 'Truck was successfully created.' } format.json { render :show, status: :created, location: @truck } else format.html { render :new } format.json { render json: @truck.errors, status: :unprocessable_entity } end end end # PATCH/PUT /trucks/1 # PATCH/PUT /trucks/1.json def update respond_to do |format| if @truck.update(truck_params) format.html { redirect_to @truck, notice: 'Truck was successfully updated.' } format.json { render :show, status: :ok, location: @truck } else format.html { render :edit } format.json { render json: @truck.errors, status: :unprocessable_entity } end end end # DELETE /trucks/1 # DELETE /trucks/1.json def destroy @truck.destroy respond_to do |format| format.html { redirect_to trucks_url, notice: 'Truck was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_truck @truck = Truck.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def truck_params params.require(:truck).permit(:delivery_total, :lon, :lat, :delivery_id, :loaded_date, :truck_driver_name, :current_location_title, :current_street_address, :current_city, :current_state, :current_country) end end ``` trucks \_form.html.erb ``` <%= simple\_form\_for(@truck) do |f| %> <%= f.error\_notification %> Loaded Date (Click Box Below) <%= f.input :loaded\_date, as: :date\_time\_picker, class: 'form-control', placeholder: "Tap to view calendar ", label: false %> <%= f.input :delivery\_total, class: 'form-control' %> <%= f.input :current\_location\_title, class: 'form-control' %> <%= f.input :truck\_driver\_name, class: 'form-control btn btn-outline-primary' %> <%= f.input :current\_street\_address, class: 'form-control' %> <%= f.input :current\_city, class: 'form-control' %> <%= f.input :current\_state, class: 'form-control' %> <%= f.input :current\_country, class: 'form-control' %> <%= f.input :delivery\_id, collection: @deliveries, :label\_method => lambda {|delivery| "Estimated Delivery Date: #{delivery.delivery\_date} | Order Id: #{delivery.id}"}, value\_method: :id, label: "Delivery Jobs", include\_blank: false, prompt: 'Add a delivery to the truck'%> <%= f.button :submit, class: 'btn btn-outline-success' %> <% end %> $(document).on('turbolinks:load', function () { $('.form\_datetime').datetimepicker({ autoclose: true, todayBtn: true, pickerPosition: "bottom-left", format: 'mm-dd-yyyy hh:ii' }); }); ```<issue_comment>username_1: As per your association definition in truck.rb and delivery.rb, the way to fetch deliveries corresponding to particular truck is: Assuming @truck is an instance of Truck class ``` @truck.deliveries ``` This will give ActiveRecord::Associations::CollectionProxy as a result. **Note:** @truck.delivery will not work as in truck.rb association is defined as has\_many :deliveries Upvotes: 0 <issue_comment>username_2: The correct relations for your truck schema are: ``` class Truck < ApplicationRecord belongs_to :delivery class Delivery < ApplicationRecord has_many :trucks ``` If you want to have many deliveries per truck, consider following schema: ``` create_table "deliveries", force: :cascade do |t| t.bigint "truck_id" class Truck < ApplicationRecord has_many :deliveries class Delivery < ApplicationRecord belongs_to :truck ``` Upvotes: 1
2018/03/16
555
1,680
<issue_start>username_0: If I have an object like this ``` const myobj ={ "Computer" : [{ "file" : MyDirectory/A/text1.txt", "line": [23,56]}, {"file" :"MyDirectory/B/text5.txt", "line" :[32,91]}] , "Book" : {"file": MyDirectory/A/text1.txt", "line": [13,46]} } ``` and suppose a function yields something like ``` {"Computer" : [{ "file" : MyDirectory/A/text1.txt", "line": [3,6]} ``` Is there a way that I can concatenate this to the list that corresponds to the "computer" key in "myobj" ? i-e can I update my obj to { "Computer" : [{ "file" : MyDirectory/A/text1.txt", "line": [23,56]}, {"file" :"MyDirectory/B/text5.txt", "line" :[32,91]},{ "file" : MyDirectory/A/text1.txt", "line": [3,6]} ] , "Book" : {"file": MyDirectory/A/text1.txt", "line": [13,46]} } ?<issue_comment>username_1: As per your association definition in truck.rb and delivery.rb, the way to fetch deliveries corresponding to particular truck is: Assuming @truck is an instance of Truck class ``` @truck.deliveries ``` This will give ActiveRecord::Associations::CollectionProxy as a result. **Note:** @truck.delivery will not work as in truck.rb association is defined as has\_many :deliveries Upvotes: 0 <issue_comment>username_2: The correct relations for your truck schema are: ``` class Truck < ApplicationRecord belongs_to :delivery class Delivery < ApplicationRecord has_many :trucks ``` If you want to have many deliveries per truck, consider following schema: ``` create_table "deliveries", force: :cascade do |t| t.bigint "truck_id" class Truck < ApplicationRecord has_many :deliveries class Delivery < ApplicationRecord belongs_to :truck ``` Upvotes: 1
2018/03/16
953
3,091
<issue_start>username_0: Current it seems we cannot run both **Neo4J Server** and **Gremlin Server** at the same time. Is there any way to have run both? 1. NEO4J is running and I try to start to Gremlin Server then I get the following error > > java.lang.RuntimeException: GraphFactory could not instantiate this > Graph implementation [class > org.apache.tinkerpop.gremlin.neo4j.structure.Neo4jGraph].......................(truncated) > > > 2. Gremlin Server is running and I try to start NEO4J Server then I get the following error > > Caused by: org.neo4j.kernel.StoreLockException: Store and its lock > file has been locked by another process: > /home/galaxia/Documents/neo4j-gremlin/data/databases/graph.db/store\_lock. > Please ensure no other process is using this database, and that the > directory is writable (required even for read-only access) > > > --- Versions * Neo4J 3.3.1 * Gremlin 3.3.1<issue_comment>username_1: You cannot run them together that way (i.e. embedded mode), but it should be possible to run them together, if you either: 1. Configure the Neo4j graph in Gremlin Server to use HA mode as described [here](http://tinkerpop.apache.org/docs/current/reference/#_high_availability_configuration) 2. Configure the Neo4j graph in Gremlin Server to use the Bolt implementation found [here](https://github.com/SteelBridgeLabs/neo4j-gremlin-bolt) 3. Enable the Bolt protocol in the Neo4j properties file provided to Gremlin Server. As an example of the third option, given the default Gremlin Server packaged configuration files for Neo4j, you can edit `conf/neo4j-empty.properties` to include: ``` gremlin.graph=org.apache.tinkerpop.gremlin.neo4j.structure.Neo4jGraph gremlin.neo4j.directory=/tmp/neo4j gremlin.neo4j.conf.dbms.connector.0.type=BOLT gremlin.neo4j.conf.dbms.connector.0.enabled=true gremlin.neo4j.conf.dbms.connector.0.address=localhost:7687 ``` and then start Gremlin Server with `bin/gremlin-server.sh conf/gremlin-server-neo4j.yaml` at which point you can use standard TinkerPop drivers as well as standard Bolt connectivity against the same graph instance. Upvotes: 3 [selected_answer]<issue_comment>username_2: I realize it has been a while, but I *finally* figured this out and thought others should know. As <NAME> said, you can use the Bolt implementation. To configure this for Gremlin Server, use the included `gremlin-server-neo4j.yaml` file and make the following change: ``` graphs: { graph: conf/neo4j-bolt.properties} ``` Then create the `neo4j-bolt.properties` file with this content: ``` gremlin.graph=com.steelbridgelabs.oss.neo4j.structure.Neo4JGraph #neo4j.graph.name=graph.db neo4j.identifier=dummy neo4j.url=bolt://localhost:7687 neo4j.username=neo4j neo4j.password= neo4j.readonly=false neo4j.vertexIdProvider=com.steelbridgelabs.oss.neo4j.structure.providers.Neo4JNativeElementIdProvider neo4j.edgeIdProvider=com.steelbridgelabs.oss.neo4j.structure.providers.Neo4JNativeElementIdProvider ``` Remember to replace the password, and any other property with the correct values. Upvotes: 2
2018/03/16
2,080
7,894
<issue_start>username_0: I used this method because I am storing an array of classified messages, I would like to vividly understand why it doesn't update. Here's the db.js: ``` const mongoose = require('mongoose'); const Schema = mongoose.Schema; const ObjectId = mongoose.Types.ObjectId; const usersessionSchema = new Schema({ fb_id: String, fb_name: String, fb_profpic: String, message_body: [ { message: String, message_type: String, timestamp: String } ], admin: Boolean, branch: String }); const model = (prefix) => { prefix = prefix || ''; console.log(prefix); if (prefix.length > 0) { return mongoose.model(prefix + "-usersessions", usersessionSchema); } else { return new Error('Undefined collection prefix!'); } } /** Push message into message body*/ module.exports.pushsession = async(model, id, data) => { return new Promise((resolve, reject) => { console.log(data); model.findOneAndUpdate({fb_id: id}, {$push: {data}},{safe: true}) .then(res => { console.log(res); / resolve(res); }) .catch(err => { reject(err); console.log(err); throw err; }); }); } ``` Here's the controller.js: ``` /** Push usersession message */ module.exports.pushsession = async(req, res, next) => { try { //jwt.validateToken(req); var en = "en"; var dateEn = moment().locale(en); format = "MM/DD/YYYY h:mm:ss A"; //h:mm:ss.SSS if you want miliseconds var datetime_now = dateEn.format(format); console.log(datetime_now); var request = { message_body: { message: req.body.message, message_type: req.body.message_type, timestamp: datetime_now } }; const model = usersessionDB(req.query['client']); const id = req.body.fb_id; const result = await usersessionDB.pushsession(model, id, request); if (result) { response.success(res, next, result, 200, response.HTTP_STATUS_CODES.ok); } else { response.failure(res, next, { message: 'ID does not exist' }, 404, response.HTTP_STATUS_CODES.not_found); } } catch (err) { response.failure(res, next, err, 500, response.HTTP_STATUS_CODES.internal_server_error); } } ``` Here's the route.js: ``` const controller = require('../controller/usersession-controller'); module.exports = (server) => { server.post('/api/session', controller.create); server.get('/api/session', controller.list); server.get('/api/session/:id', controller.get); server.put('/api/session/:id', controller.update); server.del('/api/session/:id', controller.delete); server.put('/api/pushsession', controller.pushsession); } ``` Visually, if you run this using postman, you can see that it display the one I want to search and update [Result of the postman](https://i.stack.imgur.com/9fRVS.png) What I want to happen is to insert another set of array inside that message\_body [Data I've inserting](https://i.stack.imgur.com/dzP2G.png) [My desired output](https://i.stack.imgur.com/zFFjL.png) This code is working without that promise something, but in my project it is needed so I can't remove that thing.<issue_comment>username_1: So, based on : > > This code is working without that promise something > > > i can point a thing or two, in **db.js** ``` module.exports.pushsession = async(model, id, data) => { return new Promise((resolve, reject) => { ``` you don't need `async` since you're returning a `promise` so replace this `async(model, id, data) => {` with `(model, id, data) => {` and since you're returning a `promise` and removed `async` , you don't need the `await` on the other side ( **controller.js** ), so this ``` const result = await usersessionDB.pushsession(model, id, request); if (result) { response.success(res, next, result, 200, response.HTTP_STATUS_CODES.ok); } else { ``` should be ``` usersessionDB.pushsession(model, id, request).then( (result) => { // when resolved response.success(res, next, result, 200, response.HTTP_STATUS_CODES.ok); }, (err) => { // when rejected response.failure(res, next, { message: 'ID does not exist' }, 404, response.HTTP_STATUS_CODES.not_found); }); ``` this is a comparison between `async/await` and `promises` : [Javascript Promises vs Async Await. Difference?](https://stackoverflow.com/questions/34401389/javascript-promises-vs-async-await-difference) and here's some good examples of using promises : <https://medium.com/dev-bits/writing-neat-asynchronous-node-js-code-with-promises-32ed3a4fd098> i think your `$push` is ok but you already said > > This code is working without that promise something > > > i hope this helps and Good luck :) Upvotes: 1 <issue_comment>username_2: I tried cleaning my code here's the controller.js: ``` /** Push usersession message */ module.exports.pushsession = async (req, res, next) => { try { //jwt.validateToken(req); var en = "en"; var dateEn = moment().locale(en); format = "MM/DD/YYYY h:mm:ss A"; //h:mm:ss.SSS if you want miliseconds var datetime_now = dateEn.format(format); console.log(datetime_now); var data = { message: req.body.message, message_type: req.body.message_type, timestamp: datetime_now }; const model = usersessionDB(req.query['client']); const id = req.body.fb_id; console.log(id); const result = await usersessionDB.pushsession(model, id, data).then( (result) => { // when resolved response.success(res, next, result, 200, response.HTTP_STATUS_CODES.ok); }, (err) => { // when rejected response.failure(res, next, { message: 'ID does not exist' }, 404, response.HTTP_STATUS_CODES.not_found); }); } catch (err) { response.failure(res, next, err, 500, response.HTTP_STATUS_CODES.internal_server_error); } } ``` Here's the db.js: ``` const mongoose = require('mongoose'); const Schema = mongoose.Schema; const ObjectId = mongoose.Types.ObjectId; const usersessionSchema = new Schema({ fb_id: String, fb_name: String, fb_profpic: String, message_body:[{ message: String, message_type: String, timestamp: String }], admin: Boolean, branch: String }); /** Push message into message body*/ module.exports.pushsession = async(model, id, data) => { console.log(data); return new Promise((resolve, reject) => { model.findOneAndUpdate({fb_id: id}, { $push: { message_body: data }}) .then(res => { console.log(res); resolve(res); }) .catch(err => { reject(err); console.log(err); throw err; }); }); } ``` Out of the blue after I tried to replace $push with $set then again I replace it with $push, it worked. I don't if there's a difference, or I miss something, feel free to point it out. Upvotes: 0
2018/03/16
599
2,413
<issue_start>username_0: [![enter image description here](https://i.stack.imgur.com/jo0WC.png)](https://i.stack.imgur.com/jo0WC.png) I need to change the position of compass from left to right in app.It always shows in left.Is it possible to change position?? ``` // change compass position try { assert mapFragment.getView() != null; final ViewGroup parent = (ViewGroup) mapFragment.getView().findViewWithTag("GoogleMapMyLocationButton").getParent(); parent.post(new Runnable() { @Override public void run() { try { for (int i = 0, n = parent.getChildCount(); i < n; i++) { View view = parent.getChildAt(i); RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) view.getLayoutParams(); // position on right bottom rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT); rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP,0); rlp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,0); rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); rlp.rightMargin = rlp.leftMargin; rlp.topMargin = 25; view.requestLayout(); } } catch (Exception ex) { ex.printStackTrace(); } } }); } catch (Exception ex) { ex.printStackTrace(); } ```<issue_comment>username_1: Here's the needed solution to align the Compass button on Top Right corner: ``` View compassButton = mMapView.findViewWithTag("GoogleMapCompass");//to access the compass button RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) compassButton.getLayoutParams(); rlp.addRule(RelativeLayout.ALIGN_PARENT_END); rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP); rlp.addRule(RelativeLayout.ALIGN_PARENT_START,0); rlp.topMargin = 50; ``` This will change it's `RelativeLayout` params to align to the Top Right corner. **Result:** [![enter image description here](https://i.stack.imgur.com/bvs4m.jpg)](https://i.stack.imgur.com/bvs4m.jpg) Upvotes: 3 <issue_comment>username_2: You may use GoogleMap.setPadding() method: for your compass position <https://developers.google.com/maps/documentation/android/map#map_padding> Upvotes: 0
2018/03/16
417
1,386
<issue_start>username_0: i'm making chat and i want to select the list of user's message like fb or twitter that user have sent or received. I've tried this query ``` SELECT DISTINCT * FROM message WHERE `userFrom` = 2 OR `userTo` = 2 ``` but it returned what in this photo Below is an image to explain my problem [![PROBLEM](https://i.stack.imgur.com/ysuvQ.png)](https://i.stack.imgur.com/ysuvQ.png) so i want to return last action between these user like below ![example](https://i.stack.imgur.com/ZNetO.png)<issue_comment>username_1: Here's the needed solution to align the Compass button on Top Right corner: ``` View compassButton = mMapView.findViewWithTag("GoogleMapCompass");//to access the compass button RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) compassButton.getLayoutParams(); rlp.addRule(RelativeLayout.ALIGN_PARENT_END); rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP); rlp.addRule(RelativeLayout.ALIGN_PARENT_START,0); rlp.topMargin = 50; ``` This will change it's `RelativeLayout` params to align to the Top Right corner. **Result:** [![enter image description here](https://i.stack.imgur.com/bvs4m.jpg)](https://i.stack.imgur.com/bvs4m.jpg) Upvotes: 3 <issue_comment>username_2: You may use GoogleMap.setPadding() method: for your compass position <https://developers.google.com/maps/documentation/android/map#map_padding> Upvotes: 0
2018/03/16
1,114
4,003
<issue_start>username_0: For the collection page (<https://bloomthis.co/collections/on-demand-blooms>), when each product is hovered on, the alternate image is displayed. The alternate image is the last image added in the product page. I'm working on to have a "Buy Now" button on top of the alternate image. Currently when I hover on a thumbnail, I can see the alternate image for a split second and the button is "exploded" to full size following the grid size. [![enter image description here](https://i.stack.imgur.com/zfk0l.png)](https://i.stack.imgur.com/zfk0l.png) What I want instead is for the button to be on top of the alternate image without covering the whole thumbnail area. Like this: [![enter image description here](https://i.stack.imgur.com/i9HS5.png)](https://i.stack.imgur.com/i9HS5.png) **Liquid Code** (button is in ) ``` {% if product.title contains "Subscription" %} [Send Now ![{{ product.featured_image.alt | escape }}]({{ product.featured_image.src | img_url: 'large' }}) ![{{ product.images.last.alt | escape }}]({{ product.images.last | img_url: 'large' }})]({{ product.url | within: collection }}) {% else %} [![{{ product.featured_image.alt | escape }}]({{ product.featured_image.src | img_url: 'large' }}) ![{{ product.images.last.alt | escape }}]({{ product.images.last | img_url: 'large' }}) ![{{ product.featured_image.alt | escape }}]({{ product.featured_image.src | img_url: 'large' }})]({{ product.url | within: collection }}) {% endif %} ``` **CSS** ``` //Reveal module .hidden { display: block !important; visibility: visible !important;} .btn { font-family: 'Playfair Display'; letter-spacing: 2px; text-transform: uppercase; display: inline-block; padding: 8px 10px; width: auto; margin: 0; line-height: 1.42; font-weight: bold; text-align: center; vertical-align: bottom; white-space: nowrap; cursor: pointer; border: 1px solid transparent; @include user-select(none); -webkit-appearance: none; -moz-appearance: none; border-radius: $radius; /*======== Set primary button colors - can override later ========*/ background-color: $colorBtnPrimary; color: $colorBtnPrimaryText; &:hover { background-color: $colorBtnPrimaryHover; color: $colorBtnPrimaryText; } &:active, &:focus { background-color: $colorBtnPrimaryActive; color: $colorBtnPrimaryText; } &[disabled], &.disabled { cursor: default; color: $disabledBorder; background-color: $disabledGrey; } } .btn--small { padding: 4px 5px; font-size: em(12px); } .btn--secondary { @extend .btn; background-color: $colorBtnSecondary; &:hover { background-color: $colorBtnSecondaryHover; color: $colorBtnSecondaryText; } &:active, &:focus { background-color: $colorBtnSecondaryActive; color: $colorBtnSecondaryText; } } ``` Is it possible to have three "overlays" (original image, alternate image, button)?<issue_comment>username_1: Here's the needed solution to align the Compass button on Top Right corner: ``` View compassButton = mMapView.findViewWithTag("GoogleMapCompass");//to access the compass button RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) compassButton.getLayoutParams(); rlp.addRule(RelativeLayout.ALIGN_PARENT_END); rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP); rlp.addRule(RelativeLayout.ALIGN_PARENT_START,0); rlp.topMargin = 50; ``` This will change it's `RelativeLayout` params to align to the Top Right corner. **Result:** [![enter image description here](https://i.stack.imgur.com/bvs4m.jpg)](https://i.stack.imgur.com/bvs4m.jpg) Upvotes: 3 <issue_comment>username_2: You may use GoogleMap.setPadding() method: for your compass position <https://developers.google.com/maps/documentation/android/map#map_padding> Upvotes: 0
2018/03/16
669
1,994
<issue_start>username_0: I want to count how many hours and minutes between two timestamp which are generated by `Date.parse`. After I get the difference, I need to convert it into hours and minutes like `2.10` (means, 2 hours and 10 minutes). Once I have read that to do it you need to divide it with 3600 so I tried this code but it just gives me `0.89` instead of `1.26`. ``` var now = new Date(); var endTime = Date.parse(now)/1000; var startTime = Date.parse("2018-03-16 10:29:17")/1000; $scope.timestamp_difference = startTime - endTime; $scope.hours = $scope.timestamp_difference/3600; ``` How to do it right?<issue_comment>username_1: In case you haven't heard, Momentjs makes working with dates and times pretty damn easy in javascript i updated code for you may hope it will helps you now ``` var date1 = moment('03/15/2018 11:00', 'MM/DD/YYYY hh:mm'), date2 = moment('03/16/2018 10:00', 'MM/DD/YYYY hh:mm'); var duration = moment.duration(date2.diff(date1)); //you will get 23 hours 00 minute alert(duration.asHours().toFixed(2)) ``` <http://jsfiddle.net/dp7rzmw5/9771/> ``` Output: 23:00 hrs ``` Upvotes: 1 <issue_comment>username_2: ``` function getTimeDifference(timestampDifference) { var hours = ~~(timestampDifference / 3600); var minuts = ~~((timestampDifference - hours * 3600) / 60); var seconds = timestampDifference - hours * 3600 - minuts * 60; return hours + '.' + minuts + '.' + seconds; } ``` Upvotes: 0 <issue_comment>username_3: ``` var minutes = "0" + Math.floor(timestampDifference / 60); // get minutes var seconds = "0" + Math.floor(timestampDifference - minutes * 60); // get seconds var hour = "0" + Math.floor(timestampDifference / 3600); //get hour if ( hour > 1 ) { return hour.substr(-2) + ":" + minutes.substr(-2) + ":" + seconds.substr(-2); } else { return minutes.substr(-2) + ":" + seconds.substr(-2); } // check if the hour is greater then 1 than return time with hour else return minutes. ``` Upvotes: 0
2018/03/16
1,069
3,619
<issue_start>username_0: I am getting back some data from a service and I am struggling to change the structure. Any help would be greatly appreciated. **Current Structure:** ``` { "key1": { "description":"lorem ipsum", }, "key2": { "description":"lorem ipsum", } } ``` **New Structure:** ``` [ { "label":"key1", "description":"lorem ipsum", }, { "label":"key2", "description":"lorem ipsum", } ] ```<issue_comment>username_1: ```js const serverData = { "key1": { "description":"lorem ipsum", }, "key2": { "description":"lorem ipsum", } } // Expected output: /*[ { "label":"key1", "description":"lorem ipsum", }, { "label":"key2", "description":"lorem ipsum", } ]*/ const expectedOutput = Object.keys(serverData) .map((key) => ({ label: key, description: serverData[key].description })); console.log(expectedOutput); ``` Upvotes: 2 <issue_comment>username_2: Use `Object.keys`. This will give all the keys of the object. Now use `Array.map` function to create a new array using the array which was created using `Object.keys` ```js var oldObj = { "key1": { "description": "lorem ipsum", }, "key2": { "description": "lorem ipsum", } } var getKeys = Object.keys(oldObj); var newObj = getKeys.map(function(item) { return { label: item, description: oldObj[item].description } }); console.log(newObj) ``` Upvotes: 2 <issue_comment>username_3: ```js var x = { "key1": { "description":"lorem ipsum", }, "key2": { "description":"lorem ipsum", } } var result = [] for(var i=0; i< Object.keys(x).length; i++){ var key = Object.keys(x)[i] var object = {"Key" : key, "description" : x[key].description} result.push(object) } console.log(result); ``` Upvotes: 1 <issue_comment>username_4: You can use `.map()` with `Object.keys()` and `Object.assign()`: ```js let data = { "key1": { "description":"lorem ipsum", }, "key2": { "description":"lorem ipsum", } }; let result = Object.keys(data) .map(key => Object.assign({"label": key}, data[key])); console.log(result); ``` Alternatively you can also use spread syntax: ```js let data = { "key1": { "description":"lorem ipsum", }, "key2": { "description":"lorem ipsum", } }; let result = Object.keys(data) .map(key => ({"label": key, ...data[key]})); console.log(result); ``` **Useful Resources:** * [`Array.prototype.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) * [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) * [`Object.assign()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) * [`Spread syntax`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) Upvotes: 3 [selected_answer]<issue_comment>username_5: This should produce the array of object you requested in your post. ``` var newlist = []; for (var key in yourobject) { if (yourobject.hasOwnProperty(key)) { var tmpobj = {}; tmpobj.label = key; tmpobj.description = yourobject[key]; newlist.push(tmpobj); } } ``` Upvotes: 1
2018/03/16
1,394
3,826
<issue_start>username_0: I am trying to match a six digit version (seperated by a dot `.` ),lets say `9.130.46.32.6.2` and it works fine but it matches a seven digit version (seperated by a dot `.`) aswell,lets say `9.130.46.32.6.2.1'`,how to ensure it only matches a six digit version but not anything else? ``` import re version = '192.168.127.12.6.2' (six digit) -->SHOULD MATCH version = '9.130.46.32.6.2.1'(seven digit) --> SHOULD NOT MATCH #if the version is six digit append a ".0" as 4th digit regex = re.compile(r'\d+\.\d+\.\d+\.\d+\.\d+\.\d+') m = regex.match(version) if m: print "Its a six digit version..." digit1 = version.split('.')[-6] print digit1 digit2 = version.split('.')[-5] print digit2 digit3 = version.split('.')[-4] print digit3 digit4 = version.split('.')[-3] print digit4 digit5 = version.split('.')[-2] print digit5 digit6 = version.split('.')[-1] print digit6 new_version = digit1 + "."+ digit2 + "." + digit3 + "."+ "0." + digit4 + "." + digit5 + "." + digit6 print new_version ```<issue_comment>username_1: By anchoring the regex. ``` r'^\d+\.\d+\.\d+\.\d+\.\d+\.\d+$' ``` Upvotes: 2 <issue_comment>username_2: Instead of using `compile`, grab all digits in the IP and check its length: ``` import re versions = ['192.168.127.12.6.2', '192.168.127.12.6.2.1'] new_versions = [i for i in versions if len(re.findall('\d+', i)) == 6] ``` Output: ``` ['9.130.46.32.6.2'] ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: What about this: ``` ^([0-9]+\.){5}[0-9]+$ ``` or using negative lookahead. ``` ^([0-9]+\.){5}[0-9]+(?!\.\d+) ``` see: <https://regex101.com/r/o0uNTy/1> and <https://regex101.com/r/o0uNTy/2> Upvotes: 0 <issue_comment>username_4: The regular expression match when using `re.match` can be any *prefix* of the string, so you’ll need to anchor it by matching the end of the string with `\Z`. (`$` is like `\Z` in Python regex, but can match a trailing newline.) If you didn’t want to match the broader category of Unicode digits (like `١.٢.٣.٤.٥.٦`), you should probably also use `[0-9]`. Overall: ``` r"(?:[0-9]+\.){5}[0-9]+\Z" ``` Upvotes: 0 <issue_comment>username_5: One other option would be to use a negative lookahead: ``` regex = re.compile(r'\d+\.\d+\.\d+\.\d+\.\d+\.\d+(?!\.\d+)') ``` This would explicitly disallow a `.` followed by a sequence of digits from following your match. This would mainly be interesting if you are trying to search through a string for the version numbers and wanted to match only the 6-part variant. If you already have isolated the version as a string, however, anchoring is a more appropriate solution (or just split on `.` and don't use a regex at all). Upvotes: 0 <issue_comment>username_6: ``` # if the version is six numbers long insert a "0" as 4th number fields = version.split(".") if len(fields) == 6: fields = fields[0:3] + ["0"] + fields[3:6] # `fields` now contains 7 numbers print ".".join(fields) ``` Upvotes: 2 <issue_comment>username_7: The method `re.match` will match any prefix of the string. If you are using *Python3*, use `re.fullmatch`, which will only match the full string instead. You can even use capturing groups to add `'.0'` as fourth digit. ``` version = '9.130.46.32.6.2' regex = re.compile(r'(\d+\.\d+\.\d+)(\.\d+\.\d+\.\d+)') m = regex.fullmatch(version) if m: new_version = m[1] + '.0' + m[2] # '9.130.46.0.32.6.2' ``` And here is an example for a seven digits version. ``` version = '9.130.46.32.6.2.1' m = regex.fullmatch(version) # None ``` Upvotes: 0 <issue_comment>username_8: You can simply do: ``` import re pattern=r'\d+' print([re.findall(pattern,line) for line in open('text.txt','r') if len(re.findall(pattern,line))==6]) ``` output: ``` [['9', '130', '46', '32', '6', '2']] ``` Upvotes: 0
2018/03/16
580
2,080
<issue_start>username_0: I have created a chatbot using MS Bot Framework and bot application, in C#. I added the Web chat to my html website through iframe got from bot framework. Now I want to delete the chat caption which is embedded with the Web chat. Instead of that I want to add my Chat bot's name. So how can i edit my html code to remove the Chat caption..<issue_comment>username_1: As you are aware, when you use webchat, an iframe is loaded in your webpage which renders your bot. So you can't really change anything inside the iframe via JavaScript unless its exposed. Hence you can't change the 'Chat' caption as it is. But what you can do, is to render your own webchat using directline as mentioned in [How to add Web Chat to your website](https://github.com/Microsoft/BotFramework-WebChat#how-to-add-web-chat-to-your-website). Here you have full control over what is rendered and how its rendered. Once you have setup the chat using the above mentioned link, you can find and modify the following code block in **Chat.tsx** file. ``` { typeof state.format.chatTitle === 'string' ? state.format.chatTitle : state.format.strings.title } ``` Modify it to below code and compile it: ``` { typeof state.format.chatTitle === 'string' ? "Chat bot's name" : "Chat bot's name" } ``` Or another simpler approach would be to reference the files in CDN and then use JavaScript to change it. Sample code snippet : ``` document.getElementsByClassName("wc-header")[0].innerHTML = "Chat bot's name" ``` [![enter image description here](https://i.stack.imgur.com/mn5Fw.png)](https://i.stack.imgur.com/mn5Fw.png) Upvotes: 2 <issue_comment>username_2: With [this](https://github.com/Microsoft/BotFramework-WebChat/pull/875/commits/f763302834c646f002f3ff1634e1e00e9003a802) change to botconnector-webchat, you can use top level botchat settings to enable/disable/change the title: ``` BotChat.App({ directLine: ..., user: ..., bot: ..., resize: "detect", speechOptions: ..., chatTitle: false // use this }, document.getElementById("bot")); ``` Upvotes: 1
2018/03/16
4,630
13,850
<issue_start>username_0: Guys I do hope you can help me. Back in February I went through all the hassle of creating a certificate as Apple Developer and asking my tutor to create me a provisioning file and add my devices (Apple Developer University Program). It all worked on my MacBookPro and I was happy. Unreal would highlight in green my provisioning file and my Certificate as iPhone developer. [![enter image description here](https://i.stack.imgur.com/pReQO.png)](https://i.stack.imgur.com/pReQO.png) Fast forward a month and I'm doing an Internship 8hours across the globe. First thing I do is having my new tutor assign me an iMac, I install Xcode, Unreal, set up my account on Xcode, create a certificate for the iMac, download the provisioning file and double click it (shouldn't be needed anyways). Test Deploying an app on my iPhone and done, it works. Switch over to Unreal, let's test this new AR template, open project settings and...the provisioning file is RED, saying "No Valid Certificate Found", with my certificate as iPhone Developer RIGHT UNDER THERE. [![enter image description here](https://i.stack.imgur.com/5ZHus.png)](https://i.stack.imgur.com/5ZHus.png) If I import manually the provisioning file it is the same "No Valid Certificate found" problem If I try building and deploying anyways I get this error: > > LogPlayLevel: Code Signing Error: Provisioning profile > "bartolomei-provisioning" doesn't include signing certificate "iPhone > Developer: <NAME> (2HEP25L8WM)". > > > LogPlayLevel: Code Signing Error: Code signing is required for product type 'Application' > in SDK 'iOS 11.2' > > > and it doesn't make any sense since on the very next MacBook Pro on this same desk everything works fine! What I tried: * playing around with timezones and shifting to GMT 0 * checking that my Apple Worldwide Developer Relations Certification Authority is up to date. * looking at many many posts on Answerhub * close and reopen everything multiple times * redoing everything from scratch * deleting all the provision files in the folder Library/MobileDevice/ProvisioningProfiles and importing only the one downloaded from Dev Center manually. * you name it What am I missing? I have other things on which to be stuck on, this can't be one! Thanks for help ``` LogPlayLevel: ********** STAGE COMMAND STARTED ********** LogPlayLevel: Creating UE4CommandLine.txt LogPlayLevel: Creating Staging Manifest... LogPlayLevel: CookPlat IOS, this IOSPlatform LogPlayLevel: Completed Launch On Stage: Build Task, Time: 16.000683 LogPlayLevel: UPL Init: None LogPlayLevel: Cleaning Stage Directory: /Users/massimobortolamei/Documents/Unreal Projects/ARkitTest/Saved/StagedBuilds/IOS LogPlayLevel: Copying NonUFSFiles to staging directory: /Users/massimobortolamei/Documents/Unreal Projects/ARkitTest/Saved/StagedBuilds/IOS LogPlayLevel: Copying DebugFiles to staging directory: /Users/massimobortolamei/Documents/Unreal Projects/ARkitTest/Saved/StagedBuilds/IOS LogPlayLevel: Copying UFSFiles to staging directory: /Users/massimobortolamei/Documents/Unreal Projects/ARkitTest/Saved/StagedBuilds/IOS LogPlayLevel: Running: mono "/Users/Shared/Epic Games/UE_4.19/Engine/Binaries/DotNET/IOS/DeploymentServer.exe" Backup -file "/Users/massimobortolamei/Documents/Unreal Projects/ARkitTest/Saved/StagedBuilds/IOS/Manifest_UFSFiles_IOS.txt" -file "/Users/massimobortolamei/Documents/Unreal Projects/ARkitTest/Saved/StagedBuilds/IOS/Manifest_NonUFSFiles_IOS.txt" -de vice fb578a13b17996a6436737f8863e068d017d8256 -bundle it.polimi.ARkitTest LogPlayLevel: [deploy] Created deployment server. LogPlayLevel: [DD] Trying to connect to mobile device running iOS ... LogPlayLevel: [DD] Mobile Device 'iPhone di Massimo' connected LogPlayLevel: Failed to connect to bundle 'it.polimi.ARkitTest' with Unknown error 0xE80000B7 LogPlayLevel: [DD] ... File to be written '/Users/massimobortolamei/Documents/Unreal Projects/ARkitTest/Saved/StagedBuilds/IOS\iPhone di Massimo_Manifest_UFSFiles_IOS.txt' LogPlayLevel: [DD] ... File to be written '/Users/massimobortolamei/Documents/Unreal Projects/ARkitTest/Saved/StagedBuilds/IOS\iPhone di Massimo_Manifest_NonUFSFiles_IOS.txt' LogPlayLevel: [DD] ... Error: Failed to connect to bundle 'it.polimi.ARkitTest' LogPlayLevel: [DD] LogPlayLevel: Exiting. LogPlayLevel: Took 3.09494s to run mono, ExitCode=1 LogPlayLevel: ********** STAGE COMMAND COMPLETED ********** LogPlayLevel: ********** PACKAGE COMMAND STARTED ********** LogPlayLevel: Package /Users/massimobortolamei/Documents/Unreal Projects/ARkitTest/ARkitTest.uproject LogPlayLevel: UPL Init: None LogPlayLevel: Project: /Users/massimobortolamei/Documents/Unreal Projects/ARkitTest/ARkitTest_IOS.xcworkspace LogPlayLevel: Running: mono "/Users/Shared/Epic Games/UE_4.19/Engine/Binaries/DotNET/UnrealBuildTool.exe" -XcodeProjectFiles -project="/Users/massimobortolamei/Documents/Unreal Projects/ARkitTest/ARkitTest.uproject" -platforms=IOS -game -nointellisense -IOSdeployonly -ignorejunk -nocreatestub -NoHotReload -ignorejunk LogPlayLevel: Discovering modules, targets and source code for project... LogPlayLevel: Writing project files... 0%33%67%100% LogPlayLevel: Took 15.178321s to run mono, ExitCode=0 LogPlayLevel: Running: /usr/bin/env UBT_NO_POST_DEPLOY=true /usr/bin/xcrun xcodebuild build -workspace "/Users/massimobortolamei/Documents/Unreal Projects/ARkitTest/ARkitTest_IOS.xcworkspace" -scheme 'ARkitTest' -configuration "Development" -destination generic/platform=iOS -sdk iphoneos CODE_SIGN_IDENTITY="iPhone Developer: <NAME> (2HEP25L8WM)" PROVISIONING_PROFILE_SPECIFIER=80bdffbe-a8a7-4914-a570-1d62ff3e2ddf LogPlayLevel: Build settings from command line: LogPlayLevel: CODE_SIGN_IDENTITY = iPhone Developer: <NAME> (2HEP25L8WM) LogPlayLevel: PROVISIONING_PROFILE_SPECIFIER = 80bdffbe-a8a7-4914-a570-1d62ff3e2ddf LogPlayLevel: SDKROOT = iphoneos11.2 LogPlayLevel: 2018-03-15 16:48:49.903 xcodebuild[44958:1128209] +dataWithFirstBytes:1024 ofFile:"/Users/massimobortolamei/Documents/Unreal Projects/ARkitTest/Config/DefaultEditor.ini" failed, errno = 2 LogPlayLevel: 2018-03-15 16:48:51.376 xcodebuild[44958:1128209] +dataWithFirstBytes:1024 ofFile:"/Users/Shared/Epic Games/UE_4.19/Engine/Config/BaseEditorLayout.ini" failed, errno = 2 LogPlayLevel: 2018-03-15 16:48:51.596 xcodebuild[44958:1128209] +dataWithFirstBytes:1024 ofFile:"/Users/Shared/Epic Games/UE_4.19/Engine/Plugins/Experimental/AlembicImporter/Source/ThirdParty/Alembic/alembic/houdini/SOP_AlembicIn/OPalembic/Object_1alembicarchive/Help" failed, errno = 2 LogPlayLevel: 2018-03-15 16:48:51.600 xcodebuild[44958:1128209] +dataWithFirstBytes:1024 ofFile:"/Users/Shared/Epic Games/UE_4.19/Engine/Plugins/Experimental/AlembicImporter/Source/ThirdParty/Alembic/alembic/houdini/SOP_AlembicIn/OPalembic/Object_1alembicxform/Help" failed, errno = 2 LogPlayLevel: 2018-03-15 16:48:52.055 xcodebuild[44958:1128209] +dataWithFirstBytes:1024 ofFile:"/Users/Shared/Epic Games/UE_4.19/Engine/Plugins/Experimental/AlembicImporter/Source/ThirdParty/Alembic/hdf5/tools/testfiles/tmulti-g.h5" failed, errno = 2 LogPlayLevel: 2018-03-15 16:48:52.072 xcodebuild[44958:1128209] +dataWithFirstBytes:1024 ofFile:"/Users/Shared/Epic Games/UE_4.19/Engine/Plugins/Experimental/AlembicImporter/Source/ThirdParty/Alembic/hdf5/tools/testfiles/tnoddlfile.ddl" failed, errno = 2 LogPlayLevel: 2018-03-15 16:48:52.125 xcodebuild[44958:1128209] +dataWithFirstBytes:1024 ofFile:"/Users/Shared/Epic Games/UE_4.19/Engine/Plugins/Experimental/AlembicImporter/Source/ThirdParty/Alembic/hdf5/tools/testfiles/twithddlfile.ddl" failed, errno = 2 LogPlayLevel: === BUILD TARGET ARkitTest OF PROJECT ARkitTest WITH CONFIGURATION Development === LogPlayLevel: Check dependencies LogPlayLevel: Code Signing Error: Provisioning profile "bartolomei-provisioning" doesn't include signing certificate "iPhone Developer: <NAME> (2HEP25L8WM)". LogPlayLevel: Code Signing Error: Code signing is required for product type 'Application' in SDK 'iOS 11.2' LogPlayLevel: ** BUILD FAILED ** LogPlayLevel: The following build commands failed: LogPlayLevel: Check dependencies LogPlayLevel: (1 failure) LogPlayLevel: Took 5.906535s to run env, ExitCode=65 LogPlayLevel: ERROR: CodeSign Failed LogPlayLevel: (see /Users/massimobortolamei/Library/Logs/Unreal Engine/LocalBuildLogs/UAT_Log.txt for full exception trace) LogPlayLevel: AutomationTool exiting with ExitCode=32 (Error_FailedToCodeSign) LogPlayLevel: Completed Launch On Stage: Deploy Task, Time: 26.393563 LogPlayLevel: RunUAT ERROR: AutomationTool was unable to run successfully. PackagingResults: Error: Launch failed! Failed to Code Sign ``` and when opening project settings this happens ``` LogTemp: Running Mono... LogTemp: Setting up Mono LogTemp: /Users/Shared/Epic Games/UE_4.19/Engine /Users/Shared/Epic Games/UE_4.19 LogTemp: Executing iPhonePackager certificates Engine -bundlename it.polimi.ARkitTest LogTemp: CWD: /Users/Shared/Epic Games/UE_4.19/Engine/Binaries/DotNET/IOS LogTemp: Initial Dir: /Users/Shared/Epic Games/UE_4.19/Engine LogTemp: Env CWD: /Users/Shared/Epic Games/UE_4.19/Engine/Binaries/DotNET/IOS LogTemp: BranchPath = Massimos-iMac.local///Users/Shared/Epic Games/UE_4.19/Engine/Binaries/DotNET/IOS/../.. --- GameBranchPath = Massimos-iMac.local///Users/Shared/Epic Games/UE_4.19/Engine/Binaries/DotNET/IOS/../.. LogTemp: CERTIFICATE-Name:iPhone Developer: <NAME> (2HEP25L8WM),Validity:VALID,StartDate:2018-03-15T06:28:26.0000000Z,EndDate:2019-03-15T06:28:26.0000000Z LogTemp: CERTIFICATE-Name:iPhone Developer: <NAME> (2HEP25L8WM),Validity:VALID,StartDate:2018-03-15T06:28:26.0000000Z,EndDate:2019-03-15T06:28:26.0000000Z LogTemp: Looking for a certificate that matches the application identifier 'EDG8TGNYUA.*' LogTemp: PROVISION-File:003de59d-3ce0-4c26-83c4-526d9e957553.mobileprovision,Name:iOS Team Provisioning Profile: *,Validity:NO_CERT,StartDate:3/15/2018 6:41:32 AM,EndDate:3/15/2019 6:41:32 AM,Type:DEVELOPMENT LogTemp: Looking for a certificate that matches the application identifier 'EDG8TGNYUA.*' LogTemp: .. Failed to find a valid certificate that was in date LogTemp: PROVISION-File:80bdffbe-a8a7-4914-a570-1d62ff3e2ddf.mobileprovision,Name:bartolomei-provisioning,Validity:NO_CERT,StartDate:2/23/2018 10:42:23 AM,EndDate:2/23/2019 10:42:23 AM,Type:DEVELOPMENT LogTemp: Looking for a certificate that matches the application identifier 'EDG8TGNYUA.*' LogTemp: PROVISION-File:UE4_003de59d-3ce0-4c26-83c4-526d9e957553.mobileprovision,Name:iOS Team Provisioning Profile: *,Validity:NO_CERT,StartDate:3/15/2018 6:41:32 AM,EndDate:3/15/2019 6:41:32 AM,Type:DEVELOPMENT LogTemp: Looking for a certificate that matches the application identifier 'EDG8TGNYUA.*' LogTemp: .. Failed to find a valid certificate that was in date LogTemp: PROVISION-File:UE4_80bdffbe-a8a7-4914-a570-1d62ff3e2ddf.mobileprovision,Name:bartolomei-provisioning,Validity:NO_CERT,StartDate:2/23/2018 10:42:23 AM,EndDate:2/23/2019 10:42:23 AM,Type:DEVELOPMENT LogTemp: Looking for a certificate that matches the application identifier 'EDG8TGNYUA.*' LogTemp: .. Failed to find a valid certificate that was in date LogTemp: PROVISION-File:bartolomeiprovisioning.mobileprovision,Name:bartolomei-provisioning,Validity:NO_CERT,StartDate:2/23/2018 10:42:23 AM,EndDate:2/23/2019 10:42:23 AM,Type:DEVELOPMENT LogTemp: MATCHED-Provision:,File:,Cert: ```<issue_comment>username_1: Ok so, I was able to find what I think is a solution. I have very basic understanding about code signing but it seems that the same keys and certificates I was using on my MacBookPro were linked somehow to the provisioning file I was using. Moving the provisioning file on the iMac would work fine for Xcode because it would manage things automatically, unfortunately Unreal doesn't do so and it would complain about missing signing keys. I then approached the problem from another side (since I don't have full permissions in the Dev Center because it is a university program) and looked into how to export the keys from one computer to another. this addressed the issue perfectly [The issues of exporting/importing certificate , private key under keychain access for Iphone](https://stackoverflow.com/questions/7006845/the-issues-of-exporting-importing-certificate-private-key-under-keychain-acces) for the lazy: on the working pc go to Xcode>Preferences>Accounts>small gear icon next to + and - > export remember to put a password because it is very important stuff. transfer the file to the other computer, double click, enter password and everything will be automatically imported! close and reopen Xcode preferences and log into the account. In unreal everything should be automagically imported. Just remember to start from a clean situation (I had to import the file a couple of times actually) by manually deleting all keys and certificates from Keychain. This time unreal would show "Valid" next to the provisioning file, and while deploying it would ask for the keychain password. And Done! Upvotes: 3 [selected_answer]<issue_comment>username_2: In my case, I have to : . change name of Bundle Name same as Bunder Identifier com.company.projectname . check box of : For Distribution in packaging menu. Upvotes: 0 <issue_comment>username_3: This is old, but I recently had a similar issue with unreal engine 5.1. In my case the issue was that the private key used to create the singing request, and thus the certificate, was not in my keychain. It was created on another machine. @username_1's solution solves this, but simply exporting said key with keychain access app, and importing it again on the target machine was more direct and simpler in my case. Upvotes: 0