qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
68,083,635
I am using a Queensland government API. The format for it is JSON, and the keys have spaces in them. I am trying to access them with python and flask. I can pass through the data required to the HTML file yet cannot print it using flask. ``` {% block content %} <div> {% for suburb in data %} <p>{{ suburb.Age }}</p> <p>{{ suburb.Manslaughter Unlawful Striking Causing Death }}</p> {% endfor %} </div> {% endblock content %} ``` Above is the code for the HTML file. "Manslaughter Unlawful Striking Causing Death" is the key I am trying to access but it comes up with this error when I load the page. ``` from flask import Flask, render_template import requests import json app = Flask(__name__) @app.route('/', methods=['GET']) def index(): req = requests.get("https://www.data.qld.gov.au/api/3/action/datastore_search?resource_id=8b29e643-56a3-4e06-81da-c913f0ecff4b&limit=5") data = json.loads(req.content) print(data) district=[] for Districts in data['result']['records']: district.append(Districts) return render_template('index.html', data=district) if __name__=="__main__": app.run(debug=True) ``` Above now is all the python code I am running. [The error that is shown on the webpage when trying to load it.](https://i.stack.imgur.com/Hq0LY.png) Any suggestions, please?
2021/06/22
[ "https://Stackoverflow.com/questions/68083635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16289640/" ]
There's lots of fundamental problems in the code. Most notably, `int**` is not a 2D array and cannot point at one. * `i<2` typo in the `for(int j...` loop. * `i < n` in the `for(int k...` loop. * To allocate a 2D array you must do: `int (*a)[2] = malloc(sizeof(int) * 2 * 2);`. Or if you will `malloc( sizeof(int[2][2]) )`, same thing. * To access a 2D array you do `a[i][j]`. * To pass a 2D array to a function you do `void func (int n, int arr[n][n]);` * Returning a 2D array from a function is trickier, easiest for now is just to use `void*` and get that working. * `malloc` doesn't initialize the allocated memory. If you want to do `+=` on `c` you should use `calloc` instead, to set everything to zero. * Don't write an unreadable mess like `*(*(c + i) + j)`. Write `c[i][j]`. I fixed these problems and got something that runs. You check if the algorithm is correct from there. ``` #include <stdio.h> #include <stdlib.h> void* multiply(int n, int a[n][n], int b[n][n]) { int (*c)[n] = calloc(1, sizeof(int[n][n])); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { c[i][j] += a[i][k] * b[k][j]; } } } return c; } int main() { int (*a)[2] = malloc(sizeof(int[2][2])); int (*b)[2] = malloc(sizeof(int[2][2])); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { a[i][j] = i - j; b[i][j] = j - i; } } int (*c)[2] = multiply(2, a, b); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { printf("c[%d][%d] = %d\n", i, j, c[i][j]); } } free(a); free(b); free(c); return 0; } ```
You need to fix multiple errors here: 1/ line 5/24/28: `int **c = malloc(sizeof(int*) * n )` 2/ line 15: `k<n` 3/ Remark: use `a[i][j]` instead of `*(*(a+i)+j)` 4/ line 34: `j<2` 5/ check how to create a 2d matrix using pointers. ``` #include <stdio.h> #include <stdlib.h> int** multiply(int** a, int** b, int n) { int **c = malloc(sizeof(int*) * n ); for (int i=0;i<n;i++){ c[i]=malloc(sizeof(int) * n ); } // Rows of c for (int i = 0; i < n; i++) { // Columns of c for (int j = 0; j < n; j++) { // c[i][j] = Row of a * Column of b for (int k = 0; k < n; k++) { c[i][j] += a[i][k] * b[k][j]; } } } return c; } int main() { int **a = malloc(sizeof(int*) * 2); for (int i=0;i<2;i++){ a[i]=malloc(sizeof(int)*2); } int **b = malloc(sizeof(int) * 2); for (int i=0;i<2;i++){ b[i]=malloc(sizeof(int)*2); } for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { a[i][j] = i - j; b[i][j] = i - j; } } int **c = multiply(a, b, 2); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { printf("c[%d][%d] = %d\n", i, j, c[i][j]); } } free(a); free(b); free(c); return 0; } ```
68,083,635
I am using a Queensland government API. The format for it is JSON, and the keys have spaces in them. I am trying to access them with python and flask. I can pass through the data required to the HTML file yet cannot print it using flask. ``` {% block content %} <div> {% for suburb in data %} <p>{{ suburb.Age }}</p> <p>{{ suburb.Manslaughter Unlawful Striking Causing Death }}</p> {% endfor %} </div> {% endblock content %} ``` Above is the code for the HTML file. "Manslaughter Unlawful Striking Causing Death" is the key I am trying to access but it comes up with this error when I load the page. ``` from flask import Flask, render_template import requests import json app = Flask(__name__) @app.route('/', methods=['GET']) def index(): req = requests.get("https://www.data.qld.gov.au/api/3/action/datastore_search?resource_id=8b29e643-56a3-4e06-81da-c913f0ecff4b&limit=5") data = json.loads(req.content) print(data) district=[] for Districts in data['result']['records']: district.append(Districts) return render_template('index.html', data=district) if __name__=="__main__": app.run(debug=True) ``` Above now is all the python code I am running. [The error that is shown on the webpage when trying to load it.](https://i.stack.imgur.com/Hq0LY.png) Any suggestions, please?
2021/06/22
[ "https://Stackoverflow.com/questions/68083635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16289640/" ]
From the updated requirement, the actual function prototype is `int *multiply(int *a, int *b, int n);` so the code should use a "flattened" matrix representation consisting of a 1-D array of length `n * n`. Using a flattened representation, element (`i`, `j`) of the `n * n` matrix `m` is accessed as `m[i * n + j]` or equivalently using the unary `*` operator as `*(m + i * n + j)`. (I think the array indexing operators are more readable.) First, let us fix some errors in the `for` loop variables. In `multiply`: ``` for (int k = 0; i < n; k++) { ``` should be: ``` for (int k = 0; k < n; k++) { ``` In `main`: ``` for (int j = 0; i < 2; j++) { ``` should be: ``` for (int j = 0; j < 2; j++) { ``` The original code has a loop that sums the terms for each element of the resulting matrix `c`, but is missing the initialization of the element to 0 before the summation. Corrected code, using the updated prototype with flattened matrix representation: ``` #include <stdio.h> #include <stdlib.h> int* multiply(int* a, int* b, int n) { int *c = malloc(sizeof(int) * n * n); // Rows of c for (int i = 0; i < n; i++) { // Columns of c for (int j = 0; j < n; j++) { // c[i][j] = Row of a * Column of b c[i * n + j] = 0; for (int k = 0; k < n; k++) { c[i * n + j] += a[i * n + k] * b[k * n + j]; } } } return c; } int main() { int *a = malloc(sizeof(int) * 2 * 2); int *b = malloc(sizeof(int) * 2 * 2); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { a[i * 2 + j] = i - j; b[i * 2 + j] = j - i; } } int *c = multiply(a, b, 2); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { printf("c[%d][%d] = %d\n", i, j, c[i * 2 + j]); } } free(a); free(b); free(c); return 0; } ```
You need to fix multiple errors here: 1/ line 5/24/28: `int **c = malloc(sizeof(int*) * n )` 2/ line 15: `k<n` 3/ Remark: use `a[i][j]` instead of `*(*(a+i)+j)` 4/ line 34: `j<2` 5/ check how to create a 2d matrix using pointers. ``` #include <stdio.h> #include <stdlib.h> int** multiply(int** a, int** b, int n) { int **c = malloc(sizeof(int*) * n ); for (int i=0;i<n;i++){ c[i]=malloc(sizeof(int) * n ); } // Rows of c for (int i = 0; i < n; i++) { // Columns of c for (int j = 0; j < n; j++) { // c[i][j] = Row of a * Column of b for (int k = 0; k < n; k++) { c[i][j] += a[i][k] * b[k][j]; } } } return c; } int main() { int **a = malloc(sizeof(int*) * 2); for (int i=0;i<2;i++){ a[i]=malloc(sizeof(int)*2); } int **b = malloc(sizeof(int) * 2); for (int i=0;i<2;i++){ b[i]=malloc(sizeof(int)*2); } for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { a[i][j] = i - j; b[i][j] = i - j; } } int **c = multiply(a, b, 2); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { printf("c[%d][%d] = %d\n", i, j, c[i][j]); } } free(a); free(b); free(c); return 0; } ```
47,969,587
I can't figure out how to open a dng file in opencv. The file was created when using the pro options of the Samsung Galaxy S7. The images that are created when using those options are a dng file as well as a jpg of size 3024 x 4032 (I believe that is the dimensions of the dng file as well). I tried using the answer from [here](https://stackoverflow.com/questions/18682830/opencv-python-display-raw-image) (except with 3 colors instead of grayscale) like so: ``` import numpy as np fd = open("image.dng", 'rb') rows = 4032 cols = 3024 colors = 3 f = np.fromfile(fd, dtype=np.uint8,count=rows*cols*colors) im = f.reshape((rows, cols,colors)) #notice row, column format fd.close() ``` However, i got the following error: ``` cannot reshape array of size 24411648 into shape (4032,3024,3) ``` Any help would be appreciated
2017/12/25
[ "https://Stackoverflow.com/questions/47969587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8461821/" ]
As far as i know it is possible that DNG files can be compressed (even though it is lossless format), so you will need to decode your dng image first. <https://www.libraw.org/> is capable of doing that. There is python wrapper for that library (<https://pypi.python.org/pypi/rawpy>) ``` import rawpy import imageio path = 'image.dng' with rawpy.imread(path) as raw: rgb = raw.postprocess() ```
[process\_raw](https://github.com/DIYer22/process_raw) supports both read and write `.dng` format raw image. Here is a python example: ```py import cv2 from process_raw import DngFile # Download raw.dng for test: # wget https://github.com/yl-data/yl-data.github.io/raw/master/2201.process_raw/raw-12bit-GBRG.dng dng_path = "./raw-12bit-GBRG.dng" dng = DngFile.read(dng_path) rgb1 = dng.postprocess() # demosaicing by rawpy cv2.imwrite("rgb1.jpg", rgb1[:, :, ::-1]) rgb2 = dng.demosaicing(poww=0.3) # demosaicing with gamma correction 0.3 cv2.imwrite("rgb2.jpg", rgb2[:, :, ::-1]) DngFile.save(dng_path + "-save.dng", dng.raw, bit=dng.bit, pattern=dng.pattern) ```
43,287,649
Let's say this is normal: ``` @api.route('/something', methods=['GET']) def some_function(): return jsonify([]) ``` **Is it possible to use a function that is already defined?** ``` def some_predefined_function(): return jsonify([]) @api.route('/something', methods=['GET']) some_predefined_function() ``` I tried the above type of syntax but it didn't work and I"m not a python guy so I'm not sure if it silly to want to do this.
2017/04/07
[ "https://Stackoverflow.com/questions/43287649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680578/" ]
There are a few ways to add routes in Flask, and although `@api.route` is the most elegant one, it is not the only one. Basically a decorator is just a fancy function, you can use it inline like this: ``` api.route('/api/galleries')(some_func) ``` Internally `route` is calling [add\_url\_rule](http://flask.pocoo.org/docs/0.12/api/#flask.Flask.add_url_rule) which you can also use like this: ``` app.add_url_rule('/', 'index', index) ``` You can also just create a wrapper function and use it in the classical decorator way like @bren mentioned.
Try this: ``` def some_predefined_function(): return jsonify([]) @api.route('/something', methods=['GET']) def something(): return some_predefined_function() ```
42,077,768
the code is ``` for(int i = 0; i < max; i++) { //do something } ``` I use this exact code many times when I program, always starting at 0 and using the interval i++. There is really only one variable that changes (max) It could not be that much shorter, but considering how much this code is used, it would be quite helpful. I know in python there is the range function which is much quicker to type.
2017/02/06
[ "https://Stackoverflow.com/questions/42077768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7525600/" ]
When looping through collections, you can use enhanced loops: ``` int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println(item); } ```
Since a few people asked for something like this, here are a few things you could do, although whether these are really better is arguable and a matter of taste: ``` void times(int n, Runnable r) { for (int i = 0; i < n; i++) { r.run(); } } ``` Usage: ``` times(10, () -> System.out.println("Hello, world!")); ``` Or: ``` void times(int n, IntConsumer consumer) { for (int i = 0; i < n; i++) { consumer.accept(i); } } ``` Usage: ``` times(10, x -> System.out.println(x+1)); ``` Or: ``` void range(int lo, int hi, IntConsumer consumer) { for (int i = lo; i < hi; i++) { consumer.accept(i); } } ``` Usage: ``` range(1, 11, x -> System.out.println(x)); ``` These are just a few ideas. Designed thoughtfully, placed in a common library, and used consistently, they could make common, idiomatic code terse yet readable. Used carelessly, they could turn otherwise straightforward code into an unmanageable mess. I doubt any two developers would ever agree on exactly where the lines should be drawn.
42,077,768
the code is ``` for(int i = 0; i < max; i++) { //do something } ``` I use this exact code many times when I program, always starting at 0 and using the interval i++. There is really only one variable that changes (max) It could not be that much shorter, but considering how much this code is used, it would be quite helpful. I know in python there is the range function which is much quicker to type.
2017/02/06
[ "https://Stackoverflow.com/questions/42077768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7525600/" ]
There is a way to write shorter for loop. If "for" loop is the concern, you may find this interesting ``` for(int i = -1; ++i < max;) { //do something } ``` Notice that the counter increment was done before the comparison with max is done. Also notice that the index i starts from -1 instead of normal 0.
you can use this way for List's Normal Mode: ``` List<String> myList = Arrays.asList(new String[]{"a","b","c","d","e","f"}); for (int i=0;i<myList.size();i++){ System.out.println(myList.get(i)); } ``` Short Mode 1: ``` List<String> myList = Arrays.asList(new String[]{"a","b","c","d","e","f"}); myList.forEach((node)->{ System.out.println(node); }); ``` Short Mode 2: ``` List<String> myList = Arrays.asList(new String[]{"a","b","c","d","e","f"}); for(String node: myList){ System.out.println(node); } ```
42,077,768
the code is ``` for(int i = 0; i < max; i++) { //do something } ``` I use this exact code many times when I program, always starting at 0 and using the interval i++. There is really only one variable that changes (max) It could not be that much shorter, but considering how much this code is used, it would be quite helpful. I know in python there is the range function which is much quicker to type.
2017/02/06
[ "https://Stackoverflow.com/questions/42077768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7525600/" ]
There is a way to write shorter for loop. If "for" loop is the concern, you may find this interesting ``` for(int i = -1; ++i < max;) { //do something } ``` Notice that the counter increment was done before the comparison with max is done. Also notice that the index i starts from -1 instead of normal 0.
The for shortcut I thought of is: **for (int i : val)** which works pretty fine for me. Take as an exemple the following code: ``` for (int i = 0; x < val.length; i++) System.out.print(val[i] + ", "); ``` is equivalent with ``` for (int i : val) System.out.print(i + ", "); ``` After having some research, I found this [link](https://www.cs.utexas.edu/~scottm/cs307/javacode/codeSamples/EnhancedFor.java) with examples for the *EnhancedFor*. This kind of writing the for loop looks very similar to the way of writing a [for in Linux Bash](https://www.cyberciti.biz/faq/bash-for-loop/).
42,077,768
the code is ``` for(int i = 0; i < max; i++) { //do something } ``` I use this exact code many times when I program, always starting at 0 and using the interval i++. There is really only one variable that changes (max) It could not be that much shorter, but considering how much this code is used, it would be quite helpful. I know in python there is the range function which is much quicker to type.
2017/02/06
[ "https://Stackoverflow.com/questions/42077768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7525600/" ]
Since a few people asked for something like this, here are a few things you could do, although whether these are really better is arguable and a matter of taste: ``` void times(int n, Runnable r) { for (int i = 0; i < n; i++) { r.run(); } } ``` Usage: ``` times(10, () -> System.out.println("Hello, world!")); ``` Or: ``` void times(int n, IntConsumer consumer) { for (int i = 0; i < n; i++) { consumer.accept(i); } } ``` Usage: ``` times(10, x -> System.out.println(x+1)); ``` Or: ``` void range(int lo, int hi, IntConsumer consumer) { for (int i = lo; i < hi; i++) { consumer.accept(i); } } ``` Usage: ``` range(1, 11, x -> System.out.println(x)); ``` These are just a few ideas. Designed thoughtfully, placed in a common library, and used consistently, they could make common, idiomatic code terse yet readable. Used carelessly, they could turn otherwise straightforward code into an unmanageable mess. I doubt any two developers would ever agree on exactly where the lines should be drawn.
you can use this way for List's Normal Mode: ``` List<String> myList = Arrays.asList(new String[]{"a","b","c","d","e","f"}); for (int i=0;i<myList.size();i++){ System.out.println(myList.get(i)); } ``` Short Mode 1: ``` List<String> myList = Arrays.asList(new String[]{"a","b","c","d","e","f"}); myList.forEach((node)->{ System.out.println(node); }); ``` Short Mode 2: ``` List<String> myList = Arrays.asList(new String[]{"a","b","c","d","e","f"}); for(String node: myList){ System.out.println(node); } ```
42,077,768
the code is ``` for(int i = 0; i < max; i++) { //do something } ``` I use this exact code many times when I program, always starting at 0 and using the interval i++. There is really only one variable that changes (max) It could not be that much shorter, but considering how much this code is used, it would be quite helpful. I know in python there is the range function which is much quicker to type.
2017/02/06
[ "https://Stackoverflow.com/questions/42077768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7525600/" ]
When looping through collections, you can use enhanced loops: ``` int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println(item); } ```
The for shortcut I thought of is: **for (int i : val)** which works pretty fine for me. Take as an exemple the following code: ``` for (int i = 0; x < val.length; i++) System.out.print(val[i] + ", "); ``` is equivalent with ``` for (int i : val) System.out.print(i + ", "); ``` After having some research, I found this [link](https://www.cs.utexas.edu/~scottm/cs307/javacode/codeSamples/EnhancedFor.java) with examples for the *EnhancedFor*. This kind of writing the for loop looks very similar to the way of writing a [for in Linux Bash](https://www.cyberciti.biz/faq/bash-for-loop/).
42,077,768
the code is ``` for(int i = 0; i < max; i++) { //do something } ``` I use this exact code many times when I program, always starting at 0 and using the interval i++. There is really only one variable that changes (max) It could not be that much shorter, but considering how much this code is used, it would be quite helpful. I know in python there is the range function which is much quicker to type.
2017/02/06
[ "https://Stackoverflow.com/questions/42077768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7525600/" ]
When looping through collections, you can use enhanced loops: ``` int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println(item); } ```
There is a way to write shorter for loop. If "for" loop is the concern, you may find this interesting ``` for(int i = -1; ++i < max;) { //do something } ``` Notice that the counter increment was done before the comparison with max is done. Also notice that the index i starts from -1 instead of normal 0.
42,077,768
the code is ``` for(int i = 0; i < max; i++) { //do something } ``` I use this exact code many times when I program, always starting at 0 and using the interval i++. There is really only one variable that changes (max) It could not be that much shorter, but considering how much this code is used, it would be quite helpful. I know in python there is the range function which is much quicker to type.
2017/02/06
[ "https://Stackoverflow.com/questions/42077768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7525600/" ]
There is a way to write shorter for loop. If "for" loop is the concern, you may find this interesting ``` for(int i = -1; ++i < max;) { //do something } ``` Notice that the counter increment was done before the comparison with max is done. Also notice that the index i starts from -1 instead of normal 0.
In many cases max value is unknown (data from files, databases etc.). For me the best is loading everything to List (ArrayList etc.) and use for-each loop. Looping through collections is the best way to short loop syntax in my opinion.
42,077,768
the code is ``` for(int i = 0; i < max; i++) { //do something } ``` I use this exact code many times when I program, always starting at 0 and using the interval i++. There is really only one variable that changes (max) It could not be that much shorter, but considering how much this code is used, it would be quite helpful. I know in python there is the range function which is much quicker to type.
2017/02/06
[ "https://Stackoverflow.com/questions/42077768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7525600/" ]
Since a few people asked for something like this, here are a few things you could do, although whether these are really better is arguable and a matter of taste: ``` void times(int n, Runnable r) { for (int i = 0; i < n; i++) { r.run(); } } ``` Usage: ``` times(10, () -> System.out.println("Hello, world!")); ``` Or: ``` void times(int n, IntConsumer consumer) { for (int i = 0; i < n; i++) { consumer.accept(i); } } ``` Usage: ``` times(10, x -> System.out.println(x+1)); ``` Or: ``` void range(int lo, int hi, IntConsumer consumer) { for (int i = lo; i < hi; i++) { consumer.accept(i); } } ``` Usage: ``` range(1, 11, x -> System.out.println(x)); ``` These are just a few ideas. Designed thoughtfully, placed in a common library, and used consistently, they could make common, idiomatic code terse yet readable. Used carelessly, they could turn otherwise straightforward code into an unmanageable mess. I doubt any two developers would ever agree on exactly where the lines should be drawn.
In many cases max value is unknown (data from files, databases etc.). For me the best is loading everything to List (ArrayList etc.) and use for-each loop. Looping through collections is the best way to short loop syntax in my opinion.
42,077,768
the code is ``` for(int i = 0; i < max; i++) { //do something } ``` I use this exact code many times when I program, always starting at 0 and using the interval i++. There is really only one variable that changes (max) It could not be that much shorter, but considering how much this code is used, it would be quite helpful. I know in python there is the range function which is much quicker to type.
2017/02/06
[ "https://Stackoverflow.com/questions/42077768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7525600/" ]
When looping through collections, you can use enhanced loops: ``` int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println(item); } ```
you can use this way for List's Normal Mode: ``` List<String> myList = Arrays.asList(new String[]{"a","b","c","d","e","f"}); for (int i=0;i<myList.size();i++){ System.out.println(myList.get(i)); } ``` Short Mode 1: ``` List<String> myList = Arrays.asList(new String[]{"a","b","c","d","e","f"}); myList.forEach((node)->{ System.out.println(node); }); ``` Short Mode 2: ``` List<String> myList = Arrays.asList(new String[]{"a","b","c","d","e","f"}); for(String node: myList){ System.out.println(node); } ```
42,077,768
the code is ``` for(int i = 0; i < max; i++) { //do something } ``` I use this exact code many times when I program, always starting at 0 and using the interval i++. There is really only one variable that changes (max) It could not be that much shorter, but considering how much this code is used, it would be quite helpful. I know in python there is the range function which is much quicker to type.
2017/02/06
[ "https://Stackoverflow.com/questions/42077768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7525600/" ]
If you use Java 8, you can use `IntStream.range(min, max).foreach(i ->{})`
The for shortcut I thought of is: **for (int i : val)** which works pretty fine for me. Take as an exemple the following code: ``` for (int i = 0; x < val.length; i++) System.out.print(val[i] + ", "); ``` is equivalent with ``` for (int i : val) System.out.print(i + ", "); ``` After having some research, I found this [link](https://www.cs.utexas.edu/~scottm/cs307/javacode/codeSamples/EnhancedFor.java) with examples for the *EnhancedFor*. This kind of writing the for loop looks very similar to the way of writing a [for in Linux Bash](https://www.cyberciti.biz/faq/bash-for-loop/).
44,560,051
For example, I have a 2D Array with dimensions 3 x 3. ``` [1 2 7 4 5 6 7 8 9] ``` And I want to remove all columns which contain 7 - so first and third, outputting a 3 x 1 matrix of: ``` [2 5 8] ``` How do I go about doing this in python? I want to apply it to a large matrix of n x n dimensions. Thank You!
2017/06/15
[ "https://Stackoverflow.com/questions/44560051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8164362/" ]
``` #Creating array x = np.array([[1, 2, 7],[4,5, 6],[7,8,9]]) x Out[]: array([[1, 2, 7], [4, 5, 6], [7, 8, 9]]) #Deletion a = np.delete(x,np.where(x ==7),axis=1) a Out[]: array([[2], [5], [8]]) ```
`numpy` can help you do this! ``` import numpy as np a = np.array([1, 2, 7, 4, 5, 6, 7, 8, 9]).reshape((3, 3)) b = np.array([col for col in a.T if 7 not in col]).T print(b) ```
44,560,051
For example, I have a 2D Array with dimensions 3 x 3. ``` [1 2 7 4 5 6 7 8 9] ``` And I want to remove all columns which contain 7 - so first and third, outputting a 3 x 1 matrix of: ``` [2 5 8] ``` How do I go about doing this in python? I want to apply it to a large matrix of n x n dimensions. Thank You!
2017/06/15
[ "https://Stackoverflow.com/questions/44560051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8164362/" ]
`numpy` can help you do this! ``` import numpy as np a = np.array([1, 2, 7, 4, 5, 6, 7, 8, 9]).reshape((3, 3)) b = np.array([col for col in a.T if 7 not in col]).T print(b) ```
you can use `argwhere` for column index and then delete. ``` import numpy a = numpy.array([[5, 2, 4],[1, 7, 3],[1, 2, 7]]) index = numpy.argwhere(a==7) y = numpy.delete(a, index, axis=1) print(y) ```
44,560,051
For example, I have a 2D Array with dimensions 3 x 3. ``` [1 2 7 4 5 6 7 8 9] ``` And I want to remove all columns which contain 7 - so first and third, outputting a 3 x 1 matrix of: ``` [2 5 8] ``` How do I go about doing this in python? I want to apply it to a large matrix of n x n dimensions. Thank You!
2017/06/15
[ "https://Stackoverflow.com/questions/44560051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8164362/" ]
`numpy` can help you do this! ``` import numpy as np a = np.array([1, 2, 7, 4, 5, 6, 7, 8, 9]).reshape((3, 3)) b = np.array([col for col in a.T if 7 not in col]).T print(b) ```
``` A = np.array([[1,2,7],[4,5,6],[7,8,9]]) for i in range(0,3): ... B=A[:,i] ... if(7 in B): ... A=np.delete(A,i,1) ```
44,560,051
For example, I have a 2D Array with dimensions 3 x 3. ``` [1 2 7 4 5 6 7 8 9] ``` And I want to remove all columns which contain 7 - so first and third, outputting a 3 x 1 matrix of: ``` [2 5 8] ``` How do I go about doing this in python? I want to apply it to a large matrix of n x n dimensions. Thank You!
2017/06/15
[ "https://Stackoverflow.com/questions/44560051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8164362/" ]
``` #Creating array x = np.array([[1, 2, 7],[4,5, 6],[7,8,9]]) x Out[]: array([[1, 2, 7], [4, 5, 6], [7, 8, 9]]) #Deletion a = np.delete(x,np.where(x ==7),axis=1) a Out[]: array([[2], [5], [8]]) ```
you can use `argwhere` for column index and then delete. ``` import numpy a = numpy.array([[5, 2, 4],[1, 7, 3],[1, 2, 7]]) index = numpy.argwhere(a==7) y = numpy.delete(a, index, axis=1) print(y) ```
44,560,051
For example, I have a 2D Array with dimensions 3 x 3. ``` [1 2 7 4 5 6 7 8 9] ``` And I want to remove all columns which contain 7 - so first and third, outputting a 3 x 1 matrix of: ``` [2 5 8] ``` How do I go about doing this in python? I want to apply it to a large matrix of n x n dimensions. Thank You!
2017/06/15
[ "https://Stackoverflow.com/questions/44560051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8164362/" ]
``` #Creating array x = np.array([[1, 2, 7],[4,5, 6],[7,8,9]]) x Out[]: array([[1, 2, 7], [4, 5, 6], [7, 8, 9]]) #Deletion a = np.delete(x,np.where(x ==7),axis=1) a Out[]: array([[2], [5], [8]]) ```
If you don't actually want to delete parts of the original matrix, you can just use boolean indexing: ``` a Out[]: array([[1, 2, 7], [4, 5, 6], [7, 8, 9]]) a[:, ~np.any(a == 7, axis = 1)] Out[]: array([[2], [5], [8]]) ```
44,560,051
For example, I have a 2D Array with dimensions 3 x 3. ``` [1 2 7 4 5 6 7 8 9] ``` And I want to remove all columns which contain 7 - so first and third, outputting a 3 x 1 matrix of: ``` [2 5 8] ``` How do I go about doing this in python? I want to apply it to a large matrix of n x n dimensions. Thank You!
2017/06/15
[ "https://Stackoverflow.com/questions/44560051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8164362/" ]
``` #Creating array x = np.array([[1, 2, 7],[4,5, 6],[7,8,9]]) x Out[]: array([[1, 2, 7], [4, 5, 6], [7, 8, 9]]) #Deletion a = np.delete(x,np.where(x ==7),axis=1) a Out[]: array([[2], [5], [8]]) ```
``` A = np.array([[1,2,7],[4,5,6],[7,8,9]]) for i in range(0,3): ... B=A[:,i] ... if(7 in B): ... A=np.delete(A,i,1) ```
44,560,051
For example, I have a 2D Array with dimensions 3 x 3. ``` [1 2 7 4 5 6 7 8 9] ``` And I want to remove all columns which contain 7 - so first and third, outputting a 3 x 1 matrix of: ``` [2 5 8] ``` How do I go about doing this in python? I want to apply it to a large matrix of n x n dimensions. Thank You!
2017/06/15
[ "https://Stackoverflow.com/questions/44560051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8164362/" ]
If you don't actually want to delete parts of the original matrix, you can just use boolean indexing: ``` a Out[]: array([[1, 2, 7], [4, 5, 6], [7, 8, 9]]) a[:, ~np.any(a == 7, axis = 1)] Out[]: array([[2], [5], [8]]) ```
you can use `argwhere` for column index and then delete. ``` import numpy a = numpy.array([[5, 2, 4],[1, 7, 3],[1, 2, 7]]) index = numpy.argwhere(a==7) y = numpy.delete(a, index, axis=1) print(y) ```
44,560,051
For example, I have a 2D Array with dimensions 3 x 3. ``` [1 2 7 4 5 6 7 8 9] ``` And I want to remove all columns which contain 7 - so first and third, outputting a 3 x 1 matrix of: ``` [2 5 8] ``` How do I go about doing this in python? I want to apply it to a large matrix of n x n dimensions. Thank You!
2017/06/15
[ "https://Stackoverflow.com/questions/44560051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8164362/" ]
If you don't actually want to delete parts of the original matrix, you can just use boolean indexing: ``` a Out[]: array([[1, 2, 7], [4, 5, 6], [7, 8, 9]]) a[:, ~np.any(a == 7, axis = 1)] Out[]: array([[2], [5], [8]]) ```
``` A = np.array([[1,2,7],[4,5,6],[7,8,9]]) for i in range(0,3): ... B=A[:,i] ... if(7 in B): ... A=np.delete(A,i,1) ```
58,338,523
The [documentation](https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blockblobservice.blockblobservice?view=azure-python#batch-set-standard-blob-tier-batch-set-blob-tier-sub-requests--timeout-none-) for the batch\_set\_standard\_blob\_tier function part of BlockBlobService in azure python SDK is not clear. What exactly should be passed in the parameter? An example would be appreciated.
2019/10/11
[ "https://Stackoverflow.com/questions/58338523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6603039/" ]
You need add `allowSyntheticDefaultImports` in your `tsconfig.json`. `tsconfig.json` ``` { "allowSyntheticDefaultImports": true, "resolveJsonModule": true } ``` TS ``` import countries from './countries/es.json'; ```
import is not a good idea here later on if you want to move your file to some server you will need to rewrite the whole logic i would suggest to use [httpclient](https://angular.io/guide/http) get call here.So move you file to assets folder and then ``` constructor(private http:HttpClient){ this.http.get('assets/yourfilepath').subscribe(data=>{ const countries_keys = Object.keys(data['countries']); console.log(data['countries'])//data is your json object here }) } ```
58,338,523
The [documentation](https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blockblobservice.blockblobservice?view=azure-python#batch-set-standard-blob-tier-batch-set-blob-tier-sub-requests--timeout-none-) for the batch\_set\_standard\_blob\_tier function part of BlockBlobService in azure python SDK is not clear. What exactly should be passed in the parameter? An example would be appreciated.
2019/10/11
[ "https://Stackoverflow.com/questions/58338523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6603039/" ]
import is not a good idea here later on if you want to move your file to some server you will need to rewrite the whole logic i would suggest to use [httpclient](https://angular.io/guide/http) get call here.So move you file to assets folder and then ``` constructor(private http:HttpClient){ this.http.get('assets/yourfilepath').subscribe(data=>{ const countries_keys = Object.keys(data['countries']); console.log(data['countries'])//data is your json object here }) } ```
What worked form me was: ``` import countries from './countries/es.json'; ``` This is the "default import"
58,338,523
The [documentation](https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blockblobservice.blockblobservice?view=azure-python#batch-set-standard-blob-tier-batch-set-blob-tier-sub-requests--timeout-none-) for the batch\_set\_standard\_blob\_tier function part of BlockBlobService in azure python SDK is not clear. What exactly should be passed in the parameter? An example would be appreciated.
2019/10/11
[ "https://Stackoverflow.com/questions/58338523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6603039/" ]
You need add `allowSyntheticDefaultImports` in your `tsconfig.json`. `tsconfig.json` ``` { "allowSyntheticDefaultImports": true, "resolveJsonModule": true } ``` TS ``` import countries from './countries/es.json'; ```
What worked form me was: ``` import countries from './countries/es.json'; ``` This is the "default import"
52,907,038
I am looking for a method (if available) that can compare two values and raise an assertion error with a meaningful message when the comparison fails. If I use `assert`, the failure message does not contain what values were compared when then assertion failed. ``` >>> a = 3 >>> b = 4 >>> assert a == b Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> ``` If I use the `assertEqual()` method from the `unittest.TestCase` package, the assertion message contains the values that were compared. ``` a = 3 b = 4 > self.assertEqual(a, b) E AssertionError: 3 != 4 ``` Note that, here, the assertion error message contains the values that were compared. That is very useful in real-life scenarios and hence necessary for me. The plain `assert` (see above) does not do that. However, so far, I could use `assertEqual()` only in the class that inherits from `unittest.TestCase` and provides few other required methods like `runTest()`. I want to use `assertEqual()` anywhere, not only in the inherited classes. Is that possible? I tried the following but they did not work. ``` >>> import unittest >>> unittest.TestCase.assertEqual(a, b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method failUnlessEqual() must be called with TestCase instance as first argument (got int instance instead) >>> >>> >>> tc = unittest.TestCase() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/unittest.py", line 215, in __init__ (self.__class__, methodName) ValueError: no such test method in <class 'unittest.TestCase'>: runTest >>> ``` Is there any other package or library that offers similar methods like `assertEqual()` that can be easily used without additional constraints?
2018/10/20
[ "https://Stackoverflow.com/questions/52907038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278326/" ]
You have to give the assertion message by hand: ``` assert a == b, '%s != %s' % (a, b) # AssertionError: 3 != 4 ```
have you looked at numpy.testing? <https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.testing.html> Amongst others it has: assert\_almost\_equal(actual, desired[, ...]) Raises an AssertionError if two items are not equal up to desired precision. This assert prints out actual and desired. If you ramp up precision the comparison is arbitrarily close to == (For floats)
52,907,038
I am looking for a method (if available) that can compare two values and raise an assertion error with a meaningful message when the comparison fails. If I use `assert`, the failure message does not contain what values were compared when then assertion failed. ``` >>> a = 3 >>> b = 4 >>> assert a == b Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> ``` If I use the `assertEqual()` method from the `unittest.TestCase` package, the assertion message contains the values that were compared. ``` a = 3 b = 4 > self.assertEqual(a, b) E AssertionError: 3 != 4 ``` Note that, here, the assertion error message contains the values that were compared. That is very useful in real-life scenarios and hence necessary for me. The plain `assert` (see above) does not do that. However, so far, I could use `assertEqual()` only in the class that inherits from `unittest.TestCase` and provides few other required methods like `runTest()`. I want to use `assertEqual()` anywhere, not only in the inherited classes. Is that possible? I tried the following but they did not work. ``` >>> import unittest >>> unittest.TestCase.assertEqual(a, b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method failUnlessEqual() must be called with TestCase instance as first argument (got int instance instead) >>> >>> >>> tc = unittest.TestCase() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/unittest.py", line 215, in __init__ (self.__class__, methodName) ValueError: no such test method in <class 'unittest.TestCase'>: runTest >>> ``` Is there any other package or library that offers similar methods like `assertEqual()` that can be easily used without additional constraints?
2018/10/20
[ "https://Stackoverflow.com/questions/52907038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278326/" ]
You have to give the assertion message by hand: ``` assert a == b, '%s != %s' % (a, b) # AssertionError: 3 != 4 ```
I had similar in the past and end-up writing short custom assert which accept any condition as input. ``` import inspect def custom_assert(condition): if not condition: frame = inspect.currentframe() frame = inspect.getouterframes(frame)[1] call_signature = inspect.getframeinfo(frame[0]).code_context[0].strip() import re argument = re.search('\((.+)\)', call_signature).group(1) if '!=' in argument: argument = argument.replace('!=','==') elif '==' in argument: argument = argument.replace('==','!=') elif '<' in argument: argument = argument.replace('<','>=') elif '>' in argument: argument = argument.replace('>','<=') elif '>=' in argument: argument = argument.replace('>=','<') elif '<=' in argument: argument = argument.replace('<=','>') raise AssertionError(argument) if __name__ == '__main__': custom_assert(2 == 1) ``` Output: ``` Traceback (most recent call last): File "custom_assert.py", line 27, in <module> custom_assert(2 == 1) File "custom_assert.py", line 24, in custom_assert raise AssertionError(argument) AssertionError: 2 != 1 ```
52,907,038
I am looking for a method (if available) that can compare two values and raise an assertion error with a meaningful message when the comparison fails. If I use `assert`, the failure message does not contain what values were compared when then assertion failed. ``` >>> a = 3 >>> b = 4 >>> assert a == b Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> ``` If I use the `assertEqual()` method from the `unittest.TestCase` package, the assertion message contains the values that were compared. ``` a = 3 b = 4 > self.assertEqual(a, b) E AssertionError: 3 != 4 ``` Note that, here, the assertion error message contains the values that were compared. That is very useful in real-life scenarios and hence necessary for me. The plain `assert` (see above) does not do that. However, so far, I could use `assertEqual()` only in the class that inherits from `unittest.TestCase` and provides few other required methods like `runTest()`. I want to use `assertEqual()` anywhere, not only in the inherited classes. Is that possible? I tried the following but they did not work. ``` >>> import unittest >>> unittest.TestCase.assertEqual(a, b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method failUnlessEqual() must be called with TestCase instance as first argument (got int instance instead) >>> >>> >>> tc = unittest.TestCase() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/unittest.py", line 215, in __init__ (self.__class__, methodName) ValueError: no such test method in <class 'unittest.TestCase'>: runTest >>> ``` Is there any other package or library that offers similar methods like `assertEqual()` that can be easily used without additional constraints?
2018/10/20
[ "https://Stackoverflow.com/questions/52907038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278326/" ]
You have to give the assertion message by hand: ``` assert a == b, '%s != %s' % (a, b) # AssertionError: 3 != 4 ```
The assertEqual or any other assertXxx() method expects the first argument to be an object reference. Generally we call the method as `self.assertEqual(first, second, msg=None)`. Here `self` satisfies the first expected argument. To circumvent this situation we can do the following: ``` from unittest import TestCase as tc def some_func(): dummy_obj = tc() tc.assertEqual(dummy_obj, 123, 123, msg='Not Equal') ``` The reason for this behavior is Hangover from XUnit frameworks.
52,907,038
I am looking for a method (if available) that can compare two values and raise an assertion error with a meaningful message when the comparison fails. If I use `assert`, the failure message does not contain what values were compared when then assertion failed. ``` >>> a = 3 >>> b = 4 >>> assert a == b Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> ``` If I use the `assertEqual()` method from the `unittest.TestCase` package, the assertion message contains the values that were compared. ``` a = 3 b = 4 > self.assertEqual(a, b) E AssertionError: 3 != 4 ``` Note that, here, the assertion error message contains the values that were compared. That is very useful in real-life scenarios and hence necessary for me. The plain `assert` (see above) does not do that. However, so far, I could use `assertEqual()` only in the class that inherits from `unittest.TestCase` and provides few other required methods like `runTest()`. I want to use `assertEqual()` anywhere, not only in the inherited classes. Is that possible? I tried the following but they did not work. ``` >>> import unittest >>> unittest.TestCase.assertEqual(a, b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method failUnlessEqual() must be called with TestCase instance as first argument (got int instance instead) >>> >>> >>> tc = unittest.TestCase() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/unittest.py", line 215, in __init__ (self.__class__, methodName) ValueError: no such test method in <class 'unittest.TestCase'>: runTest >>> ``` Is there any other package or library that offers similar methods like `assertEqual()` that can be easily used without additional constraints?
2018/10/20
[ "https://Stackoverflow.com/questions/52907038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278326/" ]
It is possible to create a "helper" new module that provides access to the assert functions. `AssertsAccessor` in this case: ``` from unittest import TestCase # Dummy TestCase instance, so we can initialize an instance # and access the assert instance methods class DummyTestCase(TestCase): def __init__(self): super(DummyTestCase, self).__init__('_dummy') def _dummy(self): pass # A metaclass that makes __getattr__ static class AssertsAccessorType(type): dummy = DummyTestCase() def __getattr__(cls, key): return getattr(AssertsAccessor.dummy, key) # The actual accessor, a static class, that redirect the asserts class AssertsAccessor(object): __metaclass__ = AssertsAccessorType ``` The module needs to be created just once, and then all *asserts* from the `unittest` package are accessible, e.g.: ``` AssertsAccessor.assertEquals(1, 2) ``` > > AssertionError: 1 != 2 > > > Or another example: ``` AssertsAccessor.assertGreater(1, 2) ``` Which results: > > AssertionError: 1 not greater than 2 > > > Assuming the module created for the accessor is named `assertions`, the common usage in the code would look like: ``` from assertions import AssertsAccessor def foo(small_arg, big_arg): AssertsAccessor.assertGreater(big_arg, small_arg) # some logic here ```
have you looked at numpy.testing? <https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.testing.html> Amongst others it has: assert\_almost\_equal(actual, desired[, ...]) Raises an AssertionError if two items are not equal up to desired precision. This assert prints out actual and desired. If you ramp up precision the comparison is arbitrarily close to == (For floats)
52,907,038
I am looking for a method (if available) that can compare two values and raise an assertion error with a meaningful message when the comparison fails. If I use `assert`, the failure message does not contain what values were compared when then assertion failed. ``` >>> a = 3 >>> b = 4 >>> assert a == b Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> ``` If I use the `assertEqual()` method from the `unittest.TestCase` package, the assertion message contains the values that were compared. ``` a = 3 b = 4 > self.assertEqual(a, b) E AssertionError: 3 != 4 ``` Note that, here, the assertion error message contains the values that were compared. That is very useful in real-life scenarios and hence necessary for me. The plain `assert` (see above) does not do that. However, so far, I could use `assertEqual()` only in the class that inherits from `unittest.TestCase` and provides few other required methods like `runTest()`. I want to use `assertEqual()` anywhere, not only in the inherited classes. Is that possible? I tried the following but they did not work. ``` >>> import unittest >>> unittest.TestCase.assertEqual(a, b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method failUnlessEqual() must be called with TestCase instance as first argument (got int instance instead) >>> >>> >>> tc = unittest.TestCase() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/unittest.py", line 215, in __init__ (self.__class__, methodName) ValueError: no such test method in <class 'unittest.TestCase'>: runTest >>> ``` Is there any other package or library that offers similar methods like `assertEqual()` that can be easily used without additional constraints?
2018/10/20
[ "https://Stackoverflow.com/questions/52907038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278326/" ]
have you looked at numpy.testing? <https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.testing.html> Amongst others it has: assert\_almost\_equal(actual, desired[, ...]) Raises an AssertionError if two items are not equal up to desired precision. This assert prints out actual and desired. If you ramp up precision the comparison is arbitrarily close to == (For floats)
The assertEqual or any other assertXxx() method expects the first argument to be an object reference. Generally we call the method as `self.assertEqual(first, second, msg=None)`. Here `self` satisfies the first expected argument. To circumvent this situation we can do the following: ``` from unittest import TestCase as tc def some_func(): dummy_obj = tc() tc.assertEqual(dummy_obj, 123, 123, msg='Not Equal') ``` The reason for this behavior is Hangover from XUnit frameworks.
52,907,038
I am looking for a method (if available) that can compare two values and raise an assertion error with a meaningful message when the comparison fails. If I use `assert`, the failure message does not contain what values were compared when then assertion failed. ``` >>> a = 3 >>> b = 4 >>> assert a == b Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> ``` If I use the `assertEqual()` method from the `unittest.TestCase` package, the assertion message contains the values that were compared. ``` a = 3 b = 4 > self.assertEqual(a, b) E AssertionError: 3 != 4 ``` Note that, here, the assertion error message contains the values that were compared. That is very useful in real-life scenarios and hence necessary for me. The plain `assert` (see above) does not do that. However, so far, I could use `assertEqual()` only in the class that inherits from `unittest.TestCase` and provides few other required methods like `runTest()`. I want to use `assertEqual()` anywhere, not only in the inherited classes. Is that possible? I tried the following but they did not work. ``` >>> import unittest >>> unittest.TestCase.assertEqual(a, b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method failUnlessEqual() must be called with TestCase instance as first argument (got int instance instead) >>> >>> >>> tc = unittest.TestCase() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/unittest.py", line 215, in __init__ (self.__class__, methodName) ValueError: no such test method in <class 'unittest.TestCase'>: runTest >>> ``` Is there any other package or library that offers similar methods like `assertEqual()` that can be easily used without additional constraints?
2018/10/20
[ "https://Stackoverflow.com/questions/52907038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278326/" ]
It is possible to create a "helper" new module that provides access to the assert functions. `AssertsAccessor` in this case: ``` from unittest import TestCase # Dummy TestCase instance, so we can initialize an instance # and access the assert instance methods class DummyTestCase(TestCase): def __init__(self): super(DummyTestCase, self).__init__('_dummy') def _dummy(self): pass # A metaclass that makes __getattr__ static class AssertsAccessorType(type): dummy = DummyTestCase() def __getattr__(cls, key): return getattr(AssertsAccessor.dummy, key) # The actual accessor, a static class, that redirect the asserts class AssertsAccessor(object): __metaclass__ = AssertsAccessorType ``` The module needs to be created just once, and then all *asserts* from the `unittest` package are accessible, e.g.: ``` AssertsAccessor.assertEquals(1, 2) ``` > > AssertionError: 1 != 2 > > > Or another example: ``` AssertsAccessor.assertGreater(1, 2) ``` Which results: > > AssertionError: 1 not greater than 2 > > > Assuming the module created for the accessor is named `assertions`, the common usage in the code would look like: ``` from assertions import AssertsAccessor def foo(small_arg, big_arg): AssertsAccessor.assertGreater(big_arg, small_arg) # some logic here ```
I had similar in the past and end-up writing short custom assert which accept any condition as input. ``` import inspect def custom_assert(condition): if not condition: frame = inspect.currentframe() frame = inspect.getouterframes(frame)[1] call_signature = inspect.getframeinfo(frame[0]).code_context[0].strip() import re argument = re.search('\((.+)\)', call_signature).group(1) if '!=' in argument: argument = argument.replace('!=','==') elif '==' in argument: argument = argument.replace('==','!=') elif '<' in argument: argument = argument.replace('<','>=') elif '>' in argument: argument = argument.replace('>','<=') elif '>=' in argument: argument = argument.replace('>=','<') elif '<=' in argument: argument = argument.replace('<=','>') raise AssertionError(argument) if __name__ == '__main__': custom_assert(2 == 1) ``` Output: ``` Traceback (most recent call last): File "custom_assert.py", line 27, in <module> custom_assert(2 == 1) File "custom_assert.py", line 24, in custom_assert raise AssertionError(argument) AssertionError: 2 != 1 ```
52,907,038
I am looking for a method (if available) that can compare two values and raise an assertion error with a meaningful message when the comparison fails. If I use `assert`, the failure message does not contain what values were compared when then assertion failed. ``` >>> a = 3 >>> b = 4 >>> assert a == b Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> ``` If I use the `assertEqual()` method from the `unittest.TestCase` package, the assertion message contains the values that were compared. ``` a = 3 b = 4 > self.assertEqual(a, b) E AssertionError: 3 != 4 ``` Note that, here, the assertion error message contains the values that were compared. That is very useful in real-life scenarios and hence necessary for me. The plain `assert` (see above) does not do that. However, so far, I could use `assertEqual()` only in the class that inherits from `unittest.TestCase` and provides few other required methods like `runTest()`. I want to use `assertEqual()` anywhere, not only in the inherited classes. Is that possible? I tried the following but they did not work. ``` >>> import unittest >>> unittest.TestCase.assertEqual(a, b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method failUnlessEqual() must be called with TestCase instance as first argument (got int instance instead) >>> >>> >>> tc = unittest.TestCase() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/unittest.py", line 215, in __init__ (self.__class__, methodName) ValueError: no such test method in <class 'unittest.TestCase'>: runTest >>> ``` Is there any other package or library that offers similar methods like `assertEqual()` that can be easily used without additional constraints?
2018/10/20
[ "https://Stackoverflow.com/questions/52907038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278326/" ]
It is possible to create a "helper" new module that provides access to the assert functions. `AssertsAccessor` in this case: ``` from unittest import TestCase # Dummy TestCase instance, so we can initialize an instance # and access the assert instance methods class DummyTestCase(TestCase): def __init__(self): super(DummyTestCase, self).__init__('_dummy') def _dummy(self): pass # A metaclass that makes __getattr__ static class AssertsAccessorType(type): dummy = DummyTestCase() def __getattr__(cls, key): return getattr(AssertsAccessor.dummy, key) # The actual accessor, a static class, that redirect the asserts class AssertsAccessor(object): __metaclass__ = AssertsAccessorType ``` The module needs to be created just once, and then all *asserts* from the `unittest` package are accessible, e.g.: ``` AssertsAccessor.assertEquals(1, 2) ``` > > AssertionError: 1 != 2 > > > Or another example: ``` AssertsAccessor.assertGreater(1, 2) ``` Which results: > > AssertionError: 1 not greater than 2 > > > Assuming the module created for the accessor is named `assertions`, the common usage in the code would look like: ``` from assertions import AssertsAccessor def foo(small_arg, big_arg): AssertsAccessor.assertGreater(big_arg, small_arg) # some logic here ```
The assertEqual or any other assertXxx() method expects the first argument to be an object reference. Generally we call the method as `self.assertEqual(first, second, msg=None)`. Here `self` satisfies the first expected argument. To circumvent this situation we can do the following: ``` from unittest import TestCase as tc def some_func(): dummy_obj = tc() tc.assertEqual(dummy_obj, 123, 123, msg='Not Equal') ``` The reason for this behavior is Hangover from XUnit frameworks.
52,907,038
I am looking for a method (if available) that can compare two values and raise an assertion error with a meaningful message when the comparison fails. If I use `assert`, the failure message does not contain what values were compared when then assertion failed. ``` >>> a = 3 >>> b = 4 >>> assert a == b Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> ``` If I use the `assertEqual()` method from the `unittest.TestCase` package, the assertion message contains the values that were compared. ``` a = 3 b = 4 > self.assertEqual(a, b) E AssertionError: 3 != 4 ``` Note that, here, the assertion error message contains the values that were compared. That is very useful in real-life scenarios and hence necessary for me. The plain `assert` (see above) does not do that. However, so far, I could use `assertEqual()` only in the class that inherits from `unittest.TestCase` and provides few other required methods like `runTest()`. I want to use `assertEqual()` anywhere, not only in the inherited classes. Is that possible? I tried the following but they did not work. ``` >>> import unittest >>> unittest.TestCase.assertEqual(a, b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method failUnlessEqual() must be called with TestCase instance as first argument (got int instance instead) >>> >>> >>> tc = unittest.TestCase() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/unittest.py", line 215, in __init__ (self.__class__, methodName) ValueError: no such test method in <class 'unittest.TestCase'>: runTest >>> ``` Is there any other package or library that offers similar methods like `assertEqual()` that can be easily used without additional constraints?
2018/10/20
[ "https://Stackoverflow.com/questions/52907038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278326/" ]
I had similar in the past and end-up writing short custom assert which accept any condition as input. ``` import inspect def custom_assert(condition): if not condition: frame = inspect.currentframe() frame = inspect.getouterframes(frame)[1] call_signature = inspect.getframeinfo(frame[0]).code_context[0].strip() import re argument = re.search('\((.+)\)', call_signature).group(1) if '!=' in argument: argument = argument.replace('!=','==') elif '==' in argument: argument = argument.replace('==','!=') elif '<' in argument: argument = argument.replace('<','>=') elif '>' in argument: argument = argument.replace('>','<=') elif '>=' in argument: argument = argument.replace('>=','<') elif '<=' in argument: argument = argument.replace('<=','>') raise AssertionError(argument) if __name__ == '__main__': custom_assert(2 == 1) ``` Output: ``` Traceback (most recent call last): File "custom_assert.py", line 27, in <module> custom_assert(2 == 1) File "custom_assert.py", line 24, in custom_assert raise AssertionError(argument) AssertionError: 2 != 1 ```
The assertEqual or any other assertXxx() method expects the first argument to be an object reference. Generally we call the method as `self.assertEqual(first, second, msg=None)`. Here `self` satisfies the first expected argument. To circumvent this situation we can do the following: ``` from unittest import TestCase as tc def some_func(): dummy_obj = tc() tc.assertEqual(dummy_obj, 123, 123, msg='Not Equal') ``` The reason for this behavior is Hangover from XUnit frameworks.
69,843,983
I main java and just started on python, and I ran into this error when I was trying to create a class. Can anyone tell me what is wrong? ``` import rectangle a = rectangle(4, 5) print(a.getArea()) ``` this is what is in the rectangle class: ``` class rectangle: l = 0 w = 0 def __init__(self, l, w): self.l = l self.w = w def getArea(self): return self.l * self.w def getLength(self): return self.l def getWidth(self): return self.w def __str__(self): return "this is a", self.l, "by", self.w, "rectangle with an area of", self.getArea() ```
2021/11/04
[ "https://Stackoverflow.com/questions/69843983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16533352/" ]
I don't know what you have implemented in the rectangle module but I suspect that what you're actually looking for is this: ``` from rectangle import rectangle a = rectangle(4, 5) print(a.getArea()) ``` If not, give us an indication of what's in rectangle.py
your gonna need to specify what module the function is from so either import all the functions so change `import rectangle` to `from rectangle import *` or switch the `rectangle(4,5)` to `rectangle.rectangle(4,5)`
32,967,460
I have a django site that is deployed in production and already ran `python manage.py runserver` and so now the server is running on the port of `8000`. So what I want to do is to hit the running server and visited this on the domain `domainname.com:8000` and am not getting any response from the server. Should I be doing something else? Very noob sysadmin here. Note: Already set `debug=False` and `ALLOWED_HOSTS = ['domain.com']`
2015/10/06
[ "https://Stackoverflow.com/questions/32967460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1140228/" ]
> > I have a django site that is deployed in production and already ran python manage.py runserver > > > That's not how you deploy Django projects in production, cf <https://docs.djangoproject.com/en/1.8/howto/deployment/> The builtin dev server is only made for dev - it's unsafe, doesn't handle concurrent requests etc.
Additionally to @bruno desthuilliers answer, with which I totally agree, if nevertheless you insist, you have to run the server as: ``` python manage.py runserver 0.0.0.0:8000 ``` so that to let it listen to any interface. Relevant documentation: [django-admin](https://docs.djangoproject.com/en/1.8/ref/django-admin/#runserver-port-or-address-port).
61,114,206
Recently I created a 24 game solver with python Read this website if you do not know what the 24 game is: <https://www.pagat.com/adders/24.html> Here is the code: ``` from itertools import permutations, product, chain, zip_longest from fractions import Fraction as F solutions = [] def ask4(): num1 = input("Enter First Number: ") num2 = input("Enter Second Number: ") num3 = input("Enter Third Number: ") num4 = input("Enter Fourth Number: ") digits = [num1, num2, num3, num4] return list(digits) def solve(digits, solutions): digit_length = len(digits) expr_length = 2 * digit_length - 1 digit_perm = sorted(set(permutations(digits))) op_comb = list(product('+-*/', repeat=digit_length-1)) brackets = ([()] + [(x,y) for x in range(0, expr_length, 2) for y in range(x+4, expr_length+2, 2) if (x,y) != (0,expr_length+1)] + [(0, 3+1, 4+2, 7+3)]) for d in digit_perm: for ops in op_comb: if '/' in ops: d2 = [('F(%s)' % i) for i in d] else: d2 = d ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue=''))) for b in brackets: exp = ex[::] for insert_point, bracket in zip(b, '()'*(len(b)//2)): exp.insert(insert_point, bracket) txt = ''.join(exp) try: num = eval(txt) except ZeroDivisionError: continue if num == 24: if '/' in ops: exp = [(term if not term.startswith('F(') else term[2]) for term in exp] ans = ' '.join(exp).rstrip() print("Solution found:", ans) solutions.extend(ans) return ans print("No solution found for:", ' '.join(digits)) def main(): digits = ask4() solve(digits, solutions) print(len(solutions)) print("Bye") main() ``` Right now, my code only shows one solution for the numbers given, even when there are clearly more solutions. So if someone knows how to do this please help me Thanks
2020/04/09
[ "https://Stackoverflow.com/questions/61114206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10379866/" ]
On the network tab, you must select the post request and then go to the parameters you are sending and check if you are sending the data and if it is the right structure. This is how it looks like on Chrome there is where you check the data you are sending [![This is how it looks on Chrome](https://i.stack.imgur.com/fFC8J.png)](https://i.stack.imgur.com/fFC8J.png) Try modifying your handleFormSubmit ``` handleFormSubmit() { let apppointment = JSON.stringify({ title: this.state.title, appointment_date: this.state.appointment_date }) $.ajax({ url: '/appointments', type: "POST", data: apppointment, contentType: 'application/json' }) } ```
meaby you can try with axios instance ajax
15,969,213
I have recently been working on a pet project in python using flask. It is a simple pastebin with server-side syntax highlighting support with pygments. Because this is a costly task, I delegated the syntax highlighting to a celery task queue and in the request handler I'm waiting for it to finish. Needless to say this does no more than alleviate CPU usage to another worker, because waiting for a result still locks the connection to the webserver. Despite my instincts telling me to avoid premature optimization like the plague, I still couldn't help myself from looking into async. **Async** If have been following python web development lately, you surely have seen that async is everywhere. What async does is bringing back cooperative-multitasking, meaning each "thread" decides when and where to yield to another. This non-preemptive process is more efficient than OS-threads, but still has it's drawbacks. At the moment there seem to be 2 major approaches: * event/callback style multitasking * coroutines The first one provides concurrency through loosely-coupled components executed in an event loop. Although this is safer with respect to race conditions and provides for more consistency, it is considerably less intuitive and harder to code than preemptive multitasking. The other one is a more traditional solution, closer to threaded programming style, the programmer only having to manually switch context. Although more prone to race-conditions and deadlocks, it provides an easy drop-in solution. Most async work at the moment is done on what is known as **IO-bound** tasks, tasks that block to wait for input or output. This is usually accomplished through the use of polling and timeout based functions that can be called and if they return negatively, context can be switched. Despite the name, this could be applied to **CPU-bound** tasks too, which can be delegated to another worker(thread, process, etc) and then non-blockingly waited for to yield. Ideally, these tasks would be written in an async-friendly manner, but realistically this would imply separating code into small enough chunks not to block, preferably without scattering context switches after every line of code. This is especially inconvenient for existing synchronous libraries. --- Due to the convenience, I settled on using gevent for async work and was wondering how is to be dealt with CPU-bound tasks in an async environment(using futures, celery, etc?). How to use async execution models(gevent in this case) with traditional web frameworks such as flask? What are some commonly agreed-upon solutions to these problems in python(futures, task queues)? **EDIT:** To be more specific - How to use gevent with flask and how to deal with CPU-bound tasks in this context? **EDIT2:** Considering how Python has the GIL which prevents optimal execution of threaded code, this leaves only the multiprocessing option, in my case at least. This means either using *concurrent.futures* or some other external service dealing with processing(can open the doors for even something language agnostic). What would, in this case, be some popular or often-used solutions with gevent(**i.e.** celery)? - best practices
2013/04/12
[ "https://Stackoverflow.com/questions/15969213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492162/" ]
It should be thread-safe to do something like the following to separate cpu intensive tasks into asynchronous threads: ``` from threading import Thread def send_async_email(msg): mail.send(msg) def send_email(subject, sender, recipients, text_body, html_body): msg = Message(subject, sender = sender, recipients = recipients) msg.body = text_body msg.html = html_body thr = Thread(target = send_async_email, args = [msg]) thr.start() ``` IF you need something more complicated, then perhaps Flask-Celery or Multiprocessing library with "Pool" might be useful to you. I'm not too familiar with gevent though I can't imagine what more complexity you might need or why. I mean if you're attempting to have efficiency of a major world-website, then I'd recommend building C++ applications to do your CPU-intensive work, and then use Flask-celery or Pool to run that process. (this is what YouTube does when mixing C++ & Python)
How about simply using ThreadPool and Queue? You can then process your stuff in a seperate thread in a synchronous manner and you won't have to worry about blocking at all. Well, Python is not suited for CPU bound tasks in the first place, so you should also think of spawning subprocesses.
27,260,199
So I have this issue where libv8-3.16.14.3 fails to install, even though it deceptively tells you it did install. So the first sign of issue was when it did: ``` An error occurred while installing libv8 (3.16.14.3), and Bundler cannot continue. Make sure that `gem install libv8 -v '3.16.14.3'` succeeds before bundling. ``` During a `bundle install`. So I did some googling and came across [this response](https://stackoverflow.com/a/19674065/4005826) which when run: ``` gem install libv8 -v '3.16.14.3' -- --with-system-v8 Building native extensions with: '--with-system-v8' This could take a while... Successfully installed libv8-3.16.14.3 Parsing documentation for libv8-3.16.14.3 Done installing documentation for libv8 after 1 seconds 1 gem installed ``` Leads you to thinking it worked. but run `bundle install` again and see the error in question which is: ``` An error occurred while installing libv8 (3.16.14.3), and Bundler cannot continue. Make sure that `gem install libv8 -v '3.16.14.3'` succeeds before bundling. ``` The entire trace log can be seen below (caused by running `bundle install`): ``` Gem::Ext::BuildError: ERROR: Failed to build gem native extension. /Users/Adam/.rvm/rubies/ruby-2.1.5/bin/ruby extconf.rb creating Makefile Compiling v8 for x64 Using python 2.7.6 Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Unable to find a compiler officially supported by v8. It is recommended to use GCC v4.4 or higher Using compiler: g++ Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Unable to find a compiler officially supported by v8. It is recommended to use GCC v4.4 or higher ../src/cached-powers.cc:136:18: error: unused variable 'kCachedPowersLength' [-Werror,-Wunused-const-variable] static const int kCachedPowersLength = ARRAY_SIZE(kCachedPowers); ^ 1 error generated. make[1]: *** [/Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/cached-powers.o] Error 1 make: *** [x64.release] Error 2 /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/ext/libv8/location.rb:36:in `block in verify_installation!': libv8 did not install properly, expected binary v8 archive '/Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/tools/gyp/libv8_base.a'to exist, but it was not found (Libv8::Location::Vendor::ArchiveNotFound) from /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/ext/libv8/location.rb:35:in `each' from /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/ext/libv8/location.rb:35:in `verify_installation!' from /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/ext/libv8/location.rb:26:in `install!' from extconf.rb:7:in `<main>' GYP_GENERATORS=make \ build/gyp/gyp --generator-output="out" build/all.gyp \ -Ibuild/standalone.gypi --depth=. \ -Dv8_target_arch=x64 \ -S.x64 -Dv8_enable_backtrace=1 -Dv8_can_use_vfp2_instructions=true -Darm_fpu=vfpv2 -Dv8_can_use_vfp3_instructions=true -Darm_fpu=vfpv3 CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/allocation.o CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/atomicops_internals_x86_gcc.o CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/bignum.o CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/bignum-dtoa.o CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/cached-powers.o extconf failed, exit code 1 Gem files will remain installed in /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3 for inspection. Results logged to /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/extensions/x86_64-darwin-14/2.1.0/libv8-3.16.14.3/gem_make.out An error occurred while installing libv8 (3.16.14.3), and Bundler cannot continue. Make sure that `gem install libv8 -v '3.16.14.3'` succeeds before bundling. ``` What is going on. **Note:** I am doing all this on a mac.
2014/12/02
[ "https://Stackoverflow.com/questions/27260199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4005826/" ]
I got this to work by first using Homebrew to install V8: ``` $ brew install v8 ``` Then running the command you mentioned you found on Google: ``` $ gem install libv8 -v '3.16.14.3' -- --with-system-v8 ``` And finally re-running bundle install: ``` $ bundle install ```
As others have suggested: ``` $ brew install v8 $ gem install libv8 -v '3.16.14.3' -- --with-system-v8 $ bundle install ``` If that does not work, try running `bundle update`. Running `bundle update` in addition was the only way it worked
27,260,199
So I have this issue where libv8-3.16.14.3 fails to install, even though it deceptively tells you it did install. So the first sign of issue was when it did: ``` An error occurred while installing libv8 (3.16.14.3), and Bundler cannot continue. Make sure that `gem install libv8 -v '3.16.14.3'` succeeds before bundling. ``` During a `bundle install`. So I did some googling and came across [this response](https://stackoverflow.com/a/19674065/4005826) which when run: ``` gem install libv8 -v '3.16.14.3' -- --with-system-v8 Building native extensions with: '--with-system-v8' This could take a while... Successfully installed libv8-3.16.14.3 Parsing documentation for libv8-3.16.14.3 Done installing documentation for libv8 after 1 seconds 1 gem installed ``` Leads you to thinking it worked. but run `bundle install` again and see the error in question which is: ``` An error occurred while installing libv8 (3.16.14.3), and Bundler cannot continue. Make sure that `gem install libv8 -v '3.16.14.3'` succeeds before bundling. ``` The entire trace log can be seen below (caused by running `bundle install`): ``` Gem::Ext::BuildError: ERROR: Failed to build gem native extension. /Users/Adam/.rvm/rubies/ruby-2.1.5/bin/ruby extconf.rb creating Makefile Compiling v8 for x64 Using python 2.7.6 Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Unable to find a compiler officially supported by v8. It is recommended to use GCC v4.4 or higher Using compiler: g++ Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Unable to find a compiler officially supported by v8. It is recommended to use GCC v4.4 or higher ../src/cached-powers.cc:136:18: error: unused variable 'kCachedPowersLength' [-Werror,-Wunused-const-variable] static const int kCachedPowersLength = ARRAY_SIZE(kCachedPowers); ^ 1 error generated. make[1]: *** [/Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/cached-powers.o] Error 1 make: *** [x64.release] Error 2 /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/ext/libv8/location.rb:36:in `block in verify_installation!': libv8 did not install properly, expected binary v8 archive '/Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/tools/gyp/libv8_base.a'to exist, but it was not found (Libv8::Location::Vendor::ArchiveNotFound) from /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/ext/libv8/location.rb:35:in `each' from /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/ext/libv8/location.rb:35:in `verify_installation!' from /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/ext/libv8/location.rb:26:in `install!' from extconf.rb:7:in `<main>' GYP_GENERATORS=make \ build/gyp/gyp --generator-output="out" build/all.gyp \ -Ibuild/standalone.gypi --depth=. \ -Dv8_target_arch=x64 \ -S.x64 -Dv8_enable_backtrace=1 -Dv8_can_use_vfp2_instructions=true -Darm_fpu=vfpv2 -Dv8_can_use_vfp3_instructions=true -Darm_fpu=vfpv3 CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/allocation.o CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/atomicops_internals_x86_gcc.o CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/bignum.o CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/bignum-dtoa.o CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/cached-powers.o extconf failed, exit code 1 Gem files will remain installed in /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3 for inspection. Results logged to /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/extensions/x86_64-darwin-14/2.1.0/libv8-3.16.14.3/gem_make.out An error occurred while installing libv8 (3.16.14.3), and Bundler cannot continue. Make sure that `gem install libv8 -v '3.16.14.3'` succeeds before bundling. ``` What is going on. **Note:** I am doing all this on a mac.
2014/12/02
[ "https://Stackoverflow.com/questions/27260199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4005826/" ]
I got this to work by first using Homebrew to install V8: ``` $ brew install v8 ``` Then running the command you mentioned you found on Google: ``` $ gem install libv8 -v '3.16.14.3' -- --with-system-v8 ``` And finally re-running bundle install: ``` $ bundle install ```
This error is common with projects with therubyracer and the other answers didn't solve it for me. They helped though. Order of install seem to be the clue. ``` $ gem uninstall libv8 Successfully uninstalled libv8-3.16.14.13 $ gem install therubyracer -v '0.12.2' 2 gems installed $ bundle CRASH $ gem install libv8 -v '3.16.14.13' -- --with-system-v8 Successfully installed libv8-3.16.14.13 1 gem installed $ bundle SUKSESS ``` go figure, this is bad. But it solved it for me.
27,260,199
So I have this issue where libv8-3.16.14.3 fails to install, even though it deceptively tells you it did install. So the first sign of issue was when it did: ``` An error occurred while installing libv8 (3.16.14.3), and Bundler cannot continue. Make sure that `gem install libv8 -v '3.16.14.3'` succeeds before bundling. ``` During a `bundle install`. So I did some googling and came across [this response](https://stackoverflow.com/a/19674065/4005826) which when run: ``` gem install libv8 -v '3.16.14.3' -- --with-system-v8 Building native extensions with: '--with-system-v8' This could take a while... Successfully installed libv8-3.16.14.3 Parsing documentation for libv8-3.16.14.3 Done installing documentation for libv8 after 1 seconds 1 gem installed ``` Leads you to thinking it worked. but run `bundle install` again and see the error in question which is: ``` An error occurred while installing libv8 (3.16.14.3), and Bundler cannot continue. Make sure that `gem install libv8 -v '3.16.14.3'` succeeds before bundling. ``` The entire trace log can be seen below (caused by running `bundle install`): ``` Gem::Ext::BuildError: ERROR: Failed to build gem native extension. /Users/Adam/.rvm/rubies/ruby-2.1.5/bin/ruby extconf.rb creating Makefile Compiling v8 for x64 Using python 2.7.6 Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Unable to find a compiler officially supported by v8. It is recommended to use GCC v4.4 or higher Using compiler: g++ Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Unable to find a compiler officially supported by v8. It is recommended to use GCC v4.4 or higher ../src/cached-powers.cc:136:18: error: unused variable 'kCachedPowersLength' [-Werror,-Wunused-const-variable] static const int kCachedPowersLength = ARRAY_SIZE(kCachedPowers); ^ 1 error generated. make[1]: *** [/Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/cached-powers.o] Error 1 make: *** [x64.release] Error 2 /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/ext/libv8/location.rb:36:in `block in verify_installation!': libv8 did not install properly, expected binary v8 archive '/Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/tools/gyp/libv8_base.a'to exist, but it was not found (Libv8::Location::Vendor::ArchiveNotFound) from /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/ext/libv8/location.rb:35:in `each' from /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/ext/libv8/location.rb:35:in `verify_installation!' from /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/ext/libv8/location.rb:26:in `install!' from extconf.rb:7:in `<main>' GYP_GENERATORS=make \ build/gyp/gyp --generator-output="out" build/all.gyp \ -Ibuild/standalone.gypi --depth=. \ -Dv8_target_arch=x64 \ -S.x64 -Dv8_enable_backtrace=1 -Dv8_can_use_vfp2_instructions=true -Darm_fpu=vfpv2 -Dv8_can_use_vfp3_instructions=true -Darm_fpu=vfpv3 CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/allocation.o CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/atomicops_internals_x86_gcc.o CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/bignum.o CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/bignum-dtoa.o CXX(target) /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/cached-powers.o extconf failed, exit code 1 Gem files will remain installed in /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/gems/libv8-3.16.14.3 for inspection. Results logged to /Users/Adam/Dropbox/AisisGit/AisisPlatform/.bundle/gems/extensions/x86_64-darwin-14/2.1.0/libv8-3.16.14.3/gem_make.out An error occurred while installing libv8 (3.16.14.3), and Bundler cannot continue. Make sure that `gem install libv8 -v '3.16.14.3'` succeeds before bundling. ``` What is going on. **Note:** I am doing all this on a mac.
2014/12/02
[ "https://Stackoverflow.com/questions/27260199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4005826/" ]
This error is common with projects with therubyracer and the other answers didn't solve it for me. They helped though. Order of install seem to be the clue. ``` $ gem uninstall libv8 Successfully uninstalled libv8-3.16.14.13 $ gem install therubyracer -v '0.12.2' 2 gems installed $ bundle CRASH $ gem install libv8 -v '3.16.14.13' -- --with-system-v8 Successfully installed libv8-3.16.14.13 1 gem installed $ bundle SUKSESS ``` go figure, this is bad. But it solved it for me.
As others have suggested: ``` $ brew install v8 $ gem install libv8 -v '3.16.14.3' -- --with-system-v8 $ bundle install ``` If that does not work, try running `bundle update`. Running `bundle update` in addition was the only way it worked
3,442,920
I can't seem to find any information on debugging a python web application, specifically stepping through the execution of a web request. is this just not possible? if no, why not?
2010/08/09
[ "https://Stackoverflow.com/questions/3442920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39677/" ]
If you put ``` import pdb pdb.set_trace() ``` in your code, the web app will drop to a pdb debugger session upon executing `set_trace`. Also useful, is ``` import code code.interact(local=locals()) ``` which drops you to the python interpreter. Pressing Ctrl-d resumes execution. Still more useful, is ``` import IPython.Shell ipshell = IPython.Shell.IPShellEmbed() ipshell(local_ns=locals()) ``` which drops you into an IPython session (assuming you've installed IPython). Here too, pressing Ctrl-d resumes execution.
use Python Debbuger, `import pdb; pdb.set_trace()` exactly where you want to start debugging, and your terminal will pause in that line. More info here: <http://plone.org/documentation/kb/using-pdb>
3,442,920
I can't seem to find any information on debugging a python web application, specifically stepping through the execution of a web request. is this just not possible? if no, why not?
2010/08/09
[ "https://Stackoverflow.com/questions/3442920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39677/" ]
If you put ``` import pdb pdb.set_trace() ``` in your code, the web app will drop to a pdb debugger session upon executing `set_trace`. Also useful, is ``` import code code.interact(local=locals()) ``` which drops you to the python interpreter. Pressing Ctrl-d resumes execution. Still more useful, is ``` import IPython.Shell ipshell = IPython.Shell.IPShellEmbed() ipshell(local_ns=locals()) ``` which drops you into an IPython session (assuming you've installed IPython). Here too, pressing Ctrl-d resumes execution.
If you are running your web application through apache and [mod\_wsgi](http://code.google.com/p/modwsgi/wiki/DebuggingTechniques#Python_Interactive_Debugger) or [mod\_python](http://www.modpython.org/python10/), both provide some support for step through debugging with pdb. The trick is you have to run apache in foreground mode with the -X flag. On my Gentoo system I do this with (this is essentially the same command the apache init script uses replacing the -k start with the -X): ``` /usr/sbin/apache2 -D DEFAULT_VHOST -D INFO -D LANGUAGE -D SSL -D SSL_DEFAULT_VHOST -D PYTHON -d /usr/lib64/apache2 -f /etc/apache2/httpd.conf -X ```
3,442,920
I can't seem to find any information on debugging a python web application, specifically stepping through the execution of a web request. is this just not possible? if no, why not?
2010/08/09
[ "https://Stackoverflow.com/questions/3442920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39677/" ]
If you are running your web application through apache and [mod\_wsgi](http://code.google.com/p/modwsgi/wiki/DebuggingTechniques#Python_Interactive_Debugger) or [mod\_python](http://www.modpython.org/python10/), both provide some support for step through debugging with pdb. The trick is you have to run apache in foreground mode with the -X flag. On my Gentoo system I do this with (this is essentially the same command the apache init script uses replacing the -k start with the -X): ``` /usr/sbin/apache2 -D DEFAULT_VHOST -D INFO -D LANGUAGE -D SSL -D SSL_DEFAULT_VHOST -D PYTHON -d /usr/lib64/apache2 -f /etc/apache2/httpd.conf -X ```
use Python Debbuger, `import pdb; pdb.set_trace()` exactly where you want to start debugging, and your terminal will pause in that line. More info here: <http://plone.org/documentation/kb/using-pdb>
17,919,788
I tried to run my python scripts using crontab. As the amount of my python scripts accumulates, it is hard to manage in crontab. Then I tries two python schedule task libraries named [Advanced Python Scheduler](http://pythonhosted.org/APScheduler/) and [schedule](https://github.com/dbader/schedule). The two libraries are quite the same in use, for example: ``` import schedule import time def job(): print("I'm working...") schedule.every(10).minutes.do(job) schedule.every().hour.do(job) schedule.every().day.at("10:30").do(job) while True: schedule.run_pending() time.sleep(1) ``` The library uses the `time` module to wait until the exact moment to execute the task. But the script has to run all the time and consumes tens of Megabytes memory. So I want to ask it is a better way to handle schedule jobs using the library? Thanks.
2013/07/29
[ "https://Stackoverflow.com/questions/17919788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/975222/" ]
In 2013 - when this question was created - there were not as many workflow/scheduler management tools freely available on the market as they are today. So, writing this answer in 2021, I would suggest using Crontab as long as you have only few scripts on very few machines. With a growing collection of scripts, the need for better monitoring/logging or pipelining you should consider using a dedicated tool for that ( like [Airflow](https://airflow.apache.org/), [N8N](https://n8n.io), [Luigi](https://github.com/spotify/luigi) ... )
One way is to use [management commands](https://docs.djangoproject.com/en/dev/howto/custom-management-commands/) and setup a crontab to run those. We use that in production and it works really well. Another is to use something like celery to [schedule tasks](http://docs.celeryproject.org/en/latest/reference/celery.schedules.html).
15,096,667
I'm trying to convert code from TCL into python using Tkinter. I was wondering what would be the equivalent code in Tkinter for "spawn ssh", "expect", and "send"? For example, my simple tcl program would be something like: ``` spawn ssh root@138.120.###.### expect "(yes/no)?" {send -- "yes\r"} expect "password" {send -- "thepassword\r"} ```
2013/02/26
[ "https://Stackoverflow.com/questions/15096667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1988580/" ]
You could try to use [pexpect](http://www.noah.org/wiki/pexpect). Expect is used to automate other command line tools. Edit: Of curse you could just try to execute `package require Expect` through Tkinter, but what benefit would that have over a pure Tcl script? After all you write Tcl code then, wraped in python. Another Edit: Tkinter is used to get access to Tk (the cool GUI Toolkit :P) from python, and it works by calling Tcl commands somewhere down the line. So, you can convert EVERY tcl programm to python (if you have the right tcl libs installed of course).
[pxpect](http://pexpect.sourceforge.net) has a module called pxssh, that takes a lot of the the work out of manipulating simple ssh sessions. I found that this wasn't sufficient for heavy automation and wrote [remote](http://gethub.com/Telenav/python-remote) as an add-on to increase error handling. using pxssh ``` from pxssh import pxssh p = pxssh() p.login('host', 'user', 'password') p.send('command') ``` using remote ``` from remote import remote r = remote('host', 'user', 'password') if r.login(): r.send('command') ``` I'm not sure about the Tkinter use case, my only assumption is that you are using it to craft a gui and there are many tutorials for it. I've used <http://sebsauvage.net/python/gui/> before and it compares both Tkinter and wxPython.
22,791,074
![enter image description here](https://i.stack.imgur.com/U10sa.jpg) what function should i use to draw the above performance profile of different algorithms, the running time data is from python implementation, stored in lists for different algorithm. Is there any build-in function in Python or Matlab to draw this kind of figure automatically? Thanks
2014/04/01
[ "https://Stackoverflow.com/questions/22791074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3029108/" ]
You can absolutely have a state without a URL. In fact, none of your states need URLs. That's a core part of the design. Having said that, I wouldn't do what you did above. If you want two states to have the same URL, create an [abstract parent state](https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#abstract-states), assign a URL to it, and make the two states children of it (with no URL for either one).
To add to the other answer, Multiple Named Views do not use a URL. From the docs: > > If you define a views object, your state's templateUrl, template and > templateProvider will be ignored. So in the case that you need a > parent layout of these views, you can define an abstract state that > contains a template, and a child state under the layout state that > contains the 'views' object. > > > The reason for using named views is so that you can have more than one ui-view per template or in other words multiple views inside a single state. This way, you can change the parts of your site using your routing even if the URL does not change and you can also reuse data in different templates because it's a component with it's own controller and view. See [Angular Routing using ui-router](https://scotch.io/tutorials/angular-routing-using-ui-router) for an in-depth explanation with examples.
25,185,015
I am using python request module for doing HTTP communications. I was using proxy before doing any communication. ``` import requests proxy = {'http': 'xxx.xxx.xxx.xxx:port'} OR proxy = {'http': 'http://xxx.xxx.xxx.xxx:port'} OR proxy = {'http://xxx.xxx.xxx.xxx:port'} requests.get(url, proxies = proxy) ``` I am using the above code to add the proxy to the request object. But its seems like proxy is not working. Requests module is taking my network IP and firing the request. Are there any bug or issue with the request module or any other know issue or is there anything i am missing.
2014/08/07
[ "https://Stackoverflow.com/questions/25185015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000683/" ]
Try this: ``` proxy = {'http': 'http://xxx.xxx.xxx.xxx:port'} ``` I guess you just missed the `http://` in the value of the proxy dict. Check: <http://docs.python-requests.org/en/latest/user/advanced/#proxies>
[Documentation](http://docs.python-requests.org/en/latest/user/advanced/#proxies) says: > > If you need to use a proxy, you can configure individual requests with > the proxies argument to any request method: > > > ``` import requests proxies = {"http": "http://10.10.1.10:3128"} requests.get("http://example.org", proxies=proxies) ``` Here proxies["http"] = "`http://xxx.xxx.xxx.xxx:port`". It seems you lack **http://**
61,226,690
I am relatively new to Python so please pardon my ignorance. I want to know answer to following questions 1. How does pip know the location to install packages that it installs? After a built of trial and error I suspect that it maybe hardcoded at time of installation. 2. Are executables like pip.exe what they call frozen binaries? In essence, does it mean that pip.exe will run without python. Again after a bit of trial and error i suspect that it requires a python installation to execute. P.S: I know about sys.prefix,sys.executable and sys.exec\_prefix. If there is anything else on which the questions i asked on depends, pls link me to same.
2020/04/15
[ "https://Stackoverflow.com/questions/61226690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10796482/" ]
as I understand you only want to save user input only if contains text so you have to clean the user input from HTML then check the output length ``` var regex = /(<([^>]+)>)/ig body = "<p>test</p>" hasText = !!body.replace(regex, "").length; if(hasText) save() ```
This worked for me so it wouldn't escape images. ``` function isQuillEmpty(value: string) { if (value.replace(/<(.|\n)*?>/g, '').trim().length === 0 && !value.includes("<img")) { return true; } return false; } ```
37,308,794
I'm new to this and trying to deploy a first app to the app engine. However, when i try to i get this message: "This application does not exist (app\_id=u'udacity')." I fear it might have to do with the app.yaml file so i'll just leave here what i have there: application: udacity version: 1 runtime: python27 api\_version: 1 threadsafe: yes handlers: - url: /favicon.ico static\_files: favicon.ico upload: favicon.ico * url: /.\* script: main.app libraries: - name: webapp2 version: "2.5.2" Thanks in advance.
2016/05/18
[ "https://Stackoverflow.com/questions/37308794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6002144/" ]
Blocks are normal objects so you can store them in NSArray/NSDictionary. Having that said the implementation is straightforward. ``` #import <Foundation/Foundation.h> /** LBNotificationCenter.h */ typedef void (^Observer)(NSString *name, id data); @interface LBNotificationCenter : NSObject - (void)addObserverForName:(NSString *)name block:(Observer)block; - (void)removeObserverForName:(NSString *)name block:(Observer)block; - (void)postNotification:(NSString *)name data:(id)data; @end /** LBNotificationCenter.m */ @interface LBNotificationCenter () @property (strong, nonatomic) NSMutableDictionary <id, NSMutableArray <Observer> *> *observers; @end @implementation LBNotificationCenter - (instancetype)init { self = [super init]; if (self) { _observers = [NSMutableDictionary new]; } return self; } - (void)addObserverForName:(NSString *)name block:(Observer)block { // check name and block for presence... NSMutableArray *nameObservers = self.observers[name]; if (nameObservers == nil) { nameObservers = (self.observers[name] = [NSMutableArray new]); } [nameObservers addObject:block]; } - (void)removeObserverForName:(NSString *)name block:(Observer)block { // check name and block for presence... NSMutableArray *nameObservers = self.observers[name]; // Some people might argue that this check is not needed // as Objective-C allows messaging nil // I prefer to keep it explicit if (nameObservers == nil) { return; } [nameObservers removeObject:block]; } - (void)postNotification:(NSString *)name data:(id)data { // check name and data for presence... NSMutableArray *nameObservers = self.observers[name]; if (nameObservers == nil) { return; } for (Observer observer in nameObservers) { observer(name, data); } } @end int main(int argc, const char * argv[]) { @autoreleasepool { NSString *const Notification1 = @"Notification1"; NSString *const Notification2 = @"Notification2"; LBNotificationCenter *notificationCenter = [LBNotificationCenter new]; Observer observer1 = ^(NSString *name, id data) { NSLog(@"Observer1 is called for name: %@ with some data: %@", name, data); }; Observer observer2 = ^(NSString *name, id data) { NSLog(@"Observer2 is called for name: %@ with some data: %@", name, data); }; [notificationCenter addObserverForName:Notification1 block:observer1]; [notificationCenter addObserverForName:Notification2 block:observer2]; [notificationCenter postNotification:Notification1 data:@"Some data"]; [notificationCenter postNotification:Notification2 data:@"Some data"]; [notificationCenter removeObserverForName:Notification1 block:observer1]; // no observer is listening at this point so no logs for Notification1... [notificationCenter postNotification:Notification1 data:@"Some data"]; [notificationCenter postNotification:Notification2 data:@"Some data"]; } return 0; } ```
Why don't you just add the blocks into the `NSDictionary` ? You can do it like it's explained [in this answer](https://stackoverflow.com/questions/6364648/keep-blocks-inside-a-dictionary)
38,435,845
I am newbie to elasticsearch, I know there is two official client elasticsearch supplies, but when I use the python elasticsearch, i can't find how to use the transport client.. I read the whole doc which is as following: ``` https://elasticsearch-py.readthedocs.io/en/master/index.html ``` I also search some docs, i can't find the way to use elasticsearch with python.also, in one doc, it says: > > Using the native protocol from anything other than Java is not > recommended, as it would entail implementing a lot of custom > serialization. > > > does this mean python elasticsearch can't use transport client?
2016/07/18
[ "https://Stackoverflow.com/questions/38435845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6114947/" ]
The transport client is written in Java, so the only way to use it from Python is by switching to Jython.
I think the previous answer is out of date now, if this is [the transport client you mean](https://elasticsearch-py.readthedocs.io/en/master/transports.html). I've made use of this API to do things like use the [\_rank\_eval](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-rank-eval.html) API, which is still considered "experimental" so hasn't made it into the official client yet. ``` def rank_eval(self, query, ratings, metric_name): res = self.es.transport.perform_request( "GET", "/%s/_rank_eval" % INDEX, body=self.rank_request(query, ratings, metric_name), ) return res ```
56,415,470
IPython 7.5 documentation states: > > Change to Nested Embed > > > The introduction of the ability to run async code had some effect on the IPython.embed() API. By default, embed > will not allow you to run asynchronous code unless an event loop is specified. > > > However, there seem to be no description how to specify the event loop, in the documentation. Running: ```py import IPython IPython.embed() ``` and then ``` In [1]: %autoawait on In [2]: %autoawait IPython autoawait is `on`, and set to use `<function _pseudo_sync_runner at 0x00000000066DEF28>` In [3]: import asyncio In [4]: await asyncio.sleep(1) ``` Gives: ``` --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) ~\Envs\[redacted]\lib\site-packages\IPython\core\async_helpers.py in _pseudo_sync_runner(coro) 71 # TODO: do not raise but return an execution result with the right info. 72 raise RuntimeError( ---> 73 "{coro_name!r} needs a real async loop".format(coro_name=coro.__name__) 74 ) 75 RuntimeError: 'run_cell_async' needs a real async loop ``` --- On the other hand, running: ```py import IPython IPython.embed(using='asyncio') ``` and then: ``` In [1]: %autoawait on In [2]: %autoawait IPython autoawait is `on`, and set to use `asyncio` In [3]: import asyncio In [4]: await asyncio.sleep(1) ``` Gives: ``` --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) ~\Envs\[redacted]\lib\site-packages\IPython\core\async_helpers.py in __call__(self, coro) 25 import asyncio 26 ---> 27 return asyncio.get_event_loop().run_until_complete(coro) 28 29 def __str__(self): c:\python35-64\Lib\asyncio\base_events.py in run_until_complete(self, future) 452 future.add_done_callback(_run_until_complete_cb) 453 try: --> 454 self.run_forever() 455 except: 456 if new_task and future.done() and not future.cancelled(): c:\python35-64\Lib\asyncio\base_events.py in run_forever(self) 406 self._check_closed() 407 if self.is_running(): --> 408 raise RuntimeError('This event loop is already running') 409 if events._get_running_loop() is not None: 410 raise RuntimeError( RuntimeError: This event loop is already running ``` ```
2019/06/02
[ "https://Stackoverflow.com/questions/56415470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6543759/" ]
``` from IPython import embed import nest_asyncio nest_asyncio.apply() ``` Then `embed(using='asyncio')` might somewhat work. I don't know why they don't give us a real solution though.
This seems to be possible, but you have to use `ipykernel.embed.embed_kernel()` instead of `IPython.embed()`. `ipykernel` requires you to connect to the embedded kernel remotely from a separate jupyter console though, so it is not as convenient as just being able to spawn the shell on the same window, but at least it seems to work.
62,175,337
I want to fetch the next 5 records after the specific index. For example, this is my dataframe: ``` Id Name code 1 java 45 2 python 78 3 c 65 4 c++ 25 5 html 74 6 css 63 7 javascript 45 8 php 44 9 Ajax 88 10 jQuery 92 ``` When i provide the index value as `3` then the code must fetch the next 5 values from `3`. So the result should look like: ``` Id Name code 3 c 65 4 c++ 25 5 html 74 6 css 63 7 javascript 45 ``` I do not understand how to do this. My code is not working as I want it to. I am using this code for fetching the next 5 records: ``` data = df.iloc[df.index.get_loc(indexid):+5] ```
2020/06/03
[ "https://Stackoverflow.com/questions/62175337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10971762/" ]
Set up properties on the file attached to the solution, basically you need to make sure the file is included to the solution output: 1. Set the `Build Action` property to `Content`. 2. Set the `Copy to the Output Directory` property to `Copy Always`. For example, if the file is added to the project and you select it in the Solution Explorer and go to the Properties window you may see the following: [![enter image description here](https://i.stack.imgur.com/hPVOV.png)](https://i.stack.imgur.com/hPVOV.png) It will be added automatically to the output folder along with other add-in files. So, you will just have to rebuild the installer based on your output. See [Deploy an Office solution by using Windows Installer](https://learn.microsoft.com/en-us/visualstudio/vsto/deploying-an-office-solution-by-using-windows-installer?view=vs-2019) for more information.
You really need to add that that utility to you installer project. Or you can embed the utility as a resource in your dll, extract it at run-time, copy to some folder, and execute.
62,175,337
I want to fetch the next 5 records after the specific index. For example, this is my dataframe: ``` Id Name code 1 java 45 2 python 78 3 c 65 4 c++ 25 5 html 74 6 css 63 7 javascript 45 8 php 44 9 Ajax 88 10 jQuery 92 ``` When i provide the index value as `3` then the code must fetch the next 5 values from `3`. So the result should look like: ``` Id Name code 3 c 65 4 c++ 25 5 html 74 6 css 63 7 javascript 45 ``` I do not understand how to do this. My code is not working as I want it to. I am using this code for fetching the next 5 records: ``` data = df.iloc[df.index.get_loc(indexid):+5] ```
2020/06/03
[ "https://Stackoverflow.com/questions/62175337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10971762/" ]
So, To whomever it may be useful, on top of Eugene's answer, what was missing is that I needed to add the Content files to my project output. To do that, right-click on your Setup project and Add...> Project Output...> Content Files. [![enter image description here](https://i.stack.imgur.com/XRq9m.png)](https://i.stack.imgur.com/XRq9m.png) Then, when building the solution and deploying it, PuTTY was actually copied to the installation folder of the client! Arnaud
You really need to add that that utility to you installer project. Or you can embed the utility as a resource in your dll, extract it at run-time, copy to some folder, and execute.
62,579,298
I have a data frame that looks like this: ``` name Title abc 'Tech support' xyz 'UX designer' ghj 'Manager IT' ... .... ``` I want to iterate through the data frame and using `df.str.contains` make another column that will categorize those jobs. There are 8 categories. The output will be : ``` name Title category abc 'Tech support' 'Support' xyz 'UX designer' 'Design' ghj 'Manager IT' 'Management' ... .... .... ``` here's what I've tried so far: ``` for i in range(len(df)): if df.Title[i].str.contains("Support"): df.category[i]=="Support" elif df.Title[i].str.contains("designer"): df.category[i]=="Design" else df.Title[i].str.contains("Manager"): df.category[i]=="Management" ``` of course , I'm a noob at programming and this throws the error: ``` File "<ipython-input-29-d9457f9cb172>", line 6 else df.Title[i].str.contains("Manager"): ^ SyntaxError: invalid syntax ```
2020/06/25
[ "https://Stackoverflow.com/questions/62579298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12724372/" ]
You can do something like this: ``` cat_dict = {"Support":"Support", "designer":"Designer", "Manager": "Management"} df['category'] = (df['Title'].str.extract(fr"\b({'|'.join(cat_dict.keys())})\b")[0] .map(cat_dict) ) ```
General syntax of python if statement is: ``` if test expression: Body of if elif test expression: Body of elif else: Body of else ``` As you can see in the syntax, to evaluate a *test expression*, it should be in the *if* or in the *elif* construct. The code throws the syntax error as the test expression is placed in the *else* construct. Consider changing the last *else* to *elif* and add a fall back case for error like: ``` else: df.category[i]=="Others" ```
62,579,298
I have a data frame that looks like this: ``` name Title abc 'Tech support' xyz 'UX designer' ghj 'Manager IT' ... .... ``` I want to iterate through the data frame and using `df.str.contains` make another column that will categorize those jobs. There are 8 categories. The output will be : ``` name Title category abc 'Tech support' 'Support' xyz 'UX designer' 'Design' ghj 'Manager IT' 'Management' ... .... .... ``` here's what I've tried so far: ``` for i in range(len(df)): if df.Title[i].str.contains("Support"): df.category[i]=="Support" elif df.Title[i].str.contains("designer"): df.category[i]=="Design" else df.Title[i].str.contains("Manager"): df.category[i]=="Management" ``` of course , I'm a noob at programming and this throws the error: ``` File "<ipython-input-29-d9457f9cb172>", line 6 else df.Title[i].str.contains("Manager"): ^ SyntaxError: invalid syntax ```
2020/06/25
[ "https://Stackoverflow.com/questions/62579298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12724372/" ]
You can do something like this: ``` cat_dict = {"Support":"Support", "designer":"Designer", "Manager": "Management"} df['category'] = (df['Title'].str.extract(fr"\b({'|'.join(cat_dict.keys())})\b")[0] .map(cat_dict) ) ```
This answer: [Iterate through rows and change value](https://stackoverflow.com/questions/56187195/iterate-through-rows-in-a-dataframe-and-change-value-of-a-column-based-on-other) should get you going! Lmk, if you have more questions!
62,579,298
I have a data frame that looks like this: ``` name Title abc 'Tech support' xyz 'UX designer' ghj 'Manager IT' ... .... ``` I want to iterate through the data frame and using `df.str.contains` make another column that will categorize those jobs. There are 8 categories. The output will be : ``` name Title category abc 'Tech support' 'Support' xyz 'UX designer' 'Design' ghj 'Manager IT' 'Management' ... .... .... ``` here's what I've tried so far: ``` for i in range(len(df)): if df.Title[i].str.contains("Support"): df.category[i]=="Support" elif df.Title[i].str.contains("designer"): df.category[i]=="Design" else df.Title[i].str.contains("Manager"): df.category[i]=="Management" ``` of course , I'm a noob at programming and this throws the error: ``` File "<ipython-input-29-d9457f9cb172>", line 6 else df.Title[i].str.contains("Manager"): ^ SyntaxError: invalid syntax ```
2020/06/25
[ "https://Stackoverflow.com/questions/62579298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12724372/" ]
You can do something like this: ``` cat_dict = {"Support":"Support", "designer":"Designer", "Manager": "Management"} df['category'] = (df['Title'].str.extract(fr"\b({'|'.join(cat_dict.keys())})\b")[0] .map(cat_dict) ) ```
Here you go: ```py import pandas as pd from io import StringIO df = pd.read_csv(StringIO(""" name Title abc Tech support xyz UX designer ghj Manager IT """), sep='\s{2,}', engine='python') masks = [df.Title.str.lower().str.contains('support'), df.Title.str.lower().str.contains('designer'), df.Title.str.lower().str.contains('manager') ] values = [ 'Support', 'Design', 'Management' ] import numpy as np df['Category'] = np.select(masks, values, default='Unknown') print(df) ``` Output: ``` name Title Category 0 abc Tech support Support 1 xyz UX designer Design 2 ghj Manager IT Management ```
57,309,209
I am working on a data frame with DateTimeIndex of hourly temperature data spanning a couple of years. I want to add a column with the minimum temperature between 20:00 of a day and 8:00 of the *following* day. Daytime temperatures - from 8:00 to 20:00 - are not of interest. The result can either be at the same hourly resolution of the original data or be resampled to days. I have researched a number of strategies to solve this, but am unsure about the most efficienct (in terms of primarily coding efficiency and secondary computing efficiency) respectively pythonic way to do this. Some of the possibilities I have come up with: 1. Attach a column with labels 'day', 'night' depending on `df.index.hour` and use `group_by` or `df.loc` to find the minimum 2. Resample to 12h and drop every second value. Not sure how I can make the resampling period start at 20:00. 3. Add a multi-index - I guess this is similar to approach 1, but feels a bit over the top for what I'm trying to achieve. 4. Use `df.between_time` (<https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.between_time.html#pandas.DataFrame.between_time>) though I'm not sure if the date change over midnight will make this a bit messy. 5. Lastly there is some discussion about combining rolling with a stepping parameter as new pandas feature: <https://github.com/pandas-dev/pandas/issues/15354> Original df looks like this: ``` datetime temp 2009-07-01 01:00:00 17.16 2009-07-01 02:00:00 16.64 2009-07-01 03:00:00 16.21 #<-- minimum for the night 2009-06-30 (previous date since periods starts 2009-06-30 20:00) ... ... 2019-06-24 22:00:00 14.03 #<-- minimum for the night 2019-06-24 2019-06-24 23:00:00 18.87 2019-06-25 00:00:00 17.85 2019-06-25 01:00:00 17.25 ``` I want to get something like this (min temp from day 20:00 to day+1 8:00): ``` datetime temp 2009-06-30 23:00:00 16.21 2009-07-01 00:00:00 16.21 2009-07-01 01:00:00 16.21 2009-07-01 02:00:00 16.21 2009-07-01 03:00:00 16.21 ... ... 2019-06-24 22:00:00 14.03 2019-06-24 23:00:00 14.03 2019-06-25 00:00:00 14.03 2019-06-25 01:00:00 14.03 ``` or a bit more succinct: ``` datetime temp 2009-06-30 16.21 ... ... 2019-06-24 14.03 ```
2019/08/01
[ "https://Stackoverflow.com/questions/57309209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7057547/" ]
Use the `base` option to `resample`: ``` rs = df.resample('12h', base=8).min() ``` Then keep only the rows for 20:00: ``` rs[rs.index.hour == 20] ```
you can use `TimeGrouper` with `freq=12h` and `base=8` to chunk the dataframe every 12h from 20:00 - (+day)08:00, then you can just use `.min()` try this: ```py import pandas as pd from io import StringIO s = """ datetime temp 2009-07-01 01:00:00 17.16 2009-07-01 02:00:00 16.64 2009-07-01 03:00:00 16.21 2019-06-24 22:00:00 14.03 2019-06-24 23:00:00 18.87 2019-06-25 00:00:00 17.85 2019-06-25 01:00:00 17.25""" df = pd.read_csv(StringIO(s), sep="\s\s+") df['datetime'] = pd.to_datetime(df['datetime']) result = df.sort_values('datetime').groupby(pd.Grouper(freq='12h', base=8, key='datetime')).min()['temp'].dropna() print(result) ``` Output: ``` datetime 2009-06-30 20:00:00 16.21 2019-06-24 20:00:00 14.03 Name: temp, dtype: float64 ```
54,403,437
I want to script with python using Notepad ++ but it works strangely, actually it does not work, so I have pycharm an everything is going well but in notepad ++ when I save file with .py and click run it does not work is there a step by step instruction to follow? I have same problem with sublime text editor so I am lucky with just Pycharm all of the others has confused me please help me.
2019/01/28
[ "https://Stackoverflow.com/questions/54403437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10979398/" ]
You call `setPreferredSize` twice, which results in the first call doing basically nothing. That means you always have a `preferredSize` equal to the dimensions of the second image. What you *should* do is to set the size to `new Dimension(image.getWidth() + image2.getWidth(), image2.getHeight())` assuming both have the same height. If that is not the case set the `height` as the maximum of both images. Secondly you need to offset the second image from the first image exactly by the width of the first image: ``` g2d.drawImage(image, 0, 0, this); g2d.drawImage(image2, image.getWidth(), 0, this); ```
I found some errors in your code and I did not got what are you trying to do... 1] Over there you are actually not using the first setup ``` Dimension dimension = new Dimension(image.getWidth(), image.getHeight()); setPreferredSize(dimension); //not used Dimension dimension2 = new Dimension(image2.getWidth(), image2.getHeight()); setPreferredSize(dimension2); //because overridden by this ``` It means, panel is having dimensions same as the `image2`, you should to set it as follows: * height as max of the heights of both images * width at least as summarize of widths of both pictures (if you want to paint them in same panel, as you are trying) 2] what is the `image` and `image2` datatypes? in the block above you have `File` but with different naming variables, `File` class ofcourse dont have width or height argument I am assuming its [Image](https://docs.oracle.com/javase/7/docs/api/java/awt/Image.html) due usage in `Graphics.drawImage`, then: You need to **setup preferred size** as I mentioned: * height to max value of height from images * width at least as summarize value of each widths Dimensions things: ``` Dimension panelDim = new Dimension(image.getWidth() + image2.getWidth(),Math.max(image.getHeight(),image2.getHeight())); setPreferredSize(panelDim) ``` Then you can **draw images in the original size** *- due coordinates are having 0;0 in the left top corner and right bottom is this.getWidth(); this.getHeight()* - check eg. [this explanation](https://docs.oracle.com/javase/tutorial/2d/overview/coordinate.html) - you need to start paint in the left bottom corner and then move to correct position increase "X" as the width of first image ``` @Override public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; /* public abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) */ //start to paint at [0;0] g2d.drawImage(image, 0, 0, this); //start to paint just on the right side of first image (offset equals to width of first picture)- next pixel on the same line, on the bottom of the screen g2d.drawImage(image2,image2.getWidth()+1, 0, this); } ``` I didn't had a chance to test it, but it should be like this. Important things are * you need to have proper dimensions for fitting both images * screen coordinates starts in the left top corner of the screens [0;0]
54,403,437
I want to script with python using Notepad ++ but it works strangely, actually it does not work, so I have pycharm an everything is going well but in notepad ++ when I save file with .py and click run it does not work is there a step by step instruction to follow? I have same problem with sublime text editor so I am lucky with just Pycharm all of the others has confused me please help me.
2019/01/28
[ "https://Stackoverflow.com/questions/54403437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10979398/" ]
You call `setPreferredSize` twice, which results in the first call doing basically nothing. That means you always have a `preferredSize` equal to the dimensions of the second image. What you *should* do is to set the size to `new Dimension(image.getWidth() + image2.getWidth(), image2.getHeight())` assuming both have the same height. If that is not the case set the `height` as the maximum of both images. Secondly you need to offset the second image from the first image exactly by the width of the first image: ``` g2d.drawImage(image, 0, 0, this); g2d.drawImage(image2, image.getWidth(), 0, this); ```
I would join the images whenever something changes and draw them to another buffered image. Then I can just redraw the combined image whenever the panel needs to be redrawn. [![Application](https://i.stack.imgur.com/d8QSk.png)](https://i.stack.imgur.com/d8QSk.png) ``` import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; public class SideBySideImagePanel extends JPanel { private static final long serialVersionUID = 5868633578732134172L; private BufferedImage left; private BufferedImage right; private BufferedImage join; public SideBySideImagePanel() { ClassLoader loader = this.getClass().getClassLoader(); BufferedImage left = null, right = null; try { left = ImageIO.read(loader.getResourceAsStream("resources/Android.png")); right = ImageIO.read(loader.getResourceAsStream("resources/Java.png")); } catch (IOException e) { e.printStackTrace(); } this.setLeft(left); this.setRight(right); } public BufferedImage getLeft() { return left; } public void setLeft(BufferedImage left) { this.left = left; } public BufferedImage getRight() { return right; } public void setRight(BufferedImage right) { this.right = right; } @Override public void invalidate() { super.invalidate(); join = combineImages(left, right); setPreferredSize(new Dimension(join.getWidth(), join.getHeight())); } @Override public void paintComponent(Graphics g) { g.drawImage(join, 0, 0, null); } private BufferedImage combineImages(BufferedImage left, BufferedImage right) { int width = left.getWidth() + right.getWidth(); int height = Math.max(left.getHeight(), right.getHeight()); BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics g = combined.getGraphics(); g.drawImage(left, 0, 0, null); g.drawImage(right, left.getWidth(), 0, null); return combined; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame("Image Joiner"); SideBySideImagePanel panel = new SideBySideImagePanel(); frame.getContentPane().add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.pack(); frame.setVisible(true); } }); } } ```
54,403,437
I want to script with python using Notepad ++ but it works strangely, actually it does not work, so I have pycharm an everything is going well but in notepad ++ when I save file with .py and click run it does not work is there a step by step instruction to follow? I have same problem with sublime text editor so I am lucky with just Pycharm all of the others has confused me please help me.
2019/01/28
[ "https://Stackoverflow.com/questions/54403437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10979398/" ]
The logic of the math was incorrect. See the `getPreferredSize()` method for the correct way to calculate the required width, and the changes to the `paintComponent(Graphics)` method to place them side-by-side. An alternative (not examined in this answer) is to put each image into a `JLabel`, then add the labels to a panel with an appropriate layout. This is the effect of the changes: [![enter image description here](https://i.stack.imgur.com/zAzk5.jpg)](https://i.stack.imgur.com/zAzk5.jpg) ``` import java.awt.*; import java.awt.image.BufferedImage; import javax.swing.*; import java.net.*; import javax.imageio.ImageIO; public class ObrazPanel extends JPanel { private BufferedImage image; private BufferedImage image2; public ObrazPanel() throws MalformedURLException { super(); URL imageFile = new URL("https://i.stack.imgur.com/7bI1Y.jpg"); URL imageFile2 = new URL("https://i.stack.imgur.com/aH5zB.jpg"); try { image = ImageIO.read(imageFile); image2 = ImageIO.read(imageFile2); } catch (Exception e) { System.err.println("Blad odczytu obrazka"); e.printStackTrace(); } } @Override public Dimension getPreferredSize() { int w = image.getWidth() + image2.getWidth(); int h1 = image.getHeight(); int h2 = image2.getHeight(); int h = h1>h2 ? h1 : h2; return new Dimension(w,h); } @Override public void paintComponent(Graphics g) { // always best to start with this.. super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.drawImage(image, 0, 0, this); g2d.drawImage(image2, image.getWidth(), 0, this); } public static void main(String[] args) { Runnable r = new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception useDefault) { } ObrazPanel o; try { o = new ObrazPanel(); JFrame f = new JFrame(o.getClass().getSimpleName()); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setLocationByPlatform(true); f.setContentPane(o); f.pack(); f.setMinimumSize(f.getSize()); f.setVisible(true); } catch (MalformedURLException ex) { ex.printStackTrace(); } } }; SwingUtilities.invokeLater(r); } } ```
I found some errors in your code and I did not got what are you trying to do... 1] Over there you are actually not using the first setup ``` Dimension dimension = new Dimension(image.getWidth(), image.getHeight()); setPreferredSize(dimension); //not used Dimension dimension2 = new Dimension(image2.getWidth(), image2.getHeight()); setPreferredSize(dimension2); //because overridden by this ``` It means, panel is having dimensions same as the `image2`, you should to set it as follows: * height as max of the heights of both images * width at least as summarize of widths of both pictures (if you want to paint them in same panel, as you are trying) 2] what is the `image` and `image2` datatypes? in the block above you have `File` but with different naming variables, `File` class ofcourse dont have width or height argument I am assuming its [Image](https://docs.oracle.com/javase/7/docs/api/java/awt/Image.html) due usage in `Graphics.drawImage`, then: You need to **setup preferred size** as I mentioned: * height to max value of height from images * width at least as summarize value of each widths Dimensions things: ``` Dimension panelDim = new Dimension(image.getWidth() + image2.getWidth(),Math.max(image.getHeight(),image2.getHeight())); setPreferredSize(panelDim) ``` Then you can **draw images in the original size** *- due coordinates are having 0;0 in the left top corner and right bottom is this.getWidth(); this.getHeight()* - check eg. [this explanation](https://docs.oracle.com/javase/tutorial/2d/overview/coordinate.html) - you need to start paint in the left bottom corner and then move to correct position increase "X" as the width of first image ``` @Override public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; /* public abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) */ //start to paint at [0;0] g2d.drawImage(image, 0, 0, this); //start to paint just on the right side of first image (offset equals to width of first picture)- next pixel on the same line, on the bottom of the screen g2d.drawImage(image2,image2.getWidth()+1, 0, this); } ``` I didn't had a chance to test it, but it should be like this. Important things are * you need to have proper dimensions for fitting both images * screen coordinates starts in the left top corner of the screens [0;0]
54,403,437
I want to script with python using Notepad ++ but it works strangely, actually it does not work, so I have pycharm an everything is going well but in notepad ++ when I save file with .py and click run it does not work is there a step by step instruction to follow? I have same problem with sublime text editor so I am lucky with just Pycharm all of the others has confused me please help me.
2019/01/28
[ "https://Stackoverflow.com/questions/54403437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10979398/" ]
The logic of the math was incorrect. See the `getPreferredSize()` method for the correct way to calculate the required width, and the changes to the `paintComponent(Graphics)` method to place them side-by-side. An alternative (not examined in this answer) is to put each image into a `JLabel`, then add the labels to a panel with an appropriate layout. This is the effect of the changes: [![enter image description here](https://i.stack.imgur.com/zAzk5.jpg)](https://i.stack.imgur.com/zAzk5.jpg) ``` import java.awt.*; import java.awt.image.BufferedImage; import javax.swing.*; import java.net.*; import javax.imageio.ImageIO; public class ObrazPanel extends JPanel { private BufferedImage image; private BufferedImage image2; public ObrazPanel() throws MalformedURLException { super(); URL imageFile = new URL("https://i.stack.imgur.com/7bI1Y.jpg"); URL imageFile2 = new URL("https://i.stack.imgur.com/aH5zB.jpg"); try { image = ImageIO.read(imageFile); image2 = ImageIO.read(imageFile2); } catch (Exception e) { System.err.println("Blad odczytu obrazka"); e.printStackTrace(); } } @Override public Dimension getPreferredSize() { int w = image.getWidth() + image2.getWidth(); int h1 = image.getHeight(); int h2 = image2.getHeight(); int h = h1>h2 ? h1 : h2; return new Dimension(w,h); } @Override public void paintComponent(Graphics g) { // always best to start with this.. super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.drawImage(image, 0, 0, this); g2d.drawImage(image2, image.getWidth(), 0, this); } public static void main(String[] args) { Runnable r = new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception useDefault) { } ObrazPanel o; try { o = new ObrazPanel(); JFrame f = new JFrame(o.getClass().getSimpleName()); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setLocationByPlatform(true); f.setContentPane(o); f.pack(); f.setMinimumSize(f.getSize()); f.setVisible(true); } catch (MalformedURLException ex) { ex.printStackTrace(); } } }; SwingUtilities.invokeLater(r); } } ```
I would join the images whenever something changes and draw them to another buffered image. Then I can just redraw the combined image whenever the panel needs to be redrawn. [![Application](https://i.stack.imgur.com/d8QSk.png)](https://i.stack.imgur.com/d8QSk.png) ``` import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; public class SideBySideImagePanel extends JPanel { private static final long serialVersionUID = 5868633578732134172L; private BufferedImage left; private BufferedImage right; private BufferedImage join; public SideBySideImagePanel() { ClassLoader loader = this.getClass().getClassLoader(); BufferedImage left = null, right = null; try { left = ImageIO.read(loader.getResourceAsStream("resources/Android.png")); right = ImageIO.read(loader.getResourceAsStream("resources/Java.png")); } catch (IOException e) { e.printStackTrace(); } this.setLeft(left); this.setRight(right); } public BufferedImage getLeft() { return left; } public void setLeft(BufferedImage left) { this.left = left; } public BufferedImage getRight() { return right; } public void setRight(BufferedImage right) { this.right = right; } @Override public void invalidate() { super.invalidate(); join = combineImages(left, right); setPreferredSize(new Dimension(join.getWidth(), join.getHeight())); } @Override public void paintComponent(Graphics g) { g.drawImage(join, 0, 0, null); } private BufferedImage combineImages(BufferedImage left, BufferedImage right) { int width = left.getWidth() + right.getWidth(); int height = Math.max(left.getHeight(), right.getHeight()); BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics g = combined.getGraphics(); g.drawImage(left, 0, 0, null); g.drawImage(right, left.getWidth(), 0, null); return combined; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame("Image Joiner"); SideBySideImagePanel panel = new SideBySideImagePanel(); frame.getContentPane().add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.pack(); frame.setVisible(true); } }); } } ```
44,857,219
When I use the command "pip install pyperclip" it gives me this error ``` creating /Library/Python/2.7/site-packages/pyperclip error: could not create '/Library/Python/2.7/site-packages/pyperclip': Permission denied ---------------------------------------- Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/ts/tdt25dd52pg6ymt1tc1djd540000gn/T/pip-build-QWGKB1/pyperclip/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/ts/tdt25dd52pg6ymt1tc1djd540000gn/T/pip-sfvxg3-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/ts/tdt25dd52pg6ymt1tc1djd540000gn/T/pip-build-QWGKB1/pyperclip/ ``` Why is it that I do not have permission.
2017/07/01
[ "https://Stackoverflow.com/questions/44857219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4081977/" ]
When ever you get error `Permission denied` its because you are trying to access the root using normal commands. So trying running the command as root to get rid of `Permissin denied` error. Run `sudo command` i.e `sudo pip install pyperclip`
Try it with > > sudo pip install pyperclip > > > Now if it throws some access deny error, try this: > > sudo pip -H install pyperclip > > >
44,857,219
When I use the command "pip install pyperclip" it gives me this error ``` creating /Library/Python/2.7/site-packages/pyperclip error: could not create '/Library/Python/2.7/site-packages/pyperclip': Permission denied ---------------------------------------- Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/ts/tdt25dd52pg6ymt1tc1djd540000gn/T/pip-build-QWGKB1/pyperclip/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/ts/tdt25dd52pg6ymt1tc1djd540000gn/T/pip-sfvxg3-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/ts/tdt25dd52pg6ymt1tc1djd540000gn/T/pip-build-QWGKB1/pyperclip/ ``` Why is it that I do not have permission.
2017/07/01
[ "https://Stackoverflow.com/questions/44857219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4081977/" ]
When ever you get error `Permission denied` its because you are trying to access the root using normal commands. So trying running the command as root to get rid of `Permissin denied` error. Run `sudo command` i.e `sudo pip install pyperclip`
//These below three commands worked for MacBook Pro to install Pip & Pyperclip 1./Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9 -m pip install --upgrade pip 2./Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/scripts 3.sudo pip3 install pyperclip output: Downloading pip-21.2.4-py3-none-any.whl (1.6 MB) |████████████████████████████████| 1.6 MB 3.7 MB/s Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 21.2.3 Uninstalling pip-21.2.3: Successfully uninstalled pip-21.2.3 Successfully installed pip-21.2.4 Collecting pyperclip Downloading pyperclip-1.8.2.tar.gz (20 kB) Using legacy 'setup.py install' for pyperclip, since package 'wheel' is not installed. Installing collected packages: pyperclip Running setup.py install for pyperclip ... done Successfully installed pyperclip-1.8.2
44,857,219
When I use the command "pip install pyperclip" it gives me this error ``` creating /Library/Python/2.7/site-packages/pyperclip error: could not create '/Library/Python/2.7/site-packages/pyperclip': Permission denied ---------------------------------------- Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/ts/tdt25dd52pg6ymt1tc1djd540000gn/T/pip-build-QWGKB1/pyperclip/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/ts/tdt25dd52pg6ymt1tc1djd540000gn/T/pip-sfvxg3-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/ts/tdt25dd52pg6ymt1tc1djd540000gn/T/pip-build-QWGKB1/pyperclip/ ``` Why is it that I do not have permission.
2017/07/01
[ "https://Stackoverflow.com/questions/44857219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4081977/" ]
Try it with > > sudo pip install pyperclip > > > Now if it throws some access deny error, try this: > > sudo pip -H install pyperclip > > >
//These below three commands worked for MacBook Pro to install Pip & Pyperclip 1./Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9 -m pip install --upgrade pip 2./Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/scripts 3.sudo pip3 install pyperclip output: Downloading pip-21.2.4-py3-none-any.whl (1.6 MB) |████████████████████████████████| 1.6 MB 3.7 MB/s Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 21.2.3 Uninstalling pip-21.2.3: Successfully uninstalled pip-21.2.3 Successfully installed pip-21.2.4 Collecting pyperclip Downloading pyperclip-1.8.2.tar.gz (20 kB) Using legacy 'setup.py install' for pyperclip, since package 'wheel' is not installed. Installing collected packages: pyperclip Running setup.py install for pyperclip ... done Successfully installed pyperclip-1.8.2
7,238,401
I've found similar but not identical questions [742371](https://stackoverflow.com/questions/742371/python-strange-behavior-in-for-loop-or-lists) and [4081217](https://stackoverflow.com/questions/4081217/how-to-modify-list-entries-during-for-loop) with great answers, but haven't come to a solution to my problem. I'm trying to process items in a list in place while it's being looped over, and re-loop over what's remaining in the list if it has not met a conditional. The conditional will eventually be met as True for all items in the list, but not necessarily on a "known" iteration. It reminds me of building a tree to some degree, as certain items in the list must be processed before others, but the others may be looped over beforehand. My first instinct is to create a recursive function and edit a slice copy of the list. However I'm having little luck ~ I won't initially know how many passes it will take, but it can never be more passes than elements in the list... just by the nature of at least one element will always meet the conditional as True Ideally ... the result would be something like the following ``` # initial list myList = ['it1', 'test', 'blah', 10] newList = [] # first pass newList = ['test'] # 2nd pass newList = ['test', 'blah', 10] # 3rd pass newList = ['test', 'blah', 10, 'it1'] ```
2011/08/30
[ "https://Stackoverflow.com/questions/7238401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/563343/" ]
How about something like this (just made up a silly condition so I could test it): ``` import random myList = ['it1', 'test', 'blah', 10] newList = [] def someCondition(var): return random.randrange(0,2) == 0 def test(): while len(myList) > 0: pos = 0 while pos < len(myList): if someCondition(myList[pos]): # with someCondition being a function here newList.append(myList.pop(pos)) else: pos += 1 if __name__ == '__main__': test() print(myList) print(newList) ``` [Result:] ``` [] ['it1', 10, 'blah', 'test'] ```
A brute force approach would be to create a temporary list of booleans the same size as your original list initialized to `False` everywhere. In each pass, whenever the item at index `i` of the original list meets the condition, update the value in the temporary array at index `i` with False. In each subsequent pass, look only at the values where the corresponding index is `False`. Stop when all values have become `True`. Grr, come to think of it, keep a `set` of indexes that have met the condition. Yes, sets are better than arrays of booleans.
7,238,401
I've found similar but not identical questions [742371](https://stackoverflow.com/questions/742371/python-strange-behavior-in-for-loop-or-lists) and [4081217](https://stackoverflow.com/questions/4081217/how-to-modify-list-entries-during-for-loop) with great answers, but haven't come to a solution to my problem. I'm trying to process items in a list in place while it's being looped over, and re-loop over what's remaining in the list if it has not met a conditional. The conditional will eventually be met as True for all items in the list, but not necessarily on a "known" iteration. It reminds me of building a tree to some degree, as certain items in the list must be processed before others, but the others may be looped over beforehand. My first instinct is to create a recursive function and edit a slice copy of the list. However I'm having little luck ~ I won't initially know how many passes it will take, but it can never be more passes than elements in the list... just by the nature of at least one element will always meet the conditional as True Ideally ... the result would be something like the following ``` # initial list myList = ['it1', 'test', 'blah', 10] newList = [] # first pass newList = ['test'] # 2nd pass newList = ['test', 'blah', 10] # 3rd pass newList = ['test', 'blah', 10, 'it1'] ```
2011/08/30
[ "https://Stackoverflow.com/questions/7238401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/563343/" ]
``` current = ['it1', 'test', 'blah', 10] results = [] while current: remaining = [] for item in current: (results if meets_conditional(item) else remaining).append(item) current = remaining ```
A brute force approach would be to create a temporary list of booleans the same size as your original list initialized to `False` everywhere. In each pass, whenever the item at index `i` of the original list meets the condition, update the value in the temporary array at index `i` with False. In each subsequent pass, look only at the values where the corresponding index is `False`. Stop when all values have become `True`. Grr, come to think of it, keep a `set` of indexes that have met the condition. Yes, sets are better than arrays of booleans.
7,238,401
I've found similar but not identical questions [742371](https://stackoverflow.com/questions/742371/python-strange-behavior-in-for-loop-or-lists) and [4081217](https://stackoverflow.com/questions/4081217/how-to-modify-list-entries-during-for-loop) with great answers, but haven't come to a solution to my problem. I'm trying to process items in a list in place while it's being looped over, and re-loop over what's remaining in the list if it has not met a conditional. The conditional will eventually be met as True for all items in the list, but not necessarily on a "known" iteration. It reminds me of building a tree to some degree, as certain items in the list must be processed before others, but the others may be looped over beforehand. My first instinct is to create a recursive function and edit a slice copy of the list. However I'm having little luck ~ I won't initially know how many passes it will take, but it can never be more passes than elements in the list... just by the nature of at least one element will always meet the conditional as True Ideally ... the result would be something like the following ``` # initial list myList = ['it1', 'test', 'blah', 10] newList = [] # first pass newList = ['test'] # 2nd pass newList = ['test', 'blah', 10] # 3rd pass newList = ['test', 'blah', 10, 'it1'] ```
2011/08/30
[ "https://Stackoverflow.com/questions/7238401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/563343/" ]
``` current = ['it1', 'test', 'blah', 10] results = [] while current: remaining = [] for item in current: (results if meets_conditional(item) else remaining).append(item) current = remaining ```
How about something like this (just made up a silly condition so I could test it): ``` import random myList = ['it1', 'test', 'blah', 10] newList = [] def someCondition(var): return random.randrange(0,2) == 0 def test(): while len(myList) > 0: pos = 0 while pos < len(myList): if someCondition(myList[pos]): # with someCondition being a function here newList.append(myList.pop(pos)) else: pos += 1 if __name__ == '__main__': test() print(myList) print(newList) ``` [Result:] ``` [] ['it1', 10, 'blah', 'test'] ```
65,063,178
I am trying to create a hangman game using python in VScode. I imported pygame and now it won't let me do pygame.init(). I looked at other posts here and I tried it but I'm not sure why it is not working. Other posts said to go to setting.json and add ``` { "python.linting.pylintArgs": [ "--extension-pkg-whitelist=lxml" // The extension is "lxml" not "1xml" ] } {"python.linting.pylintArgs": [ "--unsafe-load-any-extension=y" ] } ``` [enter image description here](https://i.stack.imgur.com/RAvTN.png) [enter image description here](https://i.stack.imgur.com/Jc8Ps.png)
2020/11/29
[ "https://Stackoverflow.com/questions/65063178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14730665/" ]
1. If you want to turn off Pylint notifications via settings, please use the following format: > > > ``` > "python.linting.pylintArgs": > [ > "--extension-pkg-whitelist=lxml", // The extension is "lxml" not "1xml" > "--unsafe-load-any-extension=y" > ], > > ``` > > [![enter image description here](https://i.stack.imgur.com/fBLXp.png)](https://i.stack.imgur.com/fBLXp.png) In addition, using this method will turn off all Pylint information. 2.It is recommended that you use the following settings to turn off "[no-member](https://github.com/janjur/readable-pylint-messages/blob/master/README.md#e1101---s-r-has-no-r-members)" notifications after the code can be executed: > > > ``` > "python.linting.pylintArgs": [ > "--disable=E1101" > ], > > ``` > > [![enter image description here](https://i.stack.imgur.com/KPbY4.png)](https://i.stack.imgur.com/KPbY4.png)
Vscode has launched new python language server `pylance` install it from extensions. After that change you language server to pylance. You will get amazing features like autoimport, auto completion, linter, debugger, etc. Also check in which environment you have installed pygame. Switch the python interpreter using ctrl+shift+p.
66,321,777
I have a Flask server that will fetch keys from Redis. How would I maintain a list of already deleted keys? Every time I delete a key, it needs to be added to this list within Redis. Every time I try to check for a key in the cache, if it cannot be found I want to check if it is already deleted. This would allow me to distinguish in my API between requests for unknown keys and requests for deleted keys. I am using the standard redis python library.
2021/02/22
[ "https://Stackoverflow.com/questions/66321777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127251/" ]
I think you should separate the name and the number into different attributes: ``` name | number | id ``` and the SQL query should be something like this: ``` select ... group by name, number; ``` depending on what you want to do. Is something like this?
The grouping SQL statement will be ``` select id, name from commande_ligne group by name order by name ``` The outcome should show product 78 id 5 6 11 Product 12 Id 14 15 That's the result that you will get
66,321,777
I have a Flask server that will fetch keys from Redis. How would I maintain a list of already deleted keys? Every time I delete a key, it needs to be added to this list within Redis. Every time I try to check for a key in the cache, if it cannot be found I want to check if it is already deleted. This would allow me to distinguish in my API between requests for unknown keys and requests for deleted keys. I am using the standard redis python library.
2021/02/22
[ "https://Stackoverflow.com/questions/66321777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127251/" ]
If you want all the values of `id` among the duplicates, you can do it this way: ``` select name, GROUP_CONCAT(id) from commande_ligne group by name having count(name) > 1; ``` Read more about the [GROUP\_CONCAT() function](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat).
I think you should separate the name and the number into different attributes: ``` name | number | id ``` and the SQL query should be something like this: ``` select ... group by name, number; ``` depending on what you want to do. Is something like this?
66,321,777
I have a Flask server that will fetch keys from Redis. How would I maintain a list of already deleted keys? Every time I delete a key, it needs to be added to this list within Redis. Every time I try to check for a key in the cache, if it cannot be found I want to check if it is already deleted. This would allow me to distinguish in my API between requests for unknown keys and requests for deleted keys. I am using the standard redis python library.
2021/02/22
[ "https://Stackoverflow.com/questions/66321777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127251/" ]
With the data sample provided with name as Product 78 with an Id, the result you looking for cannot be achieved because under the Unique ID there is always one Product 78 with a unique ID, so that cannot be grouped by IDs, however, you can group by Name for the different ID for grouped records by name for Product 78 it will show the Ids 5,6,11 that's when grouped by Field Name
The grouping SQL statement will be ``` select id, name from commande_ligne group by name order by name ``` The outcome should show product 78 id 5 6 11 Product 12 Id 14 15 That's the result that you will get
66,321,777
I have a Flask server that will fetch keys from Redis. How would I maintain a list of already deleted keys? Every time I delete a key, it needs to be added to this list within Redis. Every time I try to check for a key in the cache, if it cannot be found I want to check if it is already deleted. This would allow me to distinguish in my API between requests for unknown keys and requests for deleted keys. I am using the standard redis python library.
2021/02/22
[ "https://Stackoverflow.com/questions/66321777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127251/" ]
If you want all the values of `id` among the duplicates, you can do it this way: ``` select name, GROUP_CONCAT(id) from commande_ligne group by name having count(name) > 1; ``` Read more about the [GROUP\_CONCAT() function](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat).
With the data sample provided with name as Product 78 with an Id, the result you looking for cannot be achieved because under the Unique ID there is always one Product 78 with a unique ID, so that cannot be grouped by IDs, however, you can group by Name for the different ID for grouped records by name for Product 78 it will show the Ids 5,6,11 that's when grouped by Field Name
66,321,777
I have a Flask server that will fetch keys from Redis. How would I maintain a list of already deleted keys? Every time I delete a key, it needs to be added to this list within Redis. Every time I try to check for a key in the cache, if it cannot be found I want to check if it is already deleted. This would allow me to distinguish in my API between requests for unknown keys and requests for deleted keys. I am using the standard redis python library.
2021/02/22
[ "https://Stackoverflow.com/questions/66321777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127251/" ]
If you want all the values of `id` among the duplicates, you can do it this way: ``` select name, GROUP_CONCAT(id) from commande_ligne group by name having count(name) > 1; ``` Read more about the [GROUP\_CONCAT() function](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat).
The grouping SQL statement will be ``` select id, name from commande_ligne group by name order by name ``` The outcome should show product 78 id 5 6 11 Product 12 Id 14 15 That's the result that you will get
67,108,896
I am using python for webscraping (new to this) and am trying to grab the brand name from a website. It is not visible on the website but I have found the element for it: `<span itemprop="Brand" style="display:none;">Revlon</span>` I want to extract the "Revlon" text in the HTML. I am currently using html requests and have tried grabbing the selector (CSS) and text: `brandname = r.html.find('body > div:nth-child(96) > span:nth-child(2)', first=True).text.strip()` but this returns `None` and an error. I am not sure how to extract this specifically. Any help would be appreciated.
2021/04/15
[ "https://Stackoverflow.com/questions/67108896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11472545/" ]
Here is a working solution with Selenium: ``` from seleniumwire import webdriver from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) website = 'https://www.boots.com/revlon-colorstay-makeup-for-normal-dry-skin-10212694' driver.get(website) brand_name = driver.find_element_by_xpath('//*[@id="estore_product_title"]/h1') print('brand name: '+brand_name.text.split(' ')[0]) ``` **You can also use beautifulsoup for that:** ``` from bs4 import BeautifulSoup import requests urlpage = 'https://www.boots.com/revlon-colorstay-makeup-for-normal-dry-skin-10212694' # query the website and return the html to the variable 'page' page = requests.get(urlpage) # parse the html using beautiful soup and store in variable 'soup' soup = BeautifulSoup(page.content, 'html.parser') name = soup.find(id='estore_product_title') print(name.text.split(' ')[0]) ```
try this method .find("span", itemprop="Brand") I think it's work ``` from bs4 import BeautifulSoup import requests urlpage = 'https://www.boots.com/revlon-colorstay-makeup-for-normal-dry-skin-10212694' page = requests.get(urlpage) # parse the html using beautiful soup and store in variable 'soup' soup = BeautifulSoup(page.content, 'html.parser') print(soup.find("span", itemprop="Brand").text) ```
56,613,286
Say that I have a list of strings, such as ``` listStrings = [ 'cat', 'bat', 'hat', 'dad', 'look', 'ball', 'hero', 'up'] ``` Is there a way would return all rows if a particular column contains 3 or more of the strings from the list? For example If the column contained 'My dad is a hero for saving the cat' Then the row would be returned. But if the column only contained 'the cat and bat teamed up to find some food' That row wouldn't be returned. The only way I can think of is to get every combination of 3 from the list of strings, and use AND statements. e.g. 'cat' AND 'bat' AND 'hat'. But this doesn't seem computationally efficient nor pythonic. Is there a more efficient, compact way to do this? Edit Here is a pandas example ``` import pandas as pd listStrings = [ 'cat', 'bat', 'hat', 'dad', 'look', 'ball', 'hero', 'up'] df = pd.DataFrame(['test1', 'test2', 'test3'], ['My dad is a hero for saving the cat', 'the cat and bat teamed up to find some food', 'The dog found a bowl']) df.head() 0 My dad is a hero for saving the cat test1 the cat and bat teamed up to find some food test2 The dog found a bowl test3 ``` So using the `listStrings`, I would like row 1 returned, but not row 2 or row 3.
2019/06/15
[ "https://Stackoverflow.com/questions/56613286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3259896/" ]
You could use something like this: ``` $reviews = Review::orderBy('created_at', 'DESC') ->orWhere('created_at','>=',now()->subDays($request->review == 7 ? 7 : 30) ->where('listing_id', $id) ->where('user_id', Auth::user()->id) ->paginate(6, ['*'], 'review'); ``` but keep in mind you might still get wrong results. You should make sure brackets are added into query in correct place, otherwise you might get other user's results, so it's quite possible in fact you would like to use something like this: ``` $reviews = Review::orderBy('created_at', 'DESC') ->where(function($q) use ($request) { $q->where('listing_id', $id) ->orWhere('created_at','>=',now()->subDays($request->review == 7 ? 7 : 30) }) ->where('user_id', Auth::user()->id) ->paginate(6, ['*'], 'review'); ``` but you haven't explained what exact results you want to get from database so it's just a hint.
You can split Eloquent Builder by cursor. ```php $cursor = Review::orderByDesc('created_at'); if ($request->review == "7") { $cursor->orWhere('created_at','>=', 7)); } $reviews = $cursor->where('listing_id', $id) ->where('user_id', Auth::user()->id) ->paginate(6, ['*'], 'review'); ```
56,613,286
Say that I have a list of strings, such as ``` listStrings = [ 'cat', 'bat', 'hat', 'dad', 'look', 'ball', 'hero', 'up'] ``` Is there a way would return all rows if a particular column contains 3 or more of the strings from the list? For example If the column contained 'My dad is a hero for saving the cat' Then the row would be returned. But if the column only contained 'the cat and bat teamed up to find some food' That row wouldn't be returned. The only way I can think of is to get every combination of 3 from the list of strings, and use AND statements. e.g. 'cat' AND 'bat' AND 'hat'. But this doesn't seem computationally efficient nor pythonic. Is there a more efficient, compact way to do this? Edit Here is a pandas example ``` import pandas as pd listStrings = [ 'cat', 'bat', 'hat', 'dad', 'look', 'ball', 'hero', 'up'] df = pd.DataFrame(['test1', 'test2', 'test3'], ['My dad is a hero for saving the cat', 'the cat and bat teamed up to find some food', 'The dog found a bowl']) df.head() 0 My dad is a hero for saving the cat test1 the cat and bat teamed up to find some food test2 The dog found a bowl test3 ``` So using the `listStrings`, I would like row 1 returned, but not row 2 or row 3.
2019/06/15
[ "https://Stackoverflow.com/questions/56613286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3259896/" ]
You could use something like this: ``` $reviews = Review::orderBy('created_at', 'DESC') ->orWhere('created_at','>=',now()->subDays($request->review == 7 ? 7 : 30) ->where('listing_id', $id) ->where('user_id', Auth::user()->id) ->paginate(6, ['*'], 'review'); ``` but keep in mind you might still get wrong results. You should make sure brackets are added into query in correct place, otherwise you might get other user's results, so it's quite possible in fact you would like to use something like this: ``` $reviews = Review::orderBy('created_at', 'DESC') ->where(function($q) use ($request) { $q->where('listing_id', $id) ->orWhere('created_at','>=',now()->subDays($request->review == 7 ? 7 : 30) }) ->where('user_id', Auth::user()->id) ->paginate(6, ['*'], 'review'); ``` but you haven't explained what exact results you want to get from database so it's just a hint.
``` $reviews = Review::where('listing_id', $id) ->where('user_id', Auth::user()->id); if($request->review == 7){ $reviews->Where('created_at','>=',now()->subDays($request->review)); } if($request->review != 7){ $reviews->Where('created_at','>=',now()->subDays(30)); } $reviews->orderBy('created_at', 'DESC') ->paginate(6, ['*'], 'review'); ``` After understanding the above, you can go ahead to simplify the above using the ternary operator as you have below. ``` $reviews = Review::where('listing_id', $id) ->where('user_id', Auth::user()->id); ->Where('created_at','>=',now()->subDays(($request->review == 7)? 7 : 30)); ->orderBy('created_at', 'DESC') ->paginate(6, ['*'], 'review'); ```
56,613,286
Say that I have a list of strings, such as ``` listStrings = [ 'cat', 'bat', 'hat', 'dad', 'look', 'ball', 'hero', 'up'] ``` Is there a way would return all rows if a particular column contains 3 or more of the strings from the list? For example If the column contained 'My dad is a hero for saving the cat' Then the row would be returned. But if the column only contained 'the cat and bat teamed up to find some food' That row wouldn't be returned. The only way I can think of is to get every combination of 3 from the list of strings, and use AND statements. e.g. 'cat' AND 'bat' AND 'hat'. But this doesn't seem computationally efficient nor pythonic. Is there a more efficient, compact way to do this? Edit Here is a pandas example ``` import pandas as pd listStrings = [ 'cat', 'bat', 'hat', 'dad', 'look', 'ball', 'hero', 'up'] df = pd.DataFrame(['test1', 'test2', 'test3'], ['My dad is a hero for saving the cat', 'the cat and bat teamed up to find some food', 'The dog found a bowl']) df.head() 0 My dad is a hero for saving the cat test1 the cat and bat teamed up to find some food test2 The dog found a bowl test3 ``` So using the `listStrings`, I would like row 1 returned, but not row 2 or row 3.
2019/06/15
[ "https://Stackoverflow.com/questions/56613286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3259896/" ]
You could use something like this: ``` $reviews = Review::orderBy('created_at', 'DESC') ->orWhere('created_at','>=',now()->subDays($request->review == 7 ? 7 : 30) ->where('listing_id', $id) ->where('user_id', Auth::user()->id) ->paginate(6, ['*'], 'review'); ``` but keep in mind you might still get wrong results. You should make sure brackets are added into query in correct place, otherwise you might get other user's results, so it's quite possible in fact you would like to use something like this: ``` $reviews = Review::orderBy('created_at', 'DESC') ->where(function($q) use ($request) { $q->where('listing_id', $id) ->orWhere('created_at','>=',now()->subDays($request->review == 7 ? 7 : 30) }) ->where('user_id', Auth::user()->id) ->paginate(6, ['*'], 'review'); ``` but you haven't explained what exact results you want to get from database so it's just a hint.
$reviews = Review::orderBy('created\_at', 'DESC'); if ($request->review == "7") { ``` $reviews->orWhere('created_at','>=', 7)); ``` } $reviews = $reviews->where('listing\_id', $id) ``` ->where('user_id', Auth::User()->id) ->paginate(6, ['*'], 'review'); ```
21,449,085
I may get slammed because this question is too broad, but anyway I going to ask cause what else do I do? Digging through the Python source code should surely give me enough "good effort" points to warrant helping me? I am trying to use Python 3.4's new email content manager <http://docs.python.org/dev/library/email.contentmanager.html#content-manager-instances> It is my understanding that this should allow me to read an email message, then be able to access all the email header fields and body as UTF-8, without going through the painful process of decoding from whatever weird encoding back into clean UTF-8. I understand is also handles parsing of date headers and email address headers. Generally making life easier for reading emails in Python. Great stuff, very interesting. However I am a beginner programmer - there are no examples in the current documentation of how to start from the start. I need a simple example showing how to read an email file and using the new email content manager, read back the header fields, address fields and body/ I have dug into the python 3.4 source code and looked at the tests for the email content manager. I will admit to being sufficiently amatuerish that I was too confused to be able to glean enough from the tests to start writing my own simple example. So, is anyone willing to help with a simple example of how to use the Python 3.4 email content manager to read the header fields and body and address fields of an email? thanks
2014/01/30
[ "https://Stackoverflow.com/questions/21449085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/627492/" ]
First: the “address fields” in an email are in fact simply headers whose names have been agreed upon in standards, like `To` and `From`. So all you need are the email headers and body and you are done. Given a modern `contentmanager`-powered `EmailMessage` instance such as Python 3.4 returns if you specify a policy (like `default`) when reading in an email message, you can access its auto-decoded headers by treating it like a Python dictionary, and its body with the `get_body()` call. Here is an example script I wrote that does both maneuvers in a safe and standard way: <https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter12/display_email.py> Behind the scenes, the policy is what is really in charge of what happens to both headers and content — with the `default` policy automatically subjecting headers to the encoding and decoding functions in `email.utils`, and content to the logic you asked about that is inside of `contentmanager`. But as the caller you usually will not need to know the behind-the-scenes magic, because headers will “just work” and content can be easily accessed through the methods illustrated in the above script.
If you have an email in a file and want to read it into Python, it's the [`email.Parser` you should probably look at](http://docs.python.org/dev/library/email.parser.html#parser-class-api) first. [Like Brandon](https://stackoverflow.com/a/22697432/923794), I don't quite see the need for using the `contentmanager`, but maybe your question *is* too broad and you need to help me understand it better. Code could look like: ``` filename = 'your_file_here.email.txt' import email.parser with open(filename, 'r') as fh: message = email.parser.Parser().parse(fh) ``` There are even convenience functions, and the one for your case would be: ``` import email message = email.message_from_file('your_file_here.email.txt') ``` Then check the [docs on email.message](http://docs.python.org/dev/library/email.message.html) to see how to access the message's content. You can check with `is_multipart()` if it's a single monolithic block of text, or a MIME message consisting of multiple parts. In the latter case, there's `walk()` to iterate over each part.
48,065,360
I want to use python interpolate polynomial on points from a finite-field and get a polynomial with coefficients in that field. Currently I'm trying to use SymPy and specifically interpolate (from `sympy.polys.polyfuncs`), but I don't know how to force the interpolation to happen in a specific gf. If not, can this be done with another module? Edit: I'm interested in a Python implementation/library.
2018/01/02
[ "https://Stackoverflow.com/questions/48065360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5603149/" ]
SymPy's [interpolating\_poly](http://docs.sympy.org/latest/modules/polys/reference.html#sympy.polys.specialpolys.interpolating_poly) does not support polynomials over finite fields. But there are enough details under the hood of SymPy to put together a class for finite fields, and find the coefficients of [Lagrange polynomial](https://en.wikipedia.org/wiki/Lagrange_polynomial) in a brutally direct fashion. As usual, the elements of finite field GF(pn) are [represented by polynomials](https://en.wikipedia.org/wiki/Finite_field#Explicit_construction_of_finite_fields) of degree less than n, with coefficients in GF(p). Multiplication is done modulo a reducing polynomial of degree n, which is selected at the time of field construction. Inversion is done with extended Euclidean algorithm. The polynomials are represented by lists of coefficients, highest degrees first. For example, the elements of GF(32) are: ``` [], [1], [2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2] ``` The empty list represents 0. ### Class GF, finite fields Implements arithmetics as methods `add`, `sub`, `mul`, `inv` (multiplicative inverse). For convenience of testing interpolation includes `eval_poly` which evaluates a given polynomial with coefficients in GF(pn) at a point of GF(pn). Note that the constructor is used as G(3, 2), not as G(9), - the prime and its power are supplied separately. ``` import itertools from functools import reduce from sympy import symbols, Dummy from sympy.polys.domains import ZZ from sympy.polys.galoistools import (gf_irreducible_p, gf_add, \ gf_sub, gf_mul, gf_rem, gf_gcdex) from sympy.ntheory.primetest import isprime class GF(): def __init__(self, p, n=1): p, n = int(p), int(n) if not isprime(p): raise ValueError("p must be a prime number, not %s" % p) if n <= 0: raise ValueError("n must be a positive integer, not %s" % n) self.p = p self.n = n if n == 1: self.reducing = [1, 0] else: for c in itertools.product(range(p), repeat=n): poly = (1, *c) if gf_irreducible_p(poly, p, ZZ): self.reducing = poly break def add(self, x, y): return gf_add(x, y, self.p, ZZ) def sub(self, x, y): return gf_sub(x, y, self.p, ZZ) def mul(self, x, y): return gf_rem(gf_mul(x, y, self.p, ZZ), self.reducing, self.p, ZZ) def inv(self, x): s, t, h = gf_gcdex(x, self.reducing, self.p, ZZ) return s def eval_poly(self, poly, point): val = [] for c in poly: val = self.mul(val, point) val = self.add(val, c) return val ``` ### Class PolyRing, polynomials over a field This one is simpler: it implements addition, subtraction, and multiplication of polynomials, referring to the ground field for operations on coefficients. There is a lot of list reversals `[::-1]` because of SymPy's convention to list monomials starting with highest powers. ``` class PolyRing(): def __init__(self, field): self.K = field def add(self, p, q): s = [self.K.add(x, y) for x, y in \ itertools.zip_longest(p[::-1], q[::-1], fillvalue=[])] return s[::-1] def sub(self, p, q): s = [self.K.sub(x, y) for x, y in \ itertools.zip_longest(p[::-1], q[::-1], fillvalue=[])] return s[::-1] def mul(self, p, q): if len(p) < len(q): p, q = q, p s = [[]] for j, c in enumerate(q): s = self.add(s, [self.K.mul(b, c) for b in p] + \ [[]] * (len(q) - j - 1)) return s ``` ### Construction of interpolating polynomial. The [Lagrange polynomial](https://en.wikipedia.org/wiki/Lagrange_polynomial) is constructed for given x-values in list X and corresponding y-values in array Y. It is a linear combination of basis polynomials, one for each element of X. Each basis polynomial is obtained by multiplying `(x-x_k)` polynomials, represented as `[[1], K.sub([], x_k)]`. The denominator is a scalar, so it's even easier to compute. ``` def interp_poly(X, Y, K): R = PolyRing(K) poly = [[]] for j, y in enumerate(Y): Xe = X[:j] + X[j+1:] numer = reduce(lambda p, q: R.mul(p, q), ([[1], K.sub([], x)] for x in Xe)) denom = reduce(lambda x, y: K.mul(x, y), (K.sub(X[j], x) for x in Xe)) poly = R.add(poly, R.mul(numer, [K.mul(y, K.inv(denom))])) return poly ``` ### Example of usage: ``` K = GF(2, 4) X = [[], [1], [1, 0, 1]] # 0, 1, a^2 + 1 Y = [[1, 0], [1, 0, 0], [1, 0, 0, 0]] # a, a^2, a^3 intpoly = interp_poly(X, Y, K) pprint(intpoly) pprint([K.eval_poly(intpoly, x) for x in X]) # same as Y ``` The pretty print is just to avoid some type-related decorations on the output. The polynomial is shown as `[[1], [1, 1, 1], [1, 0]]`. To help readability, I added a function to turn this in a more familiar form, with a symbol `a` being a generator of finite field, and `x` being the variable in the polynomial. ``` def readable(poly, a, x): return Poly(sum((sum((c*a**j for j, c in enumerate(coef[::-1])), S.Zero) * x**k \ for k, coef in enumerate(poly[::-1])), S.Zero), x) ``` So we can do ``` a, x = symbols('a x') print(readable(intpoly, a, x)) ``` and get ``` Poly(x**2 + (a**2 + a + 1)*x + a, x, domain='ZZ[a]') ``` This algebraic object is not a polynomial over our field, this is just for the sake of readable output. ### Sage As an alternative, or just another safety check, one can use the [`lagrange_polynomial`](http://doc.sagemath.org/html/en/reference/polynomial_rings/sage/rings/polynomial/polynomial_ring.html#sage.rings.polynomial.polynomial_ring.PolynomialRing_field.lagrange_polynomial) from Sage for the same data. ``` field = GF(16, 'a') a = field.gen() R = PolynomialRing(field, "x") points = [(0, a), (1, a^2), (a^2+1, a^3)] R.lagrange_polynomial(points) ``` Output: `x^2 + (a^2 + a + 1)*x + a`
I'm the author of the [`galois`](https://github.com/mhostetter/galois) Python library. Polynomial interpolation can be performed with the `lagrange_poly()` function. Here's a simple example. ```py In [1]: import galois In [2]: galois.__version__ Out[2]: '0.0.32' In [3]: GF = galois.GF(3**5) In [4]: x = GF.Random(10); x Out[4]: GF([ 33, 58, 59, 21, 141, 133, 207, 182, 125, 162], order=3^5) In [5]: y = GF.Random(10); y Out[5]: GF([ 34, 239, 120, 170, 31, 165, 180, 79, 215, 215], order=3^5) In [6]: f = galois.lagrange_poly(x, y); f Out[6]: Poly(165x^9 + 96x^8 + 9x^7 + 111x^6 + 40x^5 + 208x^4 + 55x^3 + 17x^2 + 118x + 203, GF(3^5)) In [7]: f(x) Out[7]: GF([ 34, 239, 120, 170, 31, 165, 180, 79, 215, 215], order=3^5) ``` The finite field element display may be changed to either the polynomial or power representation. ```py In [8]: GF.display("poly"); f(x) Out[8]: GF([ α^3 + 2α + 1, 2α^4 + 2α^3 + 2α^2 + α + 2, α^4 + α^3 + α^2 + α, 2α^4 + 2α + 2, α^3 + α + 1, 2α^4 + α, 2α^4 + 2α^2, 2α^3 + 2α^2 + 2α + 1, 2α^4 + α^3 + 2α^2 + 2α + 2, 2α^4 + α^3 + 2α^2 + 2α + 2], order=3^5) In [9]: GF.display("power"); f(x) Out[9]: GF([α^198, α^162, α^116, α^100, α^214, α^137, α^169, α^95, α^175, α^175], order=3^5) ```
16,809,248
My works relates to instrumentation of code fragments in python code. So in my work i would be writing a script in python such that I take another python file as input and insert any necessary code in the required place with my script. The following code is a sample code of a file which i would be instrumenting: ``` A.py #normal un-instrumented code statements .... .... def move(self,a): statements ...... print "My function is defined" ...... statements ...... ``` My script what actually does is to check each lines in the A.py and if there is a "def" then a code fragment is instrumented on top of the code the def function The following example is how the final out put should be: ``` A.py #instrumented code statements .... .... @decorator #<------ inserted code def move(self,a): statements ...... print "My function is defined" ...... statements ...... ``` But I have been resulted with different output. The following code is the final output which i am getting: A.py #instrumented code ``` statements .... .... @decorator #<------ inserted code def move(self,a): statements ...... @decorator #<------ inserted code [this should not occur] print "My function is defined" ...... statements ...... ``` I can understand that in the instrumented code it recognizes "def" in the word "defined" and so it instruments the a code above it. In realty the instrumented code has lots of these problems I was not able to properly instrument the given python file. Is there any other way to differentiate the actual "def" from string? Thank you
2013/05/29
[ "https://Stackoverflow.com/questions/16809248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2135762/" ]
Use the [`ast` module](http://docs.python.org/2/library/ast.html) to parse the file properly. This code prints the line number and column offset of each `def` statement: ``` import ast with open('mymodule.py') as f: tree = ast.parse(f.read()) for node in ast.walk(tree): if isinstance(node, ast.FunctionDef): print node.lineno, node.col_offset ```
You could use a Regular Expression. To avoid `def` inside quotes then you can use negative look-arounds: ``` import re for line in open('A.py'): m = re.search(r"(?!<[\"'])\bdef\b(?![\"'])", line) if m: print r'@decorator #<------ inserted code' print line ``` However, there might be other occurances of `def` that you or I can't think of, and if we are not careful we end-up writing the Python parser all over again. @Janne Karila's suggestion of using `ast.parse` is probably safer in the long term.
26,027,271
I have a dictionary of configs (defined by the user as settings for a Django app). And I need to check the config to make sure it fits the rules. The rule is very simple. The 'range' within each option must be unique. sample settings =============== ``` breakpoints = { 'small': { 'verbose_name': _('Small screens'), 'min_width': None, 'max_width': 640, }, 'medium': { 'verbose_name': _('Medium screens'), 'min_width': 641, 'max_width': 1024, }, 'large': { 'verbose_name': _('Large screens'), 'min_width': 1025, 'max_width': 1440, }, 'xlarge': { 'verbose_name': _('XLarge screens'), 'min_width': 1441, 'max_width': 1920, }, 'xxlarge': { 'verbose_name': _('XXLarge screens'), 'min_width': 1921, 'max_width': None, } } ``` Here's what Ive come with so far. It works but don't seem very pythonic. ``` for alias, config in breakpoints.items(): for alias2, config2 in breakpoints.items(): if not alias2 is alias: msg = error_msg % (alias, 'breakpoint clashes with %s breakpoint' % alias2) for attr in ('min_width', 'max_width', ): if config[attr] is not None: if (config2['min_width'] and config2['max_width']) and \ (config2['min_width'] <= config[attr] <= config2['max_width']): raise ImproperlyConfigured(msg) elif (config2['min_width'] and not config2['max_width']) and \ (config2['min_width'] < config[attr]): raise ImproperlyConfigured(msg) elif (config2['max_width'] and not config2['min_width']) and \ (config2['max_width'] > config[attr]): raise ImproperlyConfigured(msg) ``` Is there a better way I can solve this?
2014/09/24
[ "https://Stackoverflow.com/questions/26027271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1682844/" ]
Its easy to scan for overlapping ranges if you sort the dataset first. 'None' appears to be used for different things in different places (as min its zero) as max its "greater than anything" - but that's harder to compare. If you have a real maximum, it makes the sorting a bit easier. (edit: scan for max because there is no known maximum) ``` MAX = max(val.get('max_width', 0) for val in breakpoints.itervalues()) + 1 # sort by min/max items = sorted( (data['min_width'] or 0, data['max_width'] or MAX, name) for name, data in breakpoints.iteritems()) # check if any range overlaps the next higher item for i in range(len(items)-1): if items[i][0] > items[i][1]: print "range is incorrect for", items[i][1] elif items[i][1] >= items[i+1][0]: print items[i+1][2], 'overlaps' ```
You can get from that a dict with the ranges as pairs: ``` ranges = { 'small': (None, 640), 'medium': (641, 1024), ...} ``` and then check, say, that `len(set(ranges.values())) == len(ranges)` EDIT: this works if the requirement is for ranges to be different. See @tdelaney's answer for disjoint ranges.
8,510,972
I have seen a lot of posts on this topic, however I have not found regarding this warning: ``` CMake Warning: Manually-specified variables were not used by the project: BUILD_PYTHON_SUPPORT ``` when I compile with cmake. When building OpenCV with this warning, it turns out that it doesn't include python support (surprise). I use this command to compile the build-files ``` cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_PYTHON_SUPPORT=ON -D BUILD_EXAMPLES=ON .. ``` I have installed python-dev.
2011/12/14
[ "https://Stackoverflow.com/questions/8510972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256664/" ]
It looks like you're using an old install guide. Use `BUILD_NEW_PYTHON_SUPPORT` instead. So, execute CMake like this: ``` cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_NEW_PYTHON_SUPPORT=ON -D BUILD_EXAMPLES=ON .. ``` Also, if you use the CMake GUI, it is easier to see all of the options you can set for OpenCV (there are so many it's quite tedious to type them all on the command-line). To get it for Ubuntu, do this: ``` sudo apt-get install cmake-qt-gui ```
**Simple instructions to install opencv with python bindings in Linux - Ubuntu/Fedora** 1. Install gcc, g++/gcc-c++, cmake (apt-get or yum, in case of yum use gcc-c++). **#apt-get install gcc, g++, cmake** 2. Downlaod latest opencv from openCV's website (<http://opencv.org/downloads.html>). 3. Untar it **#tar - xvf opencv-*\**** 4. Inside the untarred folder make a new folder called "**release**" (or any folder name) and run this command in it #**"cmake -D CMAKE\_BUILD\_TYPE=RELEASE -D CMAKE\_INSTALL\_PREFIX=/usr/local -D BUILD\_NEW\_PYTHON\_SUPPORT=ON -D BUILD\_EXAMPLES=ON .."** the ".." will pull files from the parents folder and will get the system ready for installation on your platform. 5. in the release (#cd release) folder run **#make** 6. After about 2-3 mins of make processing when its finished run **#make install** That's it, now go to python and try ">>> **import cv2**" you should not get any error message. Tested on python 2.7, should be virtually similar to python 3.x.
3,693,891
I'm writing a program that (part of what is does is) executes other programs. I want to to be able to run as many types of programs (written in different languages) as possible using `Process.Start` . So, I'm thinking I should: 1. Open the file 2. Read in the first line 3. Check if it starts with `#!` 4. If so, use what follows the `#!` as the program to execute, and pass in the filename as an argument instead 5. If no `#!` is found, check the file extension against a dictionary of known programs (e.g., `.py -> python`) and execute that program instead 6. Otherwise, just try executing the file and catch any errors But, I'm thinking it might be easier/more efficient to actually check if the file is executable first and if so, jump to 6. Is there a way to do this?
2010/09/12
[ "https://Stackoverflow.com/questions/3693891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
In Windows there is no real notion of "executable", like the specific permission that exists in \*NIX systems. You have two options. The first one, like saurabh had suggested before me, is to rely on the system to associate between the file extension and the command to be performed. This approach (of using Process.Start) has many advantages - it leaves the power of association to the user, as in letting the user pick the correct way to run the various file types. The second option is to mimic the Windows file association process, by having a dictionary from an extension to the command that can run the file, and falling back to checking the first line of the file if needed. This has the advantage of you having the power of setting the associations, but it also requires constant modifications and maintenance on your side, in addition to losing the flexibility on the user side - which may be a good thing or a bad thing.
if you are using .net than Process.Start do lot of things for you. if you pass a exe , it will run the exe. If you pass a word document , it will open the word document and may more
3,693,891
I'm writing a program that (part of what is does is) executes other programs. I want to to be able to run as many types of programs (written in different languages) as possible using `Process.Start` . So, I'm thinking I should: 1. Open the file 2. Read in the first line 3. Check if it starts with `#!` 4. If so, use what follows the `#!` as the program to execute, and pass in the filename as an argument instead 5. If no `#!` is found, check the file extension against a dictionary of known programs (e.g., `.py -> python`) and execute that program instead 6. Otherwise, just try executing the file and catch any errors But, I'm thinking it might be easier/more efficient to actually check if the file is executable first and if so, jump to 6. Is there a way to do this?
2010/09/12
[ "https://Stackoverflow.com/questions/3693891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
The only way to do this is to use P/Invoke calls in to the Win32 API. You need to use the SHGetFileInfo method and then unpack the return value: ``` [Flags] internal enum SHGFI : uint { ADDOVERLAYS = 0x20, ATTR_SPECIFIED = 0x20000, ATTRIBUTES = 0x800, DISPLAYNAME = 0x200, EXETYPE = 0x2000, ICON = 0x100, ICONLOCATION = 0x1000, LARGEICON = 0, LINKOVERLAY = 0x8000, OPENICON = 2, OVERLAYINDEX = 0x40, PIDL = 8, SELECTED = 0x10000, SHELLICONSIZE = 4, SMALLICON = 1, SYSICONINDEX = 0x4000, TYPENAME = 0x400, USEFILEATTRIBUTES = 0x10 } /// <summary> /// This structure contains information about a file object. /// </summary> /// <remarks> /// This structure is used with the SHGetFileInfo function. /// </remarks> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SHFILEINFO { /// <summary> /// Handle to the icon that represents the file. /// </summary> internal IntPtr hIcon; /// <summary> /// Index of the icon image within the system image list. /// </summary> internal int iIcon; /// <summary> /// Specifies the attributes of the file object. /// </summary> internal SFGAO dwAttributes; /// <summary> /// Null-terminated string that contains the name of the file as it /// appears in the Windows shell, or the path and name of the file that /// contains the icon representing the file. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Constants.MAX_PATH)] internal string szDisplayName; /// <summary> /// Null-terminated string that describes the type of file. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] internal string szTypeName; } /// <summary> /// Specifies the executable file type. /// </summary> public enum ExecutableType : int { /// <summary> /// The file executable type is not able to be determined. /// </summary> Unknown = 0, /// <summary> /// The file is an MS-DOS .exe, .com, or .bat file. /// </summary> DOS, /// <summary> /// The file is a Microsoft Win32®-based console application. /// </summary> Win32Console, /// <summary> /// The file is a Windows application. /// </summary> Windows, } // Retrieves information about an object in the file system, // such as a file, a folder, a directory, or a drive root. [DllImport("shell32", EntryPoint = "SHGetFileInfo", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)] internal static extern IntPtr SHGetFileInfo( string pszPath, FileAttributes dwFileAttributes, ref SHFILEINFO sfi, int cbFileInfo, SHGFI uFlags); [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] private ExecutableType IsExecutable(string fileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } ExecutableType executableType = ExecutableType.Unknown; if (File.Exists(fileName) { // Try to fill the same SHFILEINFO struct for the exe type. The returned pointer contains the encoded // executable type data. ptr = IntPtr.Zero; ptr = SHGetFileInfo(fileName, FileAttributes.Normal, ref this.shellFileInfo, Marshal.SizeOf(typeof(SHFILEINFO)), SHGFI.EXETYPE); // We need to split the returned pointer up into the high and low order words. These are important // because they help distinguish some of the types. The possible values are: // // Value Meaning // ---------------------------------------------------------------------------------------------- // 0 Nonexecutable file or an error condition. // LOWORD = NE or PE and HIWORD = Windows version Microsoft Windows application. // LOWORD = MZ and HIWORD = 0 Windows 95, Windows 98: Microsoft MS-DOS .exe, .com, or .bat file // Microsoft Windows NT, Windows 2000, Windows XP: MS-DOS .exe or .com file // LOWORD = PE and HIWORD = 0 Windows 95, Windows 98: Microsoft Win32 console application // Windows NT, Windows 2000, Windows XP: Win32 console application or .bat file // MZ = 0x5A4D - DOS signature. // NE = 0x454E - OS/2 signature. // LE = 0x454C - OS/2 LE or VXD signature. // PE = 0x4550 - Win32/NT signature. int wparam = ptr.ToInt32(); int loWord = wparam & 0xffff; int hiWord = wparam >> 16; if (wparam == 0) { executableType = ExecutableType.Unknown; } else { if (hiWord == 0x0000) { if (loWord == 0x5A4D) { // The file is an MS-DOS .exe, .com, or .bat executableType = ExecutableType.DOS; } else if (loWord == 0x4550) { executableType = ExecutableType.Win32Console; } } else { if (loWord == 0x454E || loWord == 0x4550) { executableType = ExecutableType.Windows; } else if (loWord == 0x454C) { executableType = ExecutableType.Windows; } } } } return executableType; } ``` *(This should work, but was extracted from a larger library so there may be minor issues. It should, however, be complete enough to get you most of the way there.)*
if you are using .net than Process.Start do lot of things for you. if you pass a exe , it will run the exe. If you pass a word document , it will open the word document and may more
3,693,891
I'm writing a program that (part of what is does is) executes other programs. I want to to be able to run as many types of programs (written in different languages) as possible using `Process.Start` . So, I'm thinking I should: 1. Open the file 2. Read in the first line 3. Check if it starts with `#!` 4. If so, use what follows the `#!` as the program to execute, and pass in the filename as an argument instead 5. If no `#!` is found, check the file extension against a dictionary of known programs (e.g., `.py -> python`) and execute that program instead 6. Otherwise, just try executing the file and catch any errors But, I'm thinking it might be easier/more efficient to actually check if the file is executable first and if so, jump to 6. Is there a way to do this?
2010/09/12
[ "https://Stackoverflow.com/questions/3693891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
The only way to do this is to use P/Invoke calls in to the Win32 API. You need to use the SHGetFileInfo method and then unpack the return value: ``` [Flags] internal enum SHGFI : uint { ADDOVERLAYS = 0x20, ATTR_SPECIFIED = 0x20000, ATTRIBUTES = 0x800, DISPLAYNAME = 0x200, EXETYPE = 0x2000, ICON = 0x100, ICONLOCATION = 0x1000, LARGEICON = 0, LINKOVERLAY = 0x8000, OPENICON = 2, OVERLAYINDEX = 0x40, PIDL = 8, SELECTED = 0x10000, SHELLICONSIZE = 4, SMALLICON = 1, SYSICONINDEX = 0x4000, TYPENAME = 0x400, USEFILEATTRIBUTES = 0x10 } /// <summary> /// This structure contains information about a file object. /// </summary> /// <remarks> /// This structure is used with the SHGetFileInfo function. /// </remarks> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SHFILEINFO { /// <summary> /// Handle to the icon that represents the file. /// </summary> internal IntPtr hIcon; /// <summary> /// Index of the icon image within the system image list. /// </summary> internal int iIcon; /// <summary> /// Specifies the attributes of the file object. /// </summary> internal SFGAO dwAttributes; /// <summary> /// Null-terminated string that contains the name of the file as it /// appears in the Windows shell, or the path and name of the file that /// contains the icon representing the file. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Constants.MAX_PATH)] internal string szDisplayName; /// <summary> /// Null-terminated string that describes the type of file. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] internal string szTypeName; } /// <summary> /// Specifies the executable file type. /// </summary> public enum ExecutableType : int { /// <summary> /// The file executable type is not able to be determined. /// </summary> Unknown = 0, /// <summary> /// The file is an MS-DOS .exe, .com, or .bat file. /// </summary> DOS, /// <summary> /// The file is a Microsoft Win32®-based console application. /// </summary> Win32Console, /// <summary> /// The file is a Windows application. /// </summary> Windows, } // Retrieves information about an object in the file system, // such as a file, a folder, a directory, or a drive root. [DllImport("shell32", EntryPoint = "SHGetFileInfo", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)] internal static extern IntPtr SHGetFileInfo( string pszPath, FileAttributes dwFileAttributes, ref SHFILEINFO sfi, int cbFileInfo, SHGFI uFlags); [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] private ExecutableType IsExecutable(string fileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } ExecutableType executableType = ExecutableType.Unknown; if (File.Exists(fileName) { // Try to fill the same SHFILEINFO struct for the exe type. The returned pointer contains the encoded // executable type data. ptr = IntPtr.Zero; ptr = SHGetFileInfo(fileName, FileAttributes.Normal, ref this.shellFileInfo, Marshal.SizeOf(typeof(SHFILEINFO)), SHGFI.EXETYPE); // We need to split the returned pointer up into the high and low order words. These are important // because they help distinguish some of the types. The possible values are: // // Value Meaning // ---------------------------------------------------------------------------------------------- // 0 Nonexecutable file or an error condition. // LOWORD = NE or PE and HIWORD = Windows version Microsoft Windows application. // LOWORD = MZ and HIWORD = 0 Windows 95, Windows 98: Microsoft MS-DOS .exe, .com, or .bat file // Microsoft Windows NT, Windows 2000, Windows XP: MS-DOS .exe or .com file // LOWORD = PE and HIWORD = 0 Windows 95, Windows 98: Microsoft Win32 console application // Windows NT, Windows 2000, Windows XP: Win32 console application or .bat file // MZ = 0x5A4D - DOS signature. // NE = 0x454E - OS/2 signature. // LE = 0x454C - OS/2 LE or VXD signature. // PE = 0x4550 - Win32/NT signature. int wparam = ptr.ToInt32(); int loWord = wparam & 0xffff; int hiWord = wparam >> 16; if (wparam == 0) { executableType = ExecutableType.Unknown; } else { if (hiWord == 0x0000) { if (loWord == 0x5A4D) { // The file is an MS-DOS .exe, .com, or .bat executableType = ExecutableType.DOS; } else if (loWord == 0x4550) { executableType = ExecutableType.Win32Console; } } else { if (loWord == 0x454E || loWord == 0x4550) { executableType = ExecutableType.Windows; } else if (loWord == 0x454C) { executableType = ExecutableType.Windows; } } } } return executableType; } ``` *(This should work, but was extracted from a larger library so there may be minor issues. It should, however, be complete enough to get you most of the way there.)*
In Windows there is no real notion of "executable", like the specific permission that exists in \*NIX systems. You have two options. The first one, like saurabh had suggested before me, is to rely on the system to associate between the file extension and the command to be performed. This approach (of using Process.Start) has many advantages - it leaves the power of association to the user, as in letting the user pick the correct way to run the various file types. The second option is to mimic the Windows file association process, by having a dictionary from an extension to the command that can run the file, and falling back to checking the first line of the file if needed. This has the advantage of you having the power of setting the associations, but it also requires constant modifications and maintenance on your side, in addition to losing the flexibility on the user side - which may be a good thing or a bad thing.
3,693,891
I'm writing a program that (part of what is does is) executes other programs. I want to to be able to run as many types of programs (written in different languages) as possible using `Process.Start` . So, I'm thinking I should: 1. Open the file 2. Read in the first line 3. Check if it starts with `#!` 4. If so, use what follows the `#!` as the program to execute, and pass in the filename as an argument instead 5. If no `#!` is found, check the file extension against a dictionary of known programs (e.g., `.py -> python`) and execute that program instead 6. Otherwise, just try executing the file and catch any errors But, I'm thinking it might be easier/more efficient to actually check if the file is executable first and if so, jump to 6. Is there a way to do this?
2010/09/12
[ "https://Stackoverflow.com/questions/3693891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
In Windows there is no real notion of "executable", like the specific permission that exists in \*NIX systems. You have two options. The first one, like saurabh had suggested before me, is to rely on the system to associate between the file extension and the command to be performed. This approach (of using Process.Start) has many advantages - it leaves the power of association to the user, as in letting the user pick the correct way to run the various file types. The second option is to mimic the Windows file association process, by having a dictionary from an extension to the command that can run the file, and falling back to checking the first line of the file if needed. This has the advantage of you having the power of setting the associations, but it also requires constant modifications and maintenance on your side, in addition to losing the flexibility on the user side - which may be a good thing or a bad thing.
You should be able to pretty much start with step 5. Ie check the file extension first. Windows lives for file extensions. There's not much you can do without them. If you recognise the extension as an executable, then you can pass it to Process.Start or open the file and find out which executable you should be passing it to. I would also look for the .net equivalent to ShellExecute, because I'm not 100% convinced it's Process.Start. (I've not really done much .net/c# coding in the last 5 years though, so I could be wrong here.)
3,693,891
I'm writing a program that (part of what is does is) executes other programs. I want to to be able to run as many types of programs (written in different languages) as possible using `Process.Start` . So, I'm thinking I should: 1. Open the file 2. Read in the first line 3. Check if it starts with `#!` 4. If so, use what follows the `#!` as the program to execute, and pass in the filename as an argument instead 5. If no `#!` is found, check the file extension against a dictionary of known programs (e.g., `.py -> python`) and execute that program instead 6. Otherwise, just try executing the file and catch any errors But, I'm thinking it might be easier/more efficient to actually check if the file is executable first and if so, jump to 6. Is there a way to do this?
2010/09/12
[ "https://Stackoverflow.com/questions/3693891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
In Windows there is no real notion of "executable", like the specific permission that exists in \*NIX systems. You have two options. The first one, like saurabh had suggested before me, is to rely on the system to associate between the file extension and the command to be performed. This approach (of using Process.Start) has many advantages - it leaves the power of association to the user, as in letting the user pick the correct way to run the various file types. The second option is to mimic the Windows file association process, by having a dictionary from an extension to the command that can run the file, and falling back to checking the first line of the file if needed. This has the advantage of you having the power of setting the associations, but it also requires constant modifications and maintenance on your side, in addition to losing the flexibility on the user side - which may be a good thing or a bad thing.
Since you mention Linux, you might consider using the 'file' command. I believe gnuwin32 has a port of this command for windows. Of course, that'd mean parsing the output returned by 'file' (the file MIME type such as "application/x-executable"). So depending on the number of executables you want to be able to recognise, this might not be the easiest solution. [Edit: added example output] > > file.exe d:\Downloads\tabview.py > > > d:\Downloads\tabview.py; a /usr/local/bin/python script text executable > > file.exe d:\Downloads\tabview.txt > > > d:\Downloads\tabview.txt; a /usr/local/bin/python script text executable> > > file.exe d:\Downloads\7zbv14ww.exe > > > d:\Downloads\7zbv14ww.exe; PE32 executable for MS Windows (GUI) Intel 80386 32- > it > > file.exe -b d:\Downloads\AlbumArtSmall.jpg > > > JPEG image data, JFIF standard 1.01 > > > > > > > > >
3,693,891
I'm writing a program that (part of what is does is) executes other programs. I want to to be able to run as many types of programs (written in different languages) as possible using `Process.Start` . So, I'm thinking I should: 1. Open the file 2. Read in the first line 3. Check if it starts with `#!` 4. If so, use what follows the `#!` as the program to execute, and pass in the filename as an argument instead 5. If no `#!` is found, check the file extension against a dictionary of known programs (e.g., `.py -> python`) and execute that program instead 6. Otherwise, just try executing the file and catch any errors But, I'm thinking it might be easier/more efficient to actually check if the file is executable first and if so, jump to 6. Is there a way to do this?
2010/09/12
[ "https://Stackoverflow.com/questions/3693891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
In Windows there is no real notion of "executable", like the specific permission that exists in \*NIX systems. You have two options. The first one, like saurabh had suggested before me, is to rely on the system to associate between the file extension and the command to be performed. This approach (of using Process.Start) has many advantages - it leaves the power of association to the user, as in letting the user pick the correct way to run the various file types. The second option is to mimic the Windows file association process, by having a dictionary from an extension to the command that can run the file, and falling back to checking the first line of the file if needed. This has the advantage of you having the power of setting the associations, but it also requires constant modifications and maintenance on your side, in addition to losing the flexibility on the user side - which may be a good thing or a bad thing.
Using some information from Scott's answer, I wrote my own method which returns an Enum value specifying the type of the file. What I noticed with his solution is that it will return 'Unknown' even if the file does not exist. Additionally, I simplified a couple of the `if` conditions and added an additional condition for when none of the conditions were met. ShellFileGetInfo class ---------------------- ``` public static class ShellFileGetInfo { [DllImport("shell32.dll")] public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags); [StructLayout(LayoutKind.Sequential)] public struct SHFILEINFO { public IntPtr hIcon; public IntPtr iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; }; // Enum for return of the file type public enum ShellFileType { FileNotFound, Unknown, Dos, Windows, Console } // Apply the appropriate overlays to the file's icon. The SHGFI_ICON flag must also be set. public const uint SHGFI_ADDOVERLAYS = 0x000000020; // Modify SHGFI_ATTRIBUTES to indicate that the dwAttributes member of the SHFILEINFO structure at psfi contains the specific attributes that are desired. These attributes are passed to IShellFolder::GetAttributesOf. If this flag is not specified, 0xFFFFFFFF is passed to IShellFolder::GetAttributesOf, requesting all attributes. This flag cannot be specified with the SHGFI_ICON flag. public const uint SHGFI_ATTR_SPECIFIED = 0x000020000; // Retrieve the item attributes. The attributes are copied to the dwAttributes member of the structure specified in the psfi parameter. These are the same attributes that are obtained from IShellFolder::GetAttributesOf. public const uint SHGFI_ATTRIBUTES = 0x000000800; // Retrieve the display name for the file, which is the name as it appears in Windows Explorer. The name is copied to the szDisplayName member of the structure specified in psfi. The returned display name uses the long file name, if there is one, rather than the 8.3 form of the file name. Note that the display name can be affected by settings such as whether extensions are shown. public const uint SHGFI_DISPLAYNAME = 0x000000200; // Retrieve the type of the executable file if pszPath identifies an executable file. The information is packed into the return value. This flag cannot be specified with any other flags. public const uint SHGFI_EXETYPE = 0x000002000; // Retrieve the handle to the icon that represents the file and the index of the icon within the system image list. The handle is copied to the hIcon member of the structure specified by psfi, and the index is copied to the iIcon member. public const uint SHGFI_ICON = 0x000000100; // Retrieve the name of the file that contains the icon representing the file specified by pszPath, as returned by the IExtractIcon::GetIconLocation method of the file's icon handler. Also retrieve the icon index within that file. The name of the file containing the icon is copied to the szDisplayName member of the structure specified by psfi. The icon's index is copied to that structure's iIcon member. public const uint SHGFI_ICONLOCATION = 0x000001000; // Modify SHGFI_ICON, causing the function to retrieve the file's large icon. The SHGFI_ICON flag must also be set. public const uint SHGFI_LARGEICON = 0x000000000; // Modify SHGFI_ICON, causing the function to add the link overlay to the file's icon. The SHGFI_ICON flag must also be set. public const uint SHGFI_LINKOVERLAY = 0x000008000; // Modify SHGFI_ICON, causing the function to retrieve the file's open icon. Also used to modify SHGFI_SYSICONINDEX, causing the function to return the handle to the system image list that contains the file's small open icon. A container object displays an open icon to indicate that the container is open. The SHGFI_ICON and/or SHGFI_SYSICONINDEX flag must also be set. public const uint SHGFI_OPENICON = 0x000000002; // Version 5.0. Return the index of the overlay icon. The value of the overlay index is returned in the upper eight bits of the iIcon member of the structure specified by psfi. This flag requires that the SHGFI_ICON be set as well. public const uint SHGFI_OVERLAYINDEX = 0x000000040; // Indicate that pszPath is the address of an ITEMIDLIST structure rather than a path name. public const uint SHGFI_PIDL = 0x000000008; // Modify SHGFI_ICON, causing the function to blend the file's icon with the system highlight color. The SHGFI_ICON flag must also be set. public const uint SHGFI_SELECTED = 0x000010000; // Modify SHGFI_ICON, causing the function to retrieve a Shell-sized icon. If this flag is not specified the function sizes the icon according to the system metric values. The SHGFI_ICON flag must also be set. public const uint SHGFI_SHELLICONSIZE = 0x000000004; // Modify SHGFI_ICON, causing the function to retrieve the file's small icon. Also used to modify SHGFI_SYSICONINDEX, causing the function to return the handle to the system image list that contains small icon images. The SHGFI_ICON and/or SHGFI_SYSICONINDEX flag must also be set. public const uint SHGFI_SMALLICON = 0x000000001; // Retrieve the index of a system image list icon. If successful, the index is copied to the iIcon member of psfi. The return value is a handle to the system image list. Only those images whose indices are successfully copied to iIcon are valid. Attempting to access other images in the system image list will result in undefined behavior. public const uint SHGFI_SYSICONINDEX = 0x000004000; // Retrieve the string that describes the file's type. The string is copied to the szTypeName member of the structure specified in psfi. public const uint SHGFI_TYPENAME = 0x000000400; // Indicates that the function should not attempt to access the file specified by pszPath. Rather, it should act as if the file specified by pszPath exists with the file attributes passed in dwFileAttributes. This flag cannot be combined with the SHGFI_ATTRIBUTES, SHGFI_EXETYPE, or SHGFI_PIDL flags. public const uint SHGFI_USEFILEATTRIBUTES = 0x000000010; } ``` Method to Get File Type (exe type) ---------------------------------- ``` public static ShellFileGetInfo.ShellFileType GetExeType(string file) { ShellFileGetInfo.ShellFileType type = ShellFileGetInfo.ShellFileType.FileNotFound; if (File.Exists(file)) { ShellFileGetInfo.SHFILEINFO shinfo = new ShellFileGetInfo.SHFILEINFO(); IntPtr ptr = ShellFileGetInfo.SHGetFileInfo(file, 128, ref shinfo, (uint)Marshal.SizeOf(shinfo), ShellFileGetInfo.SHGFI_EXETYPE); int wparam = ptr.ToInt32(); int loWord = wparam & 0xffff; int hiWord = wparam >> 16; type = ShellFileGetInfo.ShellFileType.Unknown; if(wparam != 0) { if (hiWord == 0x0000 && loWord == 0x5a4d) { type = ShellFileGetInfo.ShellFileType.Dos; } else if (hiWord == 0x0000 && loWord == 0x4550) { type = ShellFileGetInfo.ShellFileType.Console; } else if ((hiWord != 0x0000) && (loWord == 0x454E || loWord == 0x4550 || loWord == 0x454C)) { type = ShellFileGetInfo.ShellFileType.Windows; } } } return type; } ``` Usage of Method --------------- ``` switch(GetExeType( file )) { case ShellFileGetInfo.ShellFileType.Unknown: System.Diagnostics.Debug.WriteLine( "Unknown: " + file ); break; case ShellFileGetInfo.ShellFileType.Dos: System.Diagnostics.Debug.WriteLine( "DOS: " + file ); break; case ShellFileGetInfo.ShellFileType.Windows: System.Diagnostics.Debug.WriteLine( "Windows: " + file ); break; case ShellFileGetInfo.ShellFileType.Console: System.Diagnostics.Debug.WriteLine( "Console: " + file ); break; case ShellFileGetInfo.ShellFileType.FileNotFound: System.Diagnostics.Debug.WriteLine( "Missing: " + file ); break; } ```
3,693,891
I'm writing a program that (part of what is does is) executes other programs. I want to to be able to run as many types of programs (written in different languages) as possible using `Process.Start` . So, I'm thinking I should: 1. Open the file 2. Read in the first line 3. Check if it starts with `#!` 4. If so, use what follows the `#!` as the program to execute, and pass in the filename as an argument instead 5. If no `#!` is found, check the file extension against a dictionary of known programs (e.g., `.py -> python`) and execute that program instead 6. Otherwise, just try executing the file and catch any errors But, I'm thinking it might be easier/more efficient to actually check if the file is executable first and if so, jump to 6. Is there a way to do this?
2010/09/12
[ "https://Stackoverflow.com/questions/3693891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
The only way to do this is to use P/Invoke calls in to the Win32 API. You need to use the SHGetFileInfo method and then unpack the return value: ``` [Flags] internal enum SHGFI : uint { ADDOVERLAYS = 0x20, ATTR_SPECIFIED = 0x20000, ATTRIBUTES = 0x800, DISPLAYNAME = 0x200, EXETYPE = 0x2000, ICON = 0x100, ICONLOCATION = 0x1000, LARGEICON = 0, LINKOVERLAY = 0x8000, OPENICON = 2, OVERLAYINDEX = 0x40, PIDL = 8, SELECTED = 0x10000, SHELLICONSIZE = 4, SMALLICON = 1, SYSICONINDEX = 0x4000, TYPENAME = 0x400, USEFILEATTRIBUTES = 0x10 } /// <summary> /// This structure contains information about a file object. /// </summary> /// <remarks> /// This structure is used with the SHGetFileInfo function. /// </remarks> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SHFILEINFO { /// <summary> /// Handle to the icon that represents the file. /// </summary> internal IntPtr hIcon; /// <summary> /// Index of the icon image within the system image list. /// </summary> internal int iIcon; /// <summary> /// Specifies the attributes of the file object. /// </summary> internal SFGAO dwAttributes; /// <summary> /// Null-terminated string that contains the name of the file as it /// appears in the Windows shell, or the path and name of the file that /// contains the icon representing the file. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Constants.MAX_PATH)] internal string szDisplayName; /// <summary> /// Null-terminated string that describes the type of file. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] internal string szTypeName; } /// <summary> /// Specifies the executable file type. /// </summary> public enum ExecutableType : int { /// <summary> /// The file executable type is not able to be determined. /// </summary> Unknown = 0, /// <summary> /// The file is an MS-DOS .exe, .com, or .bat file. /// </summary> DOS, /// <summary> /// The file is a Microsoft Win32®-based console application. /// </summary> Win32Console, /// <summary> /// The file is a Windows application. /// </summary> Windows, } // Retrieves information about an object in the file system, // such as a file, a folder, a directory, or a drive root. [DllImport("shell32", EntryPoint = "SHGetFileInfo", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)] internal static extern IntPtr SHGetFileInfo( string pszPath, FileAttributes dwFileAttributes, ref SHFILEINFO sfi, int cbFileInfo, SHGFI uFlags); [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] private ExecutableType IsExecutable(string fileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } ExecutableType executableType = ExecutableType.Unknown; if (File.Exists(fileName) { // Try to fill the same SHFILEINFO struct for the exe type. The returned pointer contains the encoded // executable type data. ptr = IntPtr.Zero; ptr = SHGetFileInfo(fileName, FileAttributes.Normal, ref this.shellFileInfo, Marshal.SizeOf(typeof(SHFILEINFO)), SHGFI.EXETYPE); // We need to split the returned pointer up into the high and low order words. These are important // because they help distinguish some of the types. The possible values are: // // Value Meaning // ---------------------------------------------------------------------------------------------- // 0 Nonexecutable file or an error condition. // LOWORD = NE or PE and HIWORD = Windows version Microsoft Windows application. // LOWORD = MZ and HIWORD = 0 Windows 95, Windows 98: Microsoft MS-DOS .exe, .com, or .bat file // Microsoft Windows NT, Windows 2000, Windows XP: MS-DOS .exe or .com file // LOWORD = PE and HIWORD = 0 Windows 95, Windows 98: Microsoft Win32 console application // Windows NT, Windows 2000, Windows XP: Win32 console application or .bat file // MZ = 0x5A4D - DOS signature. // NE = 0x454E - OS/2 signature. // LE = 0x454C - OS/2 LE or VXD signature. // PE = 0x4550 - Win32/NT signature. int wparam = ptr.ToInt32(); int loWord = wparam & 0xffff; int hiWord = wparam >> 16; if (wparam == 0) { executableType = ExecutableType.Unknown; } else { if (hiWord == 0x0000) { if (loWord == 0x5A4D) { // The file is an MS-DOS .exe, .com, or .bat executableType = ExecutableType.DOS; } else if (loWord == 0x4550) { executableType = ExecutableType.Win32Console; } } else { if (loWord == 0x454E || loWord == 0x4550) { executableType = ExecutableType.Windows; } else if (loWord == 0x454C) { executableType = ExecutableType.Windows; } } } } return executableType; } ``` *(This should work, but was extracted from a larger library so there may be minor issues. It should, however, be complete enough to get you most of the way there.)*
You should be able to pretty much start with step 5. Ie check the file extension first. Windows lives for file extensions. There's not much you can do without them. If you recognise the extension as an executable, then you can pass it to Process.Start or open the file and find out which executable you should be passing it to. I would also look for the .net equivalent to ShellExecute, because I'm not 100% convinced it's Process.Start. (I've not really done much .net/c# coding in the last 5 years though, so I could be wrong here.)
3,693,891
I'm writing a program that (part of what is does is) executes other programs. I want to to be able to run as many types of programs (written in different languages) as possible using `Process.Start` . So, I'm thinking I should: 1. Open the file 2. Read in the first line 3. Check if it starts with `#!` 4. If so, use what follows the `#!` as the program to execute, and pass in the filename as an argument instead 5. If no `#!` is found, check the file extension against a dictionary of known programs (e.g., `.py -> python`) and execute that program instead 6. Otherwise, just try executing the file and catch any errors But, I'm thinking it might be easier/more efficient to actually check if the file is executable first and if so, jump to 6. Is there a way to do this?
2010/09/12
[ "https://Stackoverflow.com/questions/3693891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
The only way to do this is to use P/Invoke calls in to the Win32 API. You need to use the SHGetFileInfo method and then unpack the return value: ``` [Flags] internal enum SHGFI : uint { ADDOVERLAYS = 0x20, ATTR_SPECIFIED = 0x20000, ATTRIBUTES = 0x800, DISPLAYNAME = 0x200, EXETYPE = 0x2000, ICON = 0x100, ICONLOCATION = 0x1000, LARGEICON = 0, LINKOVERLAY = 0x8000, OPENICON = 2, OVERLAYINDEX = 0x40, PIDL = 8, SELECTED = 0x10000, SHELLICONSIZE = 4, SMALLICON = 1, SYSICONINDEX = 0x4000, TYPENAME = 0x400, USEFILEATTRIBUTES = 0x10 } /// <summary> /// This structure contains information about a file object. /// </summary> /// <remarks> /// This structure is used with the SHGetFileInfo function. /// </remarks> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SHFILEINFO { /// <summary> /// Handle to the icon that represents the file. /// </summary> internal IntPtr hIcon; /// <summary> /// Index of the icon image within the system image list. /// </summary> internal int iIcon; /// <summary> /// Specifies the attributes of the file object. /// </summary> internal SFGAO dwAttributes; /// <summary> /// Null-terminated string that contains the name of the file as it /// appears in the Windows shell, or the path and name of the file that /// contains the icon representing the file. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Constants.MAX_PATH)] internal string szDisplayName; /// <summary> /// Null-terminated string that describes the type of file. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] internal string szTypeName; } /// <summary> /// Specifies the executable file type. /// </summary> public enum ExecutableType : int { /// <summary> /// The file executable type is not able to be determined. /// </summary> Unknown = 0, /// <summary> /// The file is an MS-DOS .exe, .com, or .bat file. /// </summary> DOS, /// <summary> /// The file is a Microsoft Win32®-based console application. /// </summary> Win32Console, /// <summary> /// The file is a Windows application. /// </summary> Windows, } // Retrieves information about an object in the file system, // such as a file, a folder, a directory, or a drive root. [DllImport("shell32", EntryPoint = "SHGetFileInfo", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)] internal static extern IntPtr SHGetFileInfo( string pszPath, FileAttributes dwFileAttributes, ref SHFILEINFO sfi, int cbFileInfo, SHGFI uFlags); [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] private ExecutableType IsExecutable(string fileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } ExecutableType executableType = ExecutableType.Unknown; if (File.Exists(fileName) { // Try to fill the same SHFILEINFO struct for the exe type. The returned pointer contains the encoded // executable type data. ptr = IntPtr.Zero; ptr = SHGetFileInfo(fileName, FileAttributes.Normal, ref this.shellFileInfo, Marshal.SizeOf(typeof(SHFILEINFO)), SHGFI.EXETYPE); // We need to split the returned pointer up into the high and low order words. These are important // because they help distinguish some of the types. The possible values are: // // Value Meaning // ---------------------------------------------------------------------------------------------- // 0 Nonexecutable file or an error condition. // LOWORD = NE or PE and HIWORD = Windows version Microsoft Windows application. // LOWORD = MZ and HIWORD = 0 Windows 95, Windows 98: Microsoft MS-DOS .exe, .com, or .bat file // Microsoft Windows NT, Windows 2000, Windows XP: MS-DOS .exe or .com file // LOWORD = PE and HIWORD = 0 Windows 95, Windows 98: Microsoft Win32 console application // Windows NT, Windows 2000, Windows XP: Win32 console application or .bat file // MZ = 0x5A4D - DOS signature. // NE = 0x454E - OS/2 signature. // LE = 0x454C - OS/2 LE or VXD signature. // PE = 0x4550 - Win32/NT signature. int wparam = ptr.ToInt32(); int loWord = wparam & 0xffff; int hiWord = wparam >> 16; if (wparam == 0) { executableType = ExecutableType.Unknown; } else { if (hiWord == 0x0000) { if (loWord == 0x5A4D) { // The file is an MS-DOS .exe, .com, or .bat executableType = ExecutableType.DOS; } else if (loWord == 0x4550) { executableType = ExecutableType.Win32Console; } } else { if (loWord == 0x454E || loWord == 0x4550) { executableType = ExecutableType.Windows; } else if (loWord == 0x454C) { executableType = ExecutableType.Windows; } } } } return executableType; } ``` *(This should work, but was extracted from a larger library so there may be minor issues. It should, however, be complete enough to get you most of the way there.)*
Since you mention Linux, you might consider using the 'file' command. I believe gnuwin32 has a port of this command for windows. Of course, that'd mean parsing the output returned by 'file' (the file MIME type such as "application/x-executable"). So depending on the number of executables you want to be able to recognise, this might not be the easiest solution. [Edit: added example output] > > file.exe d:\Downloads\tabview.py > > > d:\Downloads\tabview.py; a /usr/local/bin/python script text executable > > file.exe d:\Downloads\tabview.txt > > > d:\Downloads\tabview.txt; a /usr/local/bin/python script text executable> > > file.exe d:\Downloads\7zbv14ww.exe > > > d:\Downloads\7zbv14ww.exe; PE32 executable for MS Windows (GUI) Intel 80386 32- > it > > file.exe -b d:\Downloads\AlbumArtSmall.jpg > > > JPEG image data, JFIF standard 1.01 > > > > > > > > >
3,693,891
I'm writing a program that (part of what is does is) executes other programs. I want to to be able to run as many types of programs (written in different languages) as possible using `Process.Start` . So, I'm thinking I should: 1. Open the file 2. Read in the first line 3. Check if it starts with `#!` 4. If so, use what follows the `#!` as the program to execute, and pass in the filename as an argument instead 5. If no `#!` is found, check the file extension against a dictionary of known programs (e.g., `.py -> python`) and execute that program instead 6. Otherwise, just try executing the file and catch any errors But, I'm thinking it might be easier/more efficient to actually check if the file is executable first and if so, jump to 6. Is there a way to do this?
2010/09/12
[ "https://Stackoverflow.com/questions/3693891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
The only way to do this is to use P/Invoke calls in to the Win32 API. You need to use the SHGetFileInfo method and then unpack the return value: ``` [Flags] internal enum SHGFI : uint { ADDOVERLAYS = 0x20, ATTR_SPECIFIED = 0x20000, ATTRIBUTES = 0x800, DISPLAYNAME = 0x200, EXETYPE = 0x2000, ICON = 0x100, ICONLOCATION = 0x1000, LARGEICON = 0, LINKOVERLAY = 0x8000, OPENICON = 2, OVERLAYINDEX = 0x40, PIDL = 8, SELECTED = 0x10000, SHELLICONSIZE = 4, SMALLICON = 1, SYSICONINDEX = 0x4000, TYPENAME = 0x400, USEFILEATTRIBUTES = 0x10 } /// <summary> /// This structure contains information about a file object. /// </summary> /// <remarks> /// This structure is used with the SHGetFileInfo function. /// </remarks> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SHFILEINFO { /// <summary> /// Handle to the icon that represents the file. /// </summary> internal IntPtr hIcon; /// <summary> /// Index of the icon image within the system image list. /// </summary> internal int iIcon; /// <summary> /// Specifies the attributes of the file object. /// </summary> internal SFGAO dwAttributes; /// <summary> /// Null-terminated string that contains the name of the file as it /// appears in the Windows shell, or the path and name of the file that /// contains the icon representing the file. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Constants.MAX_PATH)] internal string szDisplayName; /// <summary> /// Null-terminated string that describes the type of file. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] internal string szTypeName; } /// <summary> /// Specifies the executable file type. /// </summary> public enum ExecutableType : int { /// <summary> /// The file executable type is not able to be determined. /// </summary> Unknown = 0, /// <summary> /// The file is an MS-DOS .exe, .com, or .bat file. /// </summary> DOS, /// <summary> /// The file is a Microsoft Win32®-based console application. /// </summary> Win32Console, /// <summary> /// The file is a Windows application. /// </summary> Windows, } // Retrieves information about an object in the file system, // such as a file, a folder, a directory, or a drive root. [DllImport("shell32", EntryPoint = "SHGetFileInfo", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)] internal static extern IntPtr SHGetFileInfo( string pszPath, FileAttributes dwFileAttributes, ref SHFILEINFO sfi, int cbFileInfo, SHGFI uFlags); [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] private ExecutableType IsExecutable(string fileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } ExecutableType executableType = ExecutableType.Unknown; if (File.Exists(fileName) { // Try to fill the same SHFILEINFO struct for the exe type. The returned pointer contains the encoded // executable type data. ptr = IntPtr.Zero; ptr = SHGetFileInfo(fileName, FileAttributes.Normal, ref this.shellFileInfo, Marshal.SizeOf(typeof(SHFILEINFO)), SHGFI.EXETYPE); // We need to split the returned pointer up into the high and low order words. These are important // because they help distinguish some of the types. The possible values are: // // Value Meaning // ---------------------------------------------------------------------------------------------- // 0 Nonexecutable file or an error condition. // LOWORD = NE or PE and HIWORD = Windows version Microsoft Windows application. // LOWORD = MZ and HIWORD = 0 Windows 95, Windows 98: Microsoft MS-DOS .exe, .com, or .bat file // Microsoft Windows NT, Windows 2000, Windows XP: MS-DOS .exe or .com file // LOWORD = PE and HIWORD = 0 Windows 95, Windows 98: Microsoft Win32 console application // Windows NT, Windows 2000, Windows XP: Win32 console application or .bat file // MZ = 0x5A4D - DOS signature. // NE = 0x454E - OS/2 signature. // LE = 0x454C - OS/2 LE or VXD signature. // PE = 0x4550 - Win32/NT signature. int wparam = ptr.ToInt32(); int loWord = wparam & 0xffff; int hiWord = wparam >> 16; if (wparam == 0) { executableType = ExecutableType.Unknown; } else { if (hiWord == 0x0000) { if (loWord == 0x5A4D) { // The file is an MS-DOS .exe, .com, or .bat executableType = ExecutableType.DOS; } else if (loWord == 0x4550) { executableType = ExecutableType.Win32Console; } } else { if (loWord == 0x454E || loWord == 0x4550) { executableType = ExecutableType.Windows; } else if (loWord == 0x454C) { executableType = ExecutableType.Windows; } } } } return executableType; } ``` *(This should work, but was extracted from a larger library so there may be minor issues. It should, however, be complete enough to get you most of the way there.)*
Using some information from Scott's answer, I wrote my own method which returns an Enum value specifying the type of the file. What I noticed with his solution is that it will return 'Unknown' even if the file does not exist. Additionally, I simplified a couple of the `if` conditions and added an additional condition for when none of the conditions were met. ShellFileGetInfo class ---------------------- ``` public static class ShellFileGetInfo { [DllImport("shell32.dll")] public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags); [StructLayout(LayoutKind.Sequential)] public struct SHFILEINFO { public IntPtr hIcon; public IntPtr iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; }; // Enum for return of the file type public enum ShellFileType { FileNotFound, Unknown, Dos, Windows, Console } // Apply the appropriate overlays to the file's icon. The SHGFI_ICON flag must also be set. public const uint SHGFI_ADDOVERLAYS = 0x000000020; // Modify SHGFI_ATTRIBUTES to indicate that the dwAttributes member of the SHFILEINFO structure at psfi contains the specific attributes that are desired. These attributes are passed to IShellFolder::GetAttributesOf. If this flag is not specified, 0xFFFFFFFF is passed to IShellFolder::GetAttributesOf, requesting all attributes. This flag cannot be specified with the SHGFI_ICON flag. public const uint SHGFI_ATTR_SPECIFIED = 0x000020000; // Retrieve the item attributes. The attributes are copied to the dwAttributes member of the structure specified in the psfi parameter. These are the same attributes that are obtained from IShellFolder::GetAttributesOf. public const uint SHGFI_ATTRIBUTES = 0x000000800; // Retrieve the display name for the file, which is the name as it appears in Windows Explorer. The name is copied to the szDisplayName member of the structure specified in psfi. The returned display name uses the long file name, if there is one, rather than the 8.3 form of the file name. Note that the display name can be affected by settings such as whether extensions are shown. public const uint SHGFI_DISPLAYNAME = 0x000000200; // Retrieve the type of the executable file if pszPath identifies an executable file. The information is packed into the return value. This flag cannot be specified with any other flags. public const uint SHGFI_EXETYPE = 0x000002000; // Retrieve the handle to the icon that represents the file and the index of the icon within the system image list. The handle is copied to the hIcon member of the structure specified by psfi, and the index is copied to the iIcon member. public const uint SHGFI_ICON = 0x000000100; // Retrieve the name of the file that contains the icon representing the file specified by pszPath, as returned by the IExtractIcon::GetIconLocation method of the file's icon handler. Also retrieve the icon index within that file. The name of the file containing the icon is copied to the szDisplayName member of the structure specified by psfi. The icon's index is copied to that structure's iIcon member. public const uint SHGFI_ICONLOCATION = 0x000001000; // Modify SHGFI_ICON, causing the function to retrieve the file's large icon. The SHGFI_ICON flag must also be set. public const uint SHGFI_LARGEICON = 0x000000000; // Modify SHGFI_ICON, causing the function to add the link overlay to the file's icon. The SHGFI_ICON flag must also be set. public const uint SHGFI_LINKOVERLAY = 0x000008000; // Modify SHGFI_ICON, causing the function to retrieve the file's open icon. Also used to modify SHGFI_SYSICONINDEX, causing the function to return the handle to the system image list that contains the file's small open icon. A container object displays an open icon to indicate that the container is open. The SHGFI_ICON and/or SHGFI_SYSICONINDEX flag must also be set. public const uint SHGFI_OPENICON = 0x000000002; // Version 5.0. Return the index of the overlay icon. The value of the overlay index is returned in the upper eight bits of the iIcon member of the structure specified by psfi. This flag requires that the SHGFI_ICON be set as well. public const uint SHGFI_OVERLAYINDEX = 0x000000040; // Indicate that pszPath is the address of an ITEMIDLIST structure rather than a path name. public const uint SHGFI_PIDL = 0x000000008; // Modify SHGFI_ICON, causing the function to blend the file's icon with the system highlight color. The SHGFI_ICON flag must also be set. public const uint SHGFI_SELECTED = 0x000010000; // Modify SHGFI_ICON, causing the function to retrieve a Shell-sized icon. If this flag is not specified the function sizes the icon according to the system metric values. The SHGFI_ICON flag must also be set. public const uint SHGFI_SHELLICONSIZE = 0x000000004; // Modify SHGFI_ICON, causing the function to retrieve the file's small icon. Also used to modify SHGFI_SYSICONINDEX, causing the function to return the handle to the system image list that contains small icon images. The SHGFI_ICON and/or SHGFI_SYSICONINDEX flag must also be set. public const uint SHGFI_SMALLICON = 0x000000001; // Retrieve the index of a system image list icon. If successful, the index is copied to the iIcon member of psfi. The return value is a handle to the system image list. Only those images whose indices are successfully copied to iIcon are valid. Attempting to access other images in the system image list will result in undefined behavior. public const uint SHGFI_SYSICONINDEX = 0x000004000; // Retrieve the string that describes the file's type. The string is copied to the szTypeName member of the structure specified in psfi. public const uint SHGFI_TYPENAME = 0x000000400; // Indicates that the function should not attempt to access the file specified by pszPath. Rather, it should act as if the file specified by pszPath exists with the file attributes passed in dwFileAttributes. This flag cannot be combined with the SHGFI_ATTRIBUTES, SHGFI_EXETYPE, or SHGFI_PIDL flags. public const uint SHGFI_USEFILEATTRIBUTES = 0x000000010; } ``` Method to Get File Type (exe type) ---------------------------------- ``` public static ShellFileGetInfo.ShellFileType GetExeType(string file) { ShellFileGetInfo.ShellFileType type = ShellFileGetInfo.ShellFileType.FileNotFound; if (File.Exists(file)) { ShellFileGetInfo.SHFILEINFO shinfo = new ShellFileGetInfo.SHFILEINFO(); IntPtr ptr = ShellFileGetInfo.SHGetFileInfo(file, 128, ref shinfo, (uint)Marshal.SizeOf(shinfo), ShellFileGetInfo.SHGFI_EXETYPE); int wparam = ptr.ToInt32(); int loWord = wparam & 0xffff; int hiWord = wparam >> 16; type = ShellFileGetInfo.ShellFileType.Unknown; if(wparam != 0) { if (hiWord == 0x0000 && loWord == 0x5a4d) { type = ShellFileGetInfo.ShellFileType.Dos; } else if (hiWord == 0x0000 && loWord == 0x4550) { type = ShellFileGetInfo.ShellFileType.Console; } else if ((hiWord != 0x0000) && (loWord == 0x454E || loWord == 0x4550 || loWord == 0x454C)) { type = ShellFileGetInfo.ShellFileType.Windows; } } } return type; } ``` Usage of Method --------------- ``` switch(GetExeType( file )) { case ShellFileGetInfo.ShellFileType.Unknown: System.Diagnostics.Debug.WriteLine( "Unknown: " + file ); break; case ShellFileGetInfo.ShellFileType.Dos: System.Diagnostics.Debug.WriteLine( "DOS: " + file ); break; case ShellFileGetInfo.ShellFileType.Windows: System.Diagnostics.Debug.WriteLine( "Windows: " + file ); break; case ShellFileGetInfo.ShellFileType.Console: System.Diagnostics.Debug.WriteLine( "Console: " + file ); break; case ShellFileGetInfo.ShellFileType.FileNotFound: System.Diagnostics.Debug.WriteLine( "Missing: " + file ); break; } ```
16,082,243
``` <Control-Shift-Key-0> <Control-Key-plus> ``` works but ``` <Control-Key-/> ``` doesn't. I am unable to bind `ctrl` + `/` in python. Is there any documentation of all the possible keys?
2013/04/18
[ "https://Stackoverflow.com/questions/16082243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2219529/" ]
Use `<Control-slash>`: ``` def quit(event): print "you pressed control-forwardslash" root.quit() root = tk.Tk() root.bind('<Control-slash>', quit) # forward-slash # root.bind('<Control-backslash>', quit) # backslash root.mainloop() ``` --- I don't have a link to a complete list of these event names. Here is a partial list I've collected: ``` | event | name | | Ctrl-c | Control-c | | Ctrl-/ | Control-slash | | Ctrl-\ | Control-backslash | | Ctrl+(Mouse Button-1) | Control-1 | | Ctrl-1 | Control-Key-1 | | Enter key | Return | | | Button-1 | | | ButtonRelease-1 | | | Home | | | Up, Down, Left, Right | | | Configure | | window exposed | Expose | | mouse enters widget | Enter | | mouse leaves widget | Leave | | | Key | | | Tab | | | space | | | BackSpace | | | KeyRelease-BackSpace | | any key release | KeyRelease | | escape | Escape | | | F1 | | | Alt-h | ```
Here is a list of all the tk keysysm codes: <https://www.tcl.tk/man/tcl8.6/TkCmd/keysyms.htm> The two I was looking for was `<Win_L>` and `<Win_R>`.
68,005,264
I'm executing an extract query to google storage as follows: ``` job_config = bigquery.ExtractJobConfig() job_config.compression = bigquery.Compression.GZIP job_config.destination_format = (bigquery.DestinationFormat.CSV) job_config.print_header = False job_config.field_delimiter = "|" extract_job = client.extract_table( table_ref, destination_uri, job_config=job_config, location='us-east1', retry=query_retry, timeout=10) # API request extract_job.result() ``` Which returns an ExtractJob class and, by the google documentation (<https://googleapis.dev/python/bigquery/1.24.0/generated/google.cloud.bigquery.job.ExtractJob.html#google.cloud.bigquery.job.ExtractJob>), I need to call extract\_job.result() to wait the job to complete. After the completion, I notice that the files on Google Cloud Storage are not there (yet), maybe there's a delay. I need to ensure that the files are ready to consume after the extraction job, there's a API method to solve this or I have to make a workaround sleeping and waiting the files?
2021/06/16
[ "https://Stackoverflow.com/questions/68005264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3447863/" ]
First of all, Start Events must not have an incoming Edge. It is not allowed by the BPMN standard. So you should replace your Start Events 2 and 3 within the process with intermediate Events. The decission logic to skip or execute the Intermediate Event now representing the event of what was before Start Event 3 could be implemented in an Event Based Gateway, describing on the Edges which path to take under which condition. [![BPMN Model example](https://i.stack.imgur.com/2fY31.png)](https://i.stack.imgur.com/2fY31.png)
Based on Simulat's answer I found a alternative solution which I think is the better fit. The red path should not be possible because of the logic gate with the red circle (the top path is only viable if `Start Event 3` has not occurred). The problem I have with Simulat's answer are the intermediate events and the event based gate. Since there are no "real" events on those points so I think they should be xor logic gates, but I'm not sure. Feedback is welcome: [![enter image description here](https://i.stack.imgur.com/srL8p.png)](https://i.stack.imgur.com/srL8p.png)
54,272,604
I have a recursive solution that works, but it turns out a lot of subproblems are being recalculated. I need help with MEMOIZATION. So here's the problem statement: > > You are a professional robber planning to rob houses along a street. > Each house has a certain amount of money stashed, the only constraint > stopping you from robbing each of them is that adjacent houses have > security system connected and it will automatically contact the police > if two adjacent houses were broken into on the same night. > > > Given a list of non-negative integers representing the amount of money > of each house, determine the maximum amount of money you can rob > tonight without alerting the police. > > > Examples: > > Input: `[2,7,9,3,1]` Output: `12` Explanation: Rob house 1 (money = 2), > rob house 3 (money = 9) and rob house 5 (money = 1). > Total amount you can rob = `2 + 9 + 1 = 12`. > > > Another one: > > Input: `[1,2,3,1]` Output: `4` Explanation: Rob house 1 (money = 1) and > then rob house 3 (money = 3). > Total amount you can rob = `1 + 3 = 4`. > > > And another one > > Input: `[2, 1, 1, 2]` Output: `4` Explanation: Rob house 1 (money = 2) and > then rob house 4 (money = 2). > Total amount you can rob = `2 + 2 = 4`. > > > Now like I said I have a perfectly working recursive solution: When I build a recursive solution. I don't THINK too much. I just try to understand what the smaller subproblems are. `option_1`: I add the value in my current `index`, and go to `index + 2` `option_2`: I don't add the value in my current `index`, and I search starting from `index + 1` Maximum amount of money = `max(option_1, option_2)` ``` money = [1, 2, 1, 1] #Amounts that can be looted def helper(value, index): if index >= len(money): return value else: option1 = value + money[index] new_index1 = index + 2 option2 = value new_index2 = index + 1 return max(helper(option1, new_index1), helper(option2, new_index2)) helper(0, 0) #Starting of at value = 0 and index = 0 ``` This works perfectly.. and returns the correct value `3`. I then try my hand at MEMOIZING. ``` money = [1, 2, 1, 1] max_dict = {} def helper(value, index): if index in max_dict: return max_dict[index] elif index >= len(l1): return value else: option1 = value + money[index] new_index1 = index + 2 option2 = value new_index2 = index + 1 max_dict[index] = max(helper(option1, new_index1), helper(option2, new_index2)) return max_dict[index] helper(0, 0) ``` I simply have a dictionary called `max_dict` that STORES the value, and each recursive call checks if the value already exists and then accordingly grabs it and prints it out.. But I get the wrong solution for this as `2` instead of `3`. I went to `pythontutor.com` and typed my solution out, but I can't seem to get the recursion tree and where it's failing.. **Could someone give me a correct implementation of memoization while keeping the overall structure the same? In other words, I don't want the recursive function definition to change**
2019/01/20
[ "https://Stackoverflow.com/questions/54272604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7938658/" ]
The `helper` can be called with different `value` parameter for same `index`. So the `value` must be removed (subtracted from the stored `max_dict`). One way to do this is to add `value` just before returning, not earlier: ``` money = [2, 1, 1, 2] max_dict = {} def helper(value, index): if index in max_dict: return value + max_dict[index] elif index >= len(money): return value else: option1 = money[index] new_index1 = index + 2 option2 = 0 new_index2 = index + 1 max_dict[index] = max(helper(option1, new_index1), helper(option2, new_index2)) return value + max_dict[index] helper(0, 0) ``` A more detailed explanation what happens is given by @ggorlen's answer
Your approach for memoization won't work because when you reach some index `i`, if you've already computed some result for `i`, your algorithm fails to consider the fact that there might be a *better* result available by robbing a more optimal set of houses in the left portion of the array. The solution to this dilemma is to avoid passing the running `value` (money you've robbed) downward through the recursive calls from parents to children. The idea is to compute sub-problem results without *any input* from ancestor nodes, then build the larger solutions from the smaller ones on the way back up the call stack. Memoization of index `i` will then work because a given index `i` will always have a unique set of subproblems whose solutions will not be corrupted by choices from ancestors in the left portion of the array. This preserves the optimal substructure that's necessary for DP to work. Additionally, I recommend avoiding global variables in favor of passing your data directly into the function. ``` def maximize_robberies(houses, memo, i=0): if i in memo: return memo[i] elif i >= len(houses): return 0 memo[i] = max( maximize_robberies(houses, memo, i + 1), maximize_robberies(houses, memo, i + 2) + houses[i], ) return memo[i] if __name__ == "__main__": print(maximize_robberies([1, 2, 1, 1], {})) ```
54,272,604
I have a recursive solution that works, but it turns out a lot of subproblems are being recalculated. I need help with MEMOIZATION. So here's the problem statement: > > You are a professional robber planning to rob houses along a street. > Each house has a certain amount of money stashed, the only constraint > stopping you from robbing each of them is that adjacent houses have > security system connected and it will automatically contact the police > if two adjacent houses were broken into on the same night. > > > Given a list of non-negative integers representing the amount of money > of each house, determine the maximum amount of money you can rob > tonight without alerting the police. > > > Examples: > > Input: `[2,7,9,3,1]` Output: `12` Explanation: Rob house 1 (money = 2), > rob house 3 (money = 9) and rob house 5 (money = 1). > Total amount you can rob = `2 + 9 + 1 = 12`. > > > Another one: > > Input: `[1,2,3,1]` Output: `4` Explanation: Rob house 1 (money = 1) and > then rob house 3 (money = 3). > Total amount you can rob = `1 + 3 = 4`. > > > And another one > > Input: `[2, 1, 1, 2]` Output: `4` Explanation: Rob house 1 (money = 2) and > then rob house 4 (money = 2). > Total amount you can rob = `2 + 2 = 4`. > > > Now like I said I have a perfectly working recursive solution: When I build a recursive solution. I don't THINK too much. I just try to understand what the smaller subproblems are. `option_1`: I add the value in my current `index`, and go to `index + 2` `option_2`: I don't add the value in my current `index`, and I search starting from `index + 1` Maximum amount of money = `max(option_1, option_2)` ``` money = [1, 2, 1, 1] #Amounts that can be looted def helper(value, index): if index >= len(money): return value else: option1 = value + money[index] new_index1 = index + 2 option2 = value new_index2 = index + 1 return max(helper(option1, new_index1), helper(option2, new_index2)) helper(0, 0) #Starting of at value = 0 and index = 0 ``` This works perfectly.. and returns the correct value `3`. I then try my hand at MEMOIZING. ``` money = [1, 2, 1, 1] max_dict = {} def helper(value, index): if index in max_dict: return max_dict[index] elif index >= len(l1): return value else: option1 = value + money[index] new_index1 = index + 2 option2 = value new_index2 = index + 1 max_dict[index] = max(helper(option1, new_index1), helper(option2, new_index2)) return max_dict[index] helper(0, 0) ``` I simply have a dictionary called `max_dict` that STORES the value, and each recursive call checks if the value already exists and then accordingly grabs it and prints it out.. But I get the wrong solution for this as `2` instead of `3`. I went to `pythontutor.com` and typed my solution out, but I can't seem to get the recursion tree and where it's failing.. **Could someone give me a correct implementation of memoization while keeping the overall structure the same? In other words, I don't want the recursive function definition to change**
2019/01/20
[ "https://Stackoverflow.com/questions/54272604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7938658/" ]
The `helper` can be called with different `value` parameter for same `index`. So the `value` must be removed (subtracted from the stored `max_dict`). One way to do this is to add `value` just before returning, not earlier: ``` money = [2, 1, 1, 2] max_dict = {} def helper(value, index): if index in max_dict: return value + max_dict[index] elif index >= len(money): return value else: option1 = money[index] new_index1 = index + 2 option2 = 0 new_index2 = index + 1 max_dict[index] = max(helper(option1, new_index1), helper(option2, new_index2)) return value + max_dict[index] helper(0, 0) ``` A more detailed explanation what happens is given by @ggorlen's answer
I solved this dynamic programming problem using below method. And it is happenning in O(n) time. Do try this. ``` class Solution: # @param {integer[]} nums # @return {integer} def rob(self, nums): n = len(nums) if n==0: return 0; if n == 1: return nums[0] s = [0]*(n+1) s[1] = nums[0] s[2] = nums[1] for i in range(3,n+1): s[i] = (max(s[i-2],s[i-3]) + nums[i-1]) return max(s[n],s[n-1]) money = [2, 1, 1, 2] sol = Solution() print(sol.rob(money)) ```
54,272,604
I have a recursive solution that works, but it turns out a lot of subproblems are being recalculated. I need help with MEMOIZATION. So here's the problem statement: > > You are a professional robber planning to rob houses along a street. > Each house has a certain amount of money stashed, the only constraint > stopping you from robbing each of them is that adjacent houses have > security system connected and it will automatically contact the police > if two adjacent houses were broken into on the same night. > > > Given a list of non-negative integers representing the amount of money > of each house, determine the maximum amount of money you can rob > tonight without alerting the police. > > > Examples: > > Input: `[2,7,9,3,1]` Output: `12` Explanation: Rob house 1 (money = 2), > rob house 3 (money = 9) and rob house 5 (money = 1). > Total amount you can rob = `2 + 9 + 1 = 12`. > > > Another one: > > Input: `[1,2,3,1]` Output: `4` Explanation: Rob house 1 (money = 1) and > then rob house 3 (money = 3). > Total amount you can rob = `1 + 3 = 4`. > > > And another one > > Input: `[2, 1, 1, 2]` Output: `4` Explanation: Rob house 1 (money = 2) and > then rob house 4 (money = 2). > Total amount you can rob = `2 + 2 = 4`. > > > Now like I said I have a perfectly working recursive solution: When I build a recursive solution. I don't THINK too much. I just try to understand what the smaller subproblems are. `option_1`: I add the value in my current `index`, and go to `index + 2` `option_2`: I don't add the value in my current `index`, and I search starting from `index + 1` Maximum amount of money = `max(option_1, option_2)` ``` money = [1, 2, 1, 1] #Amounts that can be looted def helper(value, index): if index >= len(money): return value else: option1 = value + money[index] new_index1 = index + 2 option2 = value new_index2 = index + 1 return max(helper(option1, new_index1), helper(option2, new_index2)) helper(0, 0) #Starting of at value = 0 and index = 0 ``` This works perfectly.. and returns the correct value `3`. I then try my hand at MEMOIZING. ``` money = [1, 2, 1, 1] max_dict = {} def helper(value, index): if index in max_dict: return max_dict[index] elif index >= len(l1): return value else: option1 = value + money[index] new_index1 = index + 2 option2 = value new_index2 = index + 1 max_dict[index] = max(helper(option1, new_index1), helper(option2, new_index2)) return max_dict[index] helper(0, 0) ``` I simply have a dictionary called `max_dict` that STORES the value, and each recursive call checks if the value already exists and then accordingly grabs it and prints it out.. But I get the wrong solution for this as `2` instead of `3`. I went to `pythontutor.com` and typed my solution out, but I can't seem to get the recursion tree and where it's failing.. **Could someone give me a correct implementation of memoization while keeping the overall structure the same? In other words, I don't want the recursive function definition to change**
2019/01/20
[ "https://Stackoverflow.com/questions/54272604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7938658/" ]
Your approach for memoization won't work because when you reach some index `i`, if you've already computed some result for `i`, your algorithm fails to consider the fact that there might be a *better* result available by robbing a more optimal set of houses in the left portion of the array. The solution to this dilemma is to avoid passing the running `value` (money you've robbed) downward through the recursive calls from parents to children. The idea is to compute sub-problem results without *any input* from ancestor nodes, then build the larger solutions from the smaller ones on the way back up the call stack. Memoization of index `i` will then work because a given index `i` will always have a unique set of subproblems whose solutions will not be corrupted by choices from ancestors in the left portion of the array. This preserves the optimal substructure that's necessary for DP to work. Additionally, I recommend avoiding global variables in favor of passing your data directly into the function. ``` def maximize_robberies(houses, memo, i=0): if i in memo: return memo[i] elif i >= len(houses): return 0 memo[i] = max( maximize_robberies(houses, memo, i + 1), maximize_robberies(houses, memo, i + 2) + houses[i], ) return memo[i] if __name__ == "__main__": print(maximize_robberies([1, 2, 1, 1], {})) ```
I solved this dynamic programming problem using below method. And it is happenning in O(n) time. Do try this. ``` class Solution: # @param {integer[]} nums # @return {integer} def rob(self, nums): n = len(nums) if n==0: return 0; if n == 1: return nums[0] s = [0]*(n+1) s[1] = nums[0] s[2] = nums[1] for i in range(3,n+1): s[i] = (max(s[i-2],s[i-3]) + nums[i-1]) return max(s[n],s[n-1]) money = [2, 1, 1, 2] sol = Solution() print(sol.rob(money)) ```
150,532
Similar to [this](https://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python) question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python. I first read all ten bytes into a string. I then want to parse out the individual pieces of information. I can grab the two version number chars in the string, but then I have no idea how to take those two chars and get an integer out of them. The struct package seems to be what I want, but I can't get it to work. Here is my code so-far (I am very new to python btw...so take it easy on me): ``` def __init__(self, ten_byte_string): self.whole_string = ten_byte_string self.file_identifier = self.whole_string[:3] self.major_version = struct.pack('x', self.whole_string[3:4]) #this self.minor_version = struct.pack('x', self.whole_string[4:5]) # and this self.flags = self.whole_string[5:6] self.len = self.whole_string[6:10] ``` Printing out any value except is obviously crap because they are not formatted correctly.
2008/09/29
[ "https://Stackoverflow.com/questions/150532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
If you have a string, with 2 bytes that you wish to interpret as a 16 bit integer, you can do so by: ``` >>> s = '\0\x02' >>> struct.unpack('>H', s) (2,) ``` Note that the > is for big-endian (the largest part of the integer comes first). This is the format id3 tags use. For other sizes of integer, you use different format codes. eg. "i" for a signed 32 bit integer. See help(struct) for details. You can also unpack several elements at once. eg for 2 unsigned shorts, followed by a signed 32 bit value: ``` >>> a,b,c = struct.unpack('>HHi', some_string) ``` Going by your code, you are looking for (in order): * a 3 char string * 2 single byte values (major and minor version) * a 1 byte flags variable * a 32 bit length quantity The format string for this would be: ``` ident, major, minor, flags, len = struct.unpack('>3sBBBI', ten_byte_string) ```
I was going to recommend the `struct` package but then you said you had tried it. Try this: ``` self.major_version = struct.unpack('H', self.whole_string[3:5]) ``` The `pack()` function convers Python data types to bits, and the `unpack()` function converts bits to Python data types.
150,532
Similar to [this](https://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python) question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python. I first read all ten bytes into a string. I then want to parse out the individual pieces of information. I can grab the two version number chars in the string, but then I have no idea how to take those two chars and get an integer out of them. The struct package seems to be what I want, but I can't get it to work. Here is my code so-far (I am very new to python btw...so take it easy on me): ``` def __init__(self, ten_byte_string): self.whole_string = ten_byte_string self.file_identifier = self.whole_string[:3] self.major_version = struct.pack('x', self.whole_string[3:4]) #this self.minor_version = struct.pack('x', self.whole_string[4:5]) # and this self.flags = self.whole_string[5:6] self.len = self.whole_string[6:10] ``` Printing out any value except is obviously crap because they are not formatted correctly.
2008/09/29
[ "https://Stackoverflow.com/questions/150532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
If you have a string, with 2 bytes that you wish to interpret as a 16 bit integer, you can do so by: ``` >>> s = '\0\x02' >>> struct.unpack('>H', s) (2,) ``` Note that the > is for big-endian (the largest part of the integer comes first). This is the format id3 tags use. For other sizes of integer, you use different format codes. eg. "i" for a signed 32 bit integer. See help(struct) for details. You can also unpack several elements at once. eg for 2 unsigned shorts, followed by a signed 32 bit value: ``` >>> a,b,c = struct.unpack('>HHi', some_string) ``` Going by your code, you are looking for (in order): * a 3 char string * 2 single byte values (major and minor version) * a 1 byte flags variable * a 32 bit length quantity The format string for this would be: ``` ident, major, minor, flags, len = struct.unpack('>3sBBBI', ten_byte_string) ```
Why write your own? (Assuming you haven't checked out these other options.) There's a couple options out there for reading in ID3 tag info from MP3s in Python. Check out my [answer](https://stackoverflow.com/questions/8948/accessing-mp3-meta-data-with-python#102285) over at [this](https://stackoverflow.com/questions/8948/accessing-mp3-meta-data-with-python) question.
150,532
Similar to [this](https://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python) question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python. I first read all ten bytes into a string. I then want to parse out the individual pieces of information. I can grab the two version number chars in the string, but then I have no idea how to take those two chars and get an integer out of them. The struct package seems to be what I want, but I can't get it to work. Here is my code so-far (I am very new to python btw...so take it easy on me): ``` def __init__(self, ten_byte_string): self.whole_string = ten_byte_string self.file_identifier = self.whole_string[:3] self.major_version = struct.pack('x', self.whole_string[3:4]) #this self.minor_version = struct.pack('x', self.whole_string[4:5]) # and this self.flags = self.whole_string[5:6] self.len = self.whole_string[6:10] ``` Printing out any value except is obviously crap because they are not formatted correctly.
2008/09/29
[ "https://Stackoverflow.com/questions/150532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
If you have a string, with 2 bytes that you wish to interpret as a 16 bit integer, you can do so by: ``` >>> s = '\0\x02' >>> struct.unpack('>H', s) (2,) ``` Note that the > is for big-endian (the largest part of the integer comes first). This is the format id3 tags use. For other sizes of integer, you use different format codes. eg. "i" for a signed 32 bit integer. See help(struct) for details. You can also unpack several elements at once. eg for 2 unsigned shorts, followed by a signed 32 bit value: ``` >>> a,b,c = struct.unpack('>HHi', some_string) ``` Going by your code, you are looking for (in order): * a 3 char string * 2 single byte values (major and minor version) * a 1 byte flags variable * a 32 bit length quantity The format string for this would be: ``` ident, major, minor, flags, len = struct.unpack('>3sBBBI', ten_byte_string) ```
> > I am trying to read in an ID3v2 tag header > > > FWIW, there's [already a module](http://id3-py.sourceforge.net/) for this.
64,647,954
I want to webscrape german real estate website immobilienscout24.de. I would like to download the HTML of a given URL and then work with the HTML offline. It is not intended for commercial use or publication and I do not intend on spamming the site, it is merely for coding practice. I would like to write a python tool that automatically downloads the HTML of given immobilienscout24.de sites. I have tried to use beautifulsoup for this, however, the parsed HTML doesn't show the content but asks if I am a robot etc., meaning my webscraper got detected and blocked (I can access the site in Firefox just fine). I have set a referer, a delay and a user agent. What else can I do to avoid being detected (i.e. rotating proxies, rotating user agents, random clicks, other webscraping tools that don't get detected...)? I have tried to use my phones IP but got the same result. A GUI webscraping tool is not an option as I need to control it with python. Please give some implementable code if possible. Here is my code so far: ``` import urllib.request from bs4 import BeautifulSoup import requests import time import numpy url = "https://www.immobilienscout24.de/Suche/de/wohnung-mieten?sorting=2#" req = urllib.request.Request(url, data=None, headers={ 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36' }) req.add_header('Referer', 'https://www.google.de/search?q=immoscout24) delays = [3, 2, 4, 6, 7, 10, 11, 17] time.sleep(numpy.random.choice(delays)) # I want to implement delays like this page = urllib.request.urlopen(req) soup = BeautifulSoup(page, 'html.parser') print(soup.prettify) ``` ``` username:~/Desktop$ uname -a Linux username 5.4.0-52-generic #57-Ubuntu SMP Thu Oct 15 10:57:00 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux ``` Thank you!
2020/11/02
[ "https://Stackoverflow.com/questions/64647954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14361382/" ]
Try to set `Accept-Language` HTTP header (this worked for me to get correct response from server): ``` import requests from bs4 import BeautifulSoup url = "https://www.immobilienscout24.de/Suche/de/wohnung-mieten?sorting=2#" headers = { 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:82.0) Gecko/20100101 Firefox/82.0', 'Accept-Language': 'en-US,en;q=0.5' } soup = BeautifulSoup(requests.get(url, headers=headers).content, 'html.parser') for h5 in soup.select('h5'): print(h5.get_text(strip=True, separator=' ')) ``` Prints: ``` NEU Albertstadt: Praktisch geschnitten und großer Balkon NEU Sehr geräumige 3-Raum-Wohnung in der Eisenacher Weststadt NEU Gepflegte 3-Zimmer-Wohnung am Rosenberg in Hofheim a.Taunus NEU ERSTBEZUG: Wohnung neu renoviert NEU Freundliche 3,5-Zimmer-Wohnung mit Balkon und EBK in Rheinfelden NEU Für Singles und Studenten! 2 ZKB mit EBK und Balkon NEU Schöne 3-Zimmer-Wohnung mit 2 Balkonen im Parkend NEU Öffentlich geförderte 3-Zimmer-Neubau-Wohnung für die kleine Familie in Iserbrook! NEU Komfortable, neuwertige Erdgeschosswohnung in gefragter Lage am Wall NEU Möbliertes, freundliches Appartem. TOP LAGE, S-Balkon, EBK, ruhig, Schwabing Nord/, Milbertshofen NEU Extravagant & frisch saniert! 2,5-Zimmer DG-Wohnung in Duisburg-Neumühl NEU wunderschöne 3 Zimmer Dachgeschosswohnung mit Einbauküche. 2er WG-tauglich. NEU Erstbezug nach Sanierung: Helle 3-Zimmer-Wohnung mit Balkon in Monheim am Rhein NEU Morgen schon im neuen Zuhause mit der ganzen Familie! 3,5 Raum zur Miete in DUI-Overbruch NEU Erstbezug: ansprechende 2-Zimmer-EG-Wohnung in Bad Düben NEU CALENBERGER NEUSTADT | 3-Zimmer-Wohnung mit großem Süd-Balkon NEU Wohnen und Arbeiten in Bestlage von HH-Lokstedt ! NEU Erstbezug: Wohlfühlwohnen in modernem Dachgeschoss nach kompletter Sanierung! NEU CASACONCEPT Stilaltbau-Wohnung München-Bogenhausen nahe Prinzregentenplatz NEU schöne Wohnung mit Balkon und Laminatboden ```
Maybe have a go with [requests](https://requests.readthedocs.io/en/master/), the code below seems to work fine for me: ``` import requests from bs4 import BeautifulSoup r = requests.get('https://www.immobilienscout24.de/') soup = BeautifulSoup(r.text, 'html.parser') print(soup.prettify) ``` Another approach is to use [selenium](https://selenium-python.readthedocs.io/); it's powerful but maybe a bit more complicated. Edit: A possible solution using Selenium (it seems to work for me for the link you provided in the comment): ``` from selenium import webdriver from bs4 import BeautifulSoup driver = webdriver.Chrome('path/to/chromedriver') # it can also work with Firefox, Safari, etc driver.get('some_url') soup = BeautifulSoup(driver.page_source, 'html.parser') ``` If you haven't used selenium before, have a look [here](https://selenium-python.readthedocs.io/installation.html) first on how to get started.