qid
int64
469
74.7M
question
stringlengths
36
37.8k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
5
31.5k
response_k
stringlengths
10
31.6k
65,770,185
I try to make a python script that gets the dam occupancy rates from a website. Here is the code: ``` baraj_link = "https://www.turkiye.gov.tr/istanbul-su-ve-kanalizasyon-idaresi-baraj-doluluk-oranlari" response = requests.get(baraj_link) soup = BeautifulSoup(response.text, "lxml") values_list = [] values = soup.find_all('dl',{re.compile('compact')}) for val in values: text = val.find_next('dt').text value = val.text values_list.append((text,value)) baraj = values_list[0][1] ``` The output is like this: ``` Tarih 18/01/2021 Genel Doluluk Oranı (%) 29,48 ``` Genel Doluluk Oranı means occupancy rate. I need the value of occupancy rate which writes in next line like 29,48. How can I get this value from output?
2021/01/18
[ "https://Stackoverflow.com/questions/65770185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375618/" ]
### Solution For the descending order we multiply here by -1 each value in the array then sort the array and then multiply back with -1. Ultimately we build the result string with string concatenation and print it out ``` import java.util.Arrays; public class MyClass { public static void main(String args[]) { int[] array = {3,1,9}; for (int l = 0; l < array.length; l++){ array[l] = array[l]*-1; } Arrays.sort(array); for (int l = 0; l < array.length; l++){ array[l] = array[l]*-1; } String res = ""; for(int i = 0; i < array.length; i++){ res+=array[i]; } System.out.println(res); } } ``` ### Output ``` 931 ``` ### Alternatively Or as @Matt has mentioned in the comments you can basically concat the string in reverse order. Then there is no need anymore for the ascending to descending transformation with `*-1` ``` import java.util.Arrays; public class MyClass { public static void main(String args[]) { int[] array = { 9, 1, 3 }; String res = ""; Arrays.sort(array); for (int l = array.length - 1; l >= 0; l--) { res += array[l]; } System.out.println(res); } } ```
Hope it will work as per your requirement-> ``` public static void main(String[] args) { Integer[] arr = {1,3,3,9,60 }; List<Integer> flat = Arrays.stream(arr).sorted((a, b) -> findfirst(b) - findfirst(a)).collect(Collectors.toList()); System.out.println(flat); } private static int findfirst(Integer a) { int val = a; if(val>=10) { while (val >= 10) { val = val / 10; } } return val; } ```
65,770,185
I try to make a python script that gets the dam occupancy rates from a website. Here is the code: ``` baraj_link = "https://www.turkiye.gov.tr/istanbul-su-ve-kanalizasyon-idaresi-baraj-doluluk-oranlari" response = requests.get(baraj_link) soup = BeautifulSoup(response.text, "lxml") values_list = [] values = soup.find_all('dl',{re.compile('compact')}) for val in values: text = val.find_next('dt').text value = val.text values_list.append((text,value)) baraj = values_list[0][1] ``` The output is like this: ``` Tarih 18/01/2021 Genel Doluluk Oranı (%) 29,48 ``` Genel Doluluk Oranı means occupancy rate. I need the value of occupancy rate which writes in next line like 29,48. How can I get this value from output?
2021/01/18
[ "https://Stackoverflow.com/questions/65770185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375618/" ]
### Solution For the descending order we multiply here by -1 each value in the array then sort the array and then multiply back with -1. Ultimately we build the result string with string concatenation and print it out ``` import java.util.Arrays; public class MyClass { public static void main(String args[]) { int[] array = {3,1,9}; for (int l = 0; l < array.length; l++){ array[l] = array[l]*-1; } Arrays.sort(array); for (int l = 0; l < array.length; l++){ array[l] = array[l]*-1; } String res = ""; for(int i = 0; i < array.length; i++){ res+=array[i]; } System.out.println(res); } } ``` ### Output ``` 931 ``` ### Alternatively Or as @Matt has mentioned in the comments you can basically concat the string in reverse order. Then there is no need anymore for the ascending to descending transformation with `*-1` ``` import java.util.Arrays; public class MyClass { public static void main(String args[]) { int[] array = { 9, 1, 3 }; String res = ""; Arrays.sort(array); for (int l = array.length - 1; l >= 0; l--) { res += array[l]; } System.out.println(res); } } ```
A lot of problems become easier when using Java streams. In this case you could convert all numbers to String and then sort in an order which picks the higher String value of two pairings, then finally join each number to one long one. This works for your test data, but does NOT work for other data-sets: ``` List<Integer> list1 = List.of(1,3,9,60); Comparator<String> compare1 = Comparator.reverseOrder(); String num1 = list1.stream().map(String::valueOf).sorted(compare1).collect(Collectors.joining("")); ``` The comparator `Comparator.reverseOrder()` does not work for numbers of different length which start with same values, so a more complex compare function is needed which concatenates values to decide ordering, something like this which implies that "459" > "45" > "451" ``` List<Integer> list2 = List.of(1,45,451,449,450,9, 4, 459); Comparator<String> compare = (a,b) -> (b+a).substring(0, Math.max(a.length(), b.length())).compareTo((a+b).substring(0, Math.max(a.length(), b.length()))); String num2 = list2.stream().map(String::valueOf).sorted(compare).collect(Collectors.joining("")); ``` ... perhaps.
65,770,185
I try to make a python script that gets the dam occupancy rates from a website. Here is the code: ``` baraj_link = "https://www.turkiye.gov.tr/istanbul-su-ve-kanalizasyon-idaresi-baraj-doluluk-oranlari" response = requests.get(baraj_link) soup = BeautifulSoup(response.text, "lxml") values_list = [] values = soup.find_all('dl',{re.compile('compact')}) for val in values: text = val.find_next('dt').text value = val.text values_list.append((text,value)) baraj = values_list[0][1] ``` The output is like this: ``` Tarih 18/01/2021 Genel Doluluk Oranı (%) 29,48 ``` Genel Doluluk Oranı means occupancy rate. I need the value of occupancy rate which writes in next line like 29,48. How can I get this value from output?
2021/01/18
[ "https://Stackoverflow.com/questions/65770185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375618/" ]
### Solution For the descending order we multiply here by -1 each value in the array then sort the array and then multiply back with -1. Ultimately we build the result string with string concatenation and print it out ``` import java.util.Arrays; public class MyClass { public static void main(String args[]) { int[] array = {3,1,9}; for (int l = 0; l < array.length; l++){ array[l] = array[l]*-1; } Arrays.sort(array); for (int l = 0; l < array.length; l++){ array[l] = array[l]*-1; } String res = ""; for(int i = 0; i < array.length; i++){ res+=array[i]; } System.out.println(res); } } ``` ### Output ``` 931 ``` ### Alternatively Or as @Matt has mentioned in the comments you can basically concat the string in reverse order. Then there is no need anymore for the ascending to descending transformation with `*-1` ``` import java.util.Arrays; public class MyClass { public static void main(String args[]) { int[] array = { 9, 1, 3 }; String res = ""; Arrays.sort(array); for (int l = array.length - 1; l >= 0; l--) { res += array[l]; } System.out.println(res); } } ```
compare first number of each int then if it is the biggest put it at beginning then you continue, if first char is equal step into the second etc etc the bigest win, if it same at max-char-size. the first selected would be pushed then the second one immediatly after as you already know. In that maneer 9 > 60 cuz 960>609 the first char will always be the biggest in that case when u concat. it's > 9 < not > 09 <
65,770,185
I try to make a python script that gets the dam occupancy rates from a website. Here is the code: ``` baraj_link = "https://www.turkiye.gov.tr/istanbul-su-ve-kanalizasyon-idaresi-baraj-doluluk-oranlari" response = requests.get(baraj_link) soup = BeautifulSoup(response.text, "lxml") values_list = [] values = soup.find_all('dl',{re.compile('compact')}) for val in values: text = val.find_next('dt').text value = val.text values_list.append((text,value)) baraj = values_list[0][1] ``` The output is like this: ``` Tarih 18/01/2021 Genel Doluluk Oranı (%) 29,48 ``` Genel Doluluk Oranı means occupancy rate. I need the value of occupancy rate which writes in next line like 29,48. How can I get this value from output?
2021/01/18
[ "https://Stackoverflow.com/questions/65770185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375618/" ]
> > It is impossible to just sort the array to form the number that I wanted. > > > Actually, it isn't impossible. What you need is to design and implement an *ordering* that will result in the (decimal) numbers that will make the final number to be largest to sort first; e.g. for the numbers in your question, the ordering is: ``` 9 < 60 < 3 < 1 ``` You just need to work out exactly what the required ordering is *for all possible non-negative integers*. Once you have worked it out, code a `Comparator` class that implements the ordering. Hint: You would be able to specify the ordering using recursion ...
Hope it will work as per your requirement-> ``` public static void main(String[] args) { Integer[] arr = {1,3,3,9,60 }; List<Integer> flat = Arrays.stream(arr).sorted((a, b) -> findfirst(b) - findfirst(a)).collect(Collectors.toList()); System.out.println(flat); } private static int findfirst(Integer a) { int val = a; if(val>=10) { while (val >= 10) { val = val / 10; } } return val; } ```
65,770,185
I try to make a python script that gets the dam occupancy rates from a website. Here is the code: ``` baraj_link = "https://www.turkiye.gov.tr/istanbul-su-ve-kanalizasyon-idaresi-baraj-doluluk-oranlari" response = requests.get(baraj_link) soup = BeautifulSoup(response.text, "lxml") values_list = [] values = soup.find_all('dl',{re.compile('compact')}) for val in values: text = val.find_next('dt').text value = val.text values_list.append((text,value)) baraj = values_list[0][1] ``` The output is like this: ``` Tarih 18/01/2021 Genel Doluluk Oranı (%) 29,48 ``` Genel Doluluk Oranı means occupancy rate. I need the value of occupancy rate which writes in next line like 29,48. How can I get this value from output?
2021/01/18
[ "https://Stackoverflow.com/questions/65770185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375618/" ]
> > It is impossible to just sort the array to form the number that I wanted. > > > Actually, it isn't impossible. What you need is to design and implement an *ordering* that will result in the (decimal) numbers that will make the final number to be largest to sort first; e.g. for the numbers in your question, the ordering is: ``` 9 < 60 < 3 < 1 ``` You just need to work out exactly what the required ordering is *for all possible non-negative integers*. Once you have worked it out, code a `Comparator` class that implements the ordering. Hint: You would be able to specify the ordering using recursion ...
A lot of problems become easier when using Java streams. In this case you could convert all numbers to String and then sort in an order which picks the higher String value of two pairings, then finally join each number to one long one. This works for your test data, but does NOT work for other data-sets: ``` List<Integer> list1 = List.of(1,3,9,60); Comparator<String> compare1 = Comparator.reverseOrder(); String num1 = list1.stream().map(String::valueOf).sorted(compare1).collect(Collectors.joining("")); ``` The comparator `Comparator.reverseOrder()` does not work for numbers of different length which start with same values, so a more complex compare function is needed which concatenates values to decide ordering, something like this which implies that "459" > "45" > "451" ``` List<Integer> list2 = List.of(1,45,451,449,450,9, 4, 459); Comparator<String> compare = (a,b) -> (b+a).substring(0, Math.max(a.length(), b.length())).compareTo((a+b).substring(0, Math.max(a.length(), b.length()))); String num2 = list2.stream().map(String::valueOf).sorted(compare).collect(Collectors.joining("")); ``` ... perhaps.
65,770,185
I try to make a python script that gets the dam occupancy rates from a website. Here is the code: ``` baraj_link = "https://www.turkiye.gov.tr/istanbul-su-ve-kanalizasyon-idaresi-baraj-doluluk-oranlari" response = requests.get(baraj_link) soup = BeautifulSoup(response.text, "lxml") values_list = [] values = soup.find_all('dl',{re.compile('compact')}) for val in values: text = val.find_next('dt').text value = val.text values_list.append((text,value)) baraj = values_list[0][1] ``` The output is like this: ``` Tarih 18/01/2021 Genel Doluluk Oranı (%) 29,48 ``` Genel Doluluk Oranı means occupancy rate. I need the value of occupancy rate which writes in next line like 29,48. How can I get this value from output?
2021/01/18
[ "https://Stackoverflow.com/questions/65770185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375618/" ]
> > It is impossible to just sort the array to form the number that I wanted. > > > Actually, it isn't impossible. What you need is to design and implement an *ordering* that will result in the (decimal) numbers that will make the final number to be largest to sort first; e.g. for the numbers in your question, the ordering is: ``` 9 < 60 < 3 < 1 ``` You just need to work out exactly what the required ordering is *for all possible non-negative integers*. Once you have worked it out, code a `Comparator` class that implements the ordering. Hint: You would be able to specify the ordering using recursion ...
compare first number of each int then if it is the biggest put it at beginning then you continue, if first char is equal step into the second etc etc the bigest win, if it same at max-char-size. the first selected would be pushed then the second one immediatly after as you already know. In that maneer 9 > 60 cuz 960>609 the first char will always be the biggest in that case when u concat. it's > 9 < not > 09 <
30,207,041
Been using the safe and easy confines of PyCharm for a bit now, but I'm trying to get more familiar with using a text editor and the terminal together, so I've forced myself to start using iPython Notebook and Emacs. Aaaaand I have some really dumb questions. * after firing up ipython notebook from terminal with the command 'ipython notebook', it pops up on my browser and lets me code. but can i not use terminal while it's connected to ipython notebook server? * after writing my code in ipython notebook, i'm left with a something.ipynb file. How do I run this file from terminal? If it was a .py file, i know i could execute it by tying python something.py from the command line; but it doesn't work if i type python something.ipynb in the command line. And of course, I assume I hit Control-C to quit out of the running server in terminal first? or do I run the command without quitting that? Or am i doomed to test it in iPython and then copy and paste it to a different txt editor like Emacs and save it in a .py file to run it? * what good is the .ipynb file if i can't run it in terminal or outside the iPython Notebook browser? Could I get my code in a .py from iPython Notebook if I wanted to? (i assume I'll be able to easily run it in terminal by tying something.py then) thanks in advance. I'm still very much trying to figure out how to use this thing and there aren't many answers out there for questions this elementary.
2015/05/13
[ "https://Stackoverflow.com/questions/30207041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4698759/" ]
* Yes, you can not use the same terminal. Solutions: open another terminal or run `ipython notebook` inside [`screen`](http://www.gnu.org/software/screen/manual/screen.html). If you use Windows you might want to take a look into [this question](https://stackoverflow.com/questions/5473384/terminal-multiplexer-for-microsoft-windows-installers-for-gnu-screen-or-tmux) * Notebook documents (`ipynb` files) can be converted to a range of static formats including LaTeX, HTML, PDF and Python. Read more about converting notebooks in [manual](http://ipython.org/ipython-doc/stable/notebook/nbconvert.html#nbconvert) * Notebooks are great, because you can show other people your interactive sessions accompanied with text, which may have rich formatting. And if someone can run notebook server he can easily reproduce your computations and maybe modify them. Check out [awesome notebook](http://nbviewer.ipython.org/url/norvig.com/ipython/TSPv3.ipynb) on traveling salesperson problem by Peter Norvig as an example of what you can do with `ipynb`. Or [this notebook](https://dato.com/learn/gallery/notebooks/graph_analytics_movies.html). More examples are available [here](https://github.com/ipython/ipython/wiki/A-gallery-of-interesting-IPython-Notebooks)
* You can run your IPython notebook process in background. On Unix platforms you can perform that with (note the leading `&`): ``` ipython notebook & ``` Or after a "normal" run, hit `[Control+z]` and run the `bg` command ([some lecture](http://web.mit.edu/gnu/doc/html/features_5.html)). * you can convert `.ipynb` file into `.py` file using `nbconvert` with Ipython notebook 2.x ([some lecture](http://ipython.org/ipython-doc/2/notebook/nbconvert.html)): ``` ipython nbconvert --to python mynotebook.ipynb ``` with Ipython notebook 3.x ([some lecture](http://ipython.org/ipython-doc/3/notebook/nbconvert.html)): ``` ipython nbconvert --to script mynotebook.ipynb ``` * `.ipynb` contains your script **AND results AND formatted text**. You can compare it to a [literate script](http://en.wikipedia.org/wiki/Literate_programming) (but using "machine programming language").
44,813,375
I am interested in the truth value of Python sets like `{'a', 'b'}`, or the empty set `set()` (which is not the same as the empty dictionary `{}`). In particular, I would like to know whether `bool(my_set)` is `False` if and only if the set `my_set` is empty. Ignoring primitive (such as numerals) as well as user-defined types, <https://docs.python.org/3/library/stdtypes.html#truth> says: > > The following values are considered false: > > > * [...] > * any empty sequence, for example, `''`, `()`, `[]`. > * any empty mapping, for example, `{}`. > * [...] > > > All other values are considered true > > > According to <https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range>, a set is not a sequence (it is unordered, its elements do not have indices, etc.): > > There are three basic sequence types: lists, tuples, and range objects. > > > And, according to <https://docs.python.org/3/library/stdtypes.html#mapping-types-dict>, > > There is currently only one standard mapping type, the *dictionary*. > > > So, as far as I understand, the set type is not a type that can ever be `False`. However, when I try, `bool(set())` evaluates to `False`. Questions: * Is this a documentation problem, or am I getting something wrong? * Is the empty set the only set whose truth value is `False`?
2017/06/28
[ "https://Stackoverflow.com/questions/44813375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6867099/" ]
After looking at the source code for CPython, I would guess this is a documentation error, however, it could be implementation dependent and therefore would be a good issue to raise on the Python bug tracker. Specifically, [object.c](https://github.com/python/cpython/blob/a66f9c6bb134561a24374f10e8c35417d356ce14/Objects/object.c#L1313) defines the truth value of an item as follows: ``` int PyObject_IsTrue(PyObject *v) { Py_ssize_t res; if (v == Py_True) return 1; if (v == Py_False) return 0; if (v == Py_None) return 0; else if (v->ob_type->tp_as_number != NULL && v->ob_type->tp_as_number->nb_bool != NULL) res = (*v->ob_type->tp_as_number->nb_bool)(v); else if (v->ob_type->tp_as_mapping != NULL && v->ob_type->tp_as_mapping->mp_length != NULL) res = (*v->ob_type->tp_as_mapping->mp_length)(v); else if (v->ob_type->tp_as_sequence != NULL && v->ob_type->tp_as_sequence->sq_length != NULL) res = (*v->ob_type->tp_as_sequence->sq_length)(v); else return 1; /* if it is negative, it should be either -1 or -2 */ return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int); } ``` We can clearly see that the value is value would be always true if it is not a boolean type, None, a sequence, or a mapping type, which would require tp\_as\_sequence or tp\_as\_mapping to be set. Fortunately, looking at [setobject.c](https://github.com/python/cpython/blob/master/Objects/setobject.c#L2127) shows that sets do implement tp\_as\_sequence, suggesting the documentation seems to be incorrect. ``` PyTypeObject PySet_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "set", /* tp_name */ sizeof(PySetObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)set_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)set_repr, /* tp_repr */ &set_as_number, /* tp_as_number */ &set_as_sequence, /* tp_as_sequence */ 0, /* tp_as_mapping */ /* ellipsed lines */ }; ``` [Dicts](https://github.com/python/cpython/blob/master/Objects/dictobject.c#L3254) also implement tp\_as\_sequence, so it seems that although it is not a sequence type, it sequence-like, enough to be truthy. In my opionion, the documentation should clarify this: mapping-like types, or sequence-like types will be truthy dependent on their length. **Edit** As user2357112 correctly points out, `tp_as_sequence` and `tp_as_mapping` do not mean the type is a sequence or a map. For example, dict implements `tp_as_sequence`, and list implements `tp_as_mapping`.
That part of the docs is poorly written, or rather, poorly maintained. The following clause: > > instances of user-defined classes, if the class defines a `__bool__()` or `__len__()` method, when that method returns the integer zero or bool value False. > > > really applies to *all* classes, user-defined or not, including `set`, `dict`, and even the types listed in all the other clauses (all of which define either `__bool__` or `__len__`). (In Python 2, `None` is false despite not having a `__len__` or Python 2's equivalent of `__bool__`, but that exception is [gone since Python 3.3](http://bugs.python.org/issue12647).) I say poorly maintained because this section has been almost unchanged since at least [Python 1.4](https://docs.python.org/release/1.4/lib/node5.html#SECTION00311000000000000000), and maybe earlier. It's been updated for the addition of `False` and the removal of separate int/long types, but not for type/class unification or the introduction of sets. Back when the quoted clause was written, user-defined classes and built-in types really did behave differently, and I don't think built-in types actually had `__bool__` or `__len__` at the time.
44,813,375
I am interested in the truth value of Python sets like `{'a', 'b'}`, or the empty set `set()` (which is not the same as the empty dictionary `{}`). In particular, I would like to know whether `bool(my_set)` is `False` if and only if the set `my_set` is empty. Ignoring primitive (such as numerals) as well as user-defined types, <https://docs.python.org/3/library/stdtypes.html#truth> says: > > The following values are considered false: > > > * [...] > * any empty sequence, for example, `''`, `()`, `[]`. > * any empty mapping, for example, `{}`. > * [...] > > > All other values are considered true > > > According to <https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range>, a set is not a sequence (it is unordered, its elements do not have indices, etc.): > > There are three basic sequence types: lists, tuples, and range objects. > > > And, according to <https://docs.python.org/3/library/stdtypes.html#mapping-types-dict>, > > There is currently only one standard mapping type, the *dictionary*. > > > So, as far as I understand, the set type is not a type that can ever be `False`. However, when I try, `bool(set())` evaluates to `False`. Questions: * Is this a documentation problem, or am I getting something wrong? * Is the empty set the only set whose truth value is `False`?
2017/06/28
[ "https://Stackoverflow.com/questions/44813375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6867099/" ]
After looking at the source code for CPython, I would guess this is a documentation error, however, it could be implementation dependent and therefore would be a good issue to raise on the Python bug tracker. Specifically, [object.c](https://github.com/python/cpython/blob/a66f9c6bb134561a24374f10e8c35417d356ce14/Objects/object.c#L1313) defines the truth value of an item as follows: ``` int PyObject_IsTrue(PyObject *v) { Py_ssize_t res; if (v == Py_True) return 1; if (v == Py_False) return 0; if (v == Py_None) return 0; else if (v->ob_type->tp_as_number != NULL && v->ob_type->tp_as_number->nb_bool != NULL) res = (*v->ob_type->tp_as_number->nb_bool)(v); else if (v->ob_type->tp_as_mapping != NULL && v->ob_type->tp_as_mapping->mp_length != NULL) res = (*v->ob_type->tp_as_mapping->mp_length)(v); else if (v->ob_type->tp_as_sequence != NULL && v->ob_type->tp_as_sequence->sq_length != NULL) res = (*v->ob_type->tp_as_sequence->sq_length)(v); else return 1; /* if it is negative, it should be either -1 or -2 */ return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int); } ``` We can clearly see that the value is value would be always true if it is not a boolean type, None, a sequence, or a mapping type, which would require tp\_as\_sequence or tp\_as\_mapping to be set. Fortunately, looking at [setobject.c](https://github.com/python/cpython/blob/master/Objects/setobject.c#L2127) shows that sets do implement tp\_as\_sequence, suggesting the documentation seems to be incorrect. ``` PyTypeObject PySet_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "set", /* tp_name */ sizeof(PySetObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)set_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)set_repr, /* tp_repr */ &set_as_number, /* tp_as_number */ &set_as_sequence, /* tp_as_sequence */ 0, /* tp_as_mapping */ /* ellipsed lines */ }; ``` [Dicts](https://github.com/python/cpython/blob/master/Objects/dictobject.c#L3254) also implement tp\_as\_sequence, so it seems that although it is not a sequence type, it sequence-like, enough to be truthy. In my opionion, the documentation should clarify this: mapping-like types, or sequence-like types will be truthy dependent on their length. **Edit** As user2357112 correctly points out, `tp_as_sequence` and `tp_as_mapping` do not mean the type is a sequence or a map. For example, dict implements `tp_as_sequence`, and list implements `tp_as_mapping`.
The documentation for [`__bool__`](https://docs.python.org/3/reference/datamodel.html#object.__bool__) states that this method is called for truth value testing and if it is not defined then [`__len__`](https://docs.python.org/3/reference/datamodel.html#object.__len__) is evaluated: > > Called to implement truth value testing and the built-in operation bool(); [...] When this method is not defined, `__len__()` is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither `__len__()` nor `__bool__()`, all its instances are considered true. > > > This holds for any Python object. As we can see `set` does not define a method `__bool__`: ``` >>> set.__bool__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: type object 'set' has no attribute '__bool__' ``` so the truth testing falls back on `__len__`: ``` >>> set.__len__ <slot wrapper '__len__' of 'set' objects> ``` Therefore only an empty set (zero-length) is considered false. The part for [truth value testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing) in the documentation is not complete with regard to this aspect.
44,813,375
I am interested in the truth value of Python sets like `{'a', 'b'}`, or the empty set `set()` (which is not the same as the empty dictionary `{}`). In particular, I would like to know whether `bool(my_set)` is `False` if and only if the set `my_set` is empty. Ignoring primitive (such as numerals) as well as user-defined types, <https://docs.python.org/3/library/stdtypes.html#truth> says: > > The following values are considered false: > > > * [...] > * any empty sequence, for example, `''`, `()`, `[]`. > * any empty mapping, for example, `{}`. > * [...] > > > All other values are considered true > > > According to <https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range>, a set is not a sequence (it is unordered, its elements do not have indices, etc.): > > There are three basic sequence types: lists, tuples, and range objects. > > > And, according to <https://docs.python.org/3/library/stdtypes.html#mapping-types-dict>, > > There is currently only one standard mapping type, the *dictionary*. > > > So, as far as I understand, the set type is not a type that can ever be `False`. However, when I try, `bool(set())` evaluates to `False`. Questions: * Is this a documentation problem, or am I getting something wrong? * Is the empty set the only set whose truth value is `False`?
2017/06/28
[ "https://Stackoverflow.com/questions/44813375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6867099/" ]
The documentation for [`__bool__`](https://docs.python.org/3/reference/datamodel.html#object.__bool__) states that this method is called for truth value testing and if it is not defined then [`__len__`](https://docs.python.org/3/reference/datamodel.html#object.__len__) is evaluated: > > Called to implement truth value testing and the built-in operation bool(); [...] When this method is not defined, `__len__()` is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither `__len__()` nor `__bool__()`, all its instances are considered true. > > > This holds for any Python object. As we can see `set` does not define a method `__bool__`: ``` >>> set.__bool__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: type object 'set' has no attribute '__bool__' ``` so the truth testing falls back on `__len__`: ``` >>> set.__len__ <slot wrapper '__len__' of 'set' objects> ``` Therefore only an empty set (zero-length) is considered false. The part for [truth value testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing) in the documentation is not complete with regard to this aspect.
That part of the docs is poorly written, or rather, poorly maintained. The following clause: > > instances of user-defined classes, if the class defines a `__bool__()` or `__len__()` method, when that method returns the integer zero or bool value False. > > > really applies to *all* classes, user-defined or not, including `set`, `dict`, and even the types listed in all the other clauses (all of which define either `__bool__` or `__len__`). (In Python 2, `None` is false despite not having a `__len__` or Python 2's equivalent of `__bool__`, but that exception is [gone since Python 3.3](http://bugs.python.org/issue12647).) I say poorly maintained because this section has been almost unchanged since at least [Python 1.4](https://docs.python.org/release/1.4/lib/node5.html#SECTION00311000000000000000), and maybe earlier. It's been updated for the addition of `False` and the removal of separate int/long types, but not for type/class unification or the introduction of sets. Back when the quoted clause was written, user-defined classes and built-in types really did behave differently, and I don't think built-in types actually had `__bool__` or `__len__` at the time.
59,063,829
I tried to get a vector dot product in a nested list For example : ``` A = np.array([[1,2,1,3],[2,1,2,3],[3,1,2,4]]) ``` And I tried to get: ``` B = [[15], [19, 23]] ``` Where 15 = np.dot(A[0],A[1]), 19 = np.dot(A[0],A[2]), 23 = np.dot(A[1],A[2]) The fist inner\_list in B is the dot product of A[0] and A[1], The second inner\_list in B is dot product of A[0] and A[2], dot product of A[1] and A[2] I tried to write some loop in python but failed How to get B in Python?
2019/11/27
[ "https://Stackoverflow.com/questions/59063829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10595338/" ]
Here is a explicit for loop coupled with list comprehension solution: ``` In [1]: import numpy as np In [2]: A = np.array([[1,2,1,3],[2,1,2,3],[3,1,2,4]]) In [5]: def get_dp(A): ...: out = [] ...: for i, a in enumerate(A[1:]): ...: out.append([np.dot(a, b) for b in A[:i+1]]) ...: return out In [6]: get_dp(A) Out[6]: [[15], [19, 23]] ``` Explanation: The for loop is running from 2nd elements and the list comprehension is running from the beginning to the current iterated element.
An iterator class that spits out elements same as B. If you want the full list, you can `list(iter_dotprod(A))` example: ```py class iter_dotprod: def __init__(self, nested_arr): self.nested_arr = nested_arr self.hist = [] def __iter__(self): self.n = 0 return self def __next__(self): if self.n > len(self.nested_arr) -2: raise StopIteration res = np.dot(self.nested_arr[self.n], self.nested_arr[self.n+1]) self.hist.append(res) self.n += 1 return self.hist A = np.array([[1,2,1,3],[2,1,2,3],[3,1,2,4]]) tt = iter_dotprod(A) for b in iter_dotprod(A): print(b) ```
64,799,010
I am trying to get all ec2 instances details in a csv file, followed another post "https://stackoverflow.com/questions/62815990/export-aws-ec2-details-to-xlsx-csv-using-boto3-and-python". But was having attribute error for Instances. So I am trying this: ``` import boto3 import datetime import csv ec2 = boto3.resource('ec2') for i in ec2.instances.all(): Id = i.id State = i.state['Name'] Launched = i.launch_time InstanceType = i.instance_type Platform = i.platform if i.tags: for idx, tag in enumerate(i.tags, start=1): if tag['Key'] == 'Name': Instancename = tag['Value'] output = Instancename + ',' + Id + ',' + State + ',' + str(Platform) + ',' + InstanceType + ',' + str(Launched) with open('ec2_list.csv', 'w', newline='') as csvfile: header = ['Instancename', 'Id', 'State', 'Platform', 'InstanceType', 'Launched'] writer = csv.DictWriter(csvfile, fieldnames=header) writer.writeheader() writer.writerow(output) ``` For above I am having below error: ``` traceback (most recent call last): File "list_instances_2.py", line 23, in <module> writer.writerow(output) File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py", line 155, in writerow return self.writer.writerow(self._dict_to_list(rowdict)) File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py", line 148, in _dict_to_list wrong_fields = rowdict.keys() - self.fieldnames AttributeError: 'str' object has no attribute 'keys' ``` I can see that this is not creating a dict output. Need suggestions on how can I create a dictionary of 'output' and publish that in a .csv file.
2020/11/12
[ "https://Stackoverflow.com/questions/64799010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14614887/" ]
Since you are using `DictWriter`, your `output` should be: ``` output = { 'Instancename': Instancename, 'Id': Id, 'State': State, 'Platform': str(Platform), 'InstanceType': InstanceType , 'Launched': str(Launched) } ``` Your function will also just keep **overwriting** your `ec2_list.csv` in each iteration, so you should probably re-factor it anyway.
A [`DictWriter`](https://docs.python.org/3/library/csv.html#csv.DictWriter) - as the name would suggest - writes `dicts` i.e. dictionaries to a CSV file. The dictionary must have the keys that correspond to the column names. See the example in the docs I linked. In the code you posted, you are passing `output` - a string - to the `writerow` function. Which will not work because, a string is not a `dict`. You'll have to convert your `output` to something that `writerow` can accept, like a `dict`: ``` output = {'Instancename': Instancename, 'Id': Id ... } ``` And then try that.
72,842,182
I am using flask with this code: ```py from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True, port=8000) ``` ```html <form method="GET"> <p>Phone number:</p> <input name="phone_number" type="number"> <br><br> <input type="submit"> </form> ``` I want to be able to use the inputted phone number text as a variable in my python code when it is submitted. How do I do that?
2022/07/02
[ "https://Stackoverflow.com/questions/72842182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19409503/" ]
In most cases, if you are using `react-hook-form`, you don't need to track form fields with `useState` hook. Using a `Controller` component is the right way to go. But there is a problem with `onChange` handler in your 1st method. When you submit form, you are getting default date `null` because `field` is destructed, but it's not passed to `DatePicker`. So, `onChange` prop of `field` is not triggered when date is changed and `react-hook-form` doesn't have new date. Here's how your render method should be ``` render={({field}) => <LocalizationProvider dateAdapter={AdapterDateFns}> <DatePicker label="Original Release Date" renderInput={(params) => <TextField {...params} />} {...field} /> </LocalizationProvider> } ``` If for some reason, you need to update component state then you have to send data to `react-hook-form` and then update local state ``` render={({field: {onChange,...restField}) => <LocalizationProvider dateAdapter={AdapterDateFns}> <DatePicker label="Original Release Date" onChange={(event) => { onChange(event); setOriginalReleaseDate(event.target.value); }} renderInput={(params) => <TextField {...params} />} {...restField} /> </LocalizationProvider> } ```
I couldn't replicate your setup, but my guess is that in the first render the reference to the 'setOriginalReleaseDate' is lost when being passed through the Controller's render arrow function. ``` ... onChange={(newValue) => { setOriginalReleaseDate(newValue); }} ... ``` so, try putting the logic in a defined function like: ``` const handleOriginalReleaseDateChange = (newValue) => { setOriginalReleaseDate(newValue); }; ``` and change the onChange to call the function. ``` ... onChange={handleOriginalReleaseDateChange} ... ```
72,842,182
I am using flask with this code: ```py from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True, port=8000) ``` ```html <form method="GET"> <p>Phone number:</p> <input name="phone_number" type="number"> <br><br> <input type="submit"> </form> ``` I want to be able to use the inputted phone number text as a variable in my python code when it is submitted. How do I do that?
2022/07/02
[ "https://Stackoverflow.com/questions/72842182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19409503/" ]
Just modified the above answer with a bracket. ```js const [reqDate, setreqDate] = useState(new Date()); <Controller name="reqDate" defaultValue={reqDate} control={control} render={ ({ field: { onChange, ...restField } }) => <LocalizationProvider dateAdapter={AdapterDateFns}> <DatePicker label="Request Date" onChange={(event) => { onChange(event); setreqDate(event); }} renderInput={(params) => <TextField {...params} />} {...restField} /> </LocalizationProvider> } /> ``` ```html ```
I couldn't replicate your setup, but my guess is that in the first render the reference to the 'setOriginalReleaseDate' is lost when being passed through the Controller's render arrow function. ``` ... onChange={(newValue) => { setOriginalReleaseDate(newValue); }} ... ``` so, try putting the logic in a defined function like: ``` const handleOriginalReleaseDateChange = (newValue) => { setOriginalReleaseDate(newValue); }; ``` and change the onChange to call the function. ``` ... onChange={handleOriginalReleaseDateChange} ... ```
72,842,182
I am using flask with this code: ```py from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True, port=8000) ``` ```html <form method="GET"> <p>Phone number:</p> <input name="phone_number" type="number"> <br><br> <input type="submit"> </form> ``` I want to be able to use the inputted phone number text as a variable in my python code when it is submitted. How do I do that?
2022/07/02
[ "https://Stackoverflow.com/questions/72842182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19409503/" ]
``` InputDate.propTypes = { name: PropTypes.string, label: PropTypes.string, }; export default function InputDate({ name, label }) { const { control } = useFormContext(); return ( <Controller name={name} control={control} render={({ field: { onChange, value }, fieldState: { error } }) => ( <LocalizationProvider dateAdapter={AdapterMoment} > <DesktopDatePicker label={label} control={control} inputFormat="DD-MM-YYYY" value={value} onChange={(event) => { onChange(event); }} renderInput={(params) => <TextField {...params} error={!!error} helperText={error?.message} />} /> </LocalizationProvider> )} /> ) } ```
I couldn't replicate your setup, but my guess is that in the first render the reference to the 'setOriginalReleaseDate' is lost when being passed through the Controller's render arrow function. ``` ... onChange={(newValue) => { setOriginalReleaseDate(newValue); }} ... ``` so, try putting the logic in a defined function like: ``` const handleOriginalReleaseDateChange = (newValue) => { setOriginalReleaseDate(newValue); }; ``` and change the onChange to call the function. ``` ... onChange={handleOriginalReleaseDateChange} ... ```
72,842,182
I am using flask with this code: ```py from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True, port=8000) ``` ```html <form method="GET"> <p>Phone number:</p> <input name="phone_number" type="number"> <br><br> <input type="submit"> </form> ``` I want to be able to use the inputted phone number text as a variable in my python code when it is submitted. How do I do that?
2022/07/02
[ "https://Stackoverflow.com/questions/72842182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19409503/" ]
Just modified the above answer with a bracket. ```js const [reqDate, setreqDate] = useState(new Date()); <Controller name="reqDate" defaultValue={reqDate} control={control} render={ ({ field: { onChange, ...restField } }) => <LocalizationProvider dateAdapter={AdapterDateFns}> <DatePicker label="Request Date" onChange={(event) => { onChange(event); setreqDate(event); }} renderInput={(params) => <TextField {...params} />} {...restField} /> </LocalizationProvider> } /> ``` ```html ```
In most cases, if you are using `react-hook-form`, you don't need to track form fields with `useState` hook. Using a `Controller` component is the right way to go. But there is a problem with `onChange` handler in your 1st method. When you submit form, you are getting default date `null` because `field` is destructed, but it's not passed to `DatePicker`. So, `onChange` prop of `field` is not triggered when date is changed and `react-hook-form` doesn't have new date. Here's how your render method should be ``` render={({field}) => <LocalizationProvider dateAdapter={AdapterDateFns}> <DatePicker label="Original Release Date" renderInput={(params) => <TextField {...params} />} {...field} /> </LocalizationProvider> } ``` If for some reason, you need to update component state then you have to send data to `react-hook-form` and then update local state ``` render={({field: {onChange,...restField}) => <LocalizationProvider dateAdapter={AdapterDateFns}> <DatePicker label="Original Release Date" onChange={(event) => { onChange(event); setOriginalReleaseDate(event.target.value); }} renderInput={(params) => <TextField {...params} />} {...restField} /> </LocalizationProvider> } ```
72,842,182
I am using flask with this code: ```py from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True, port=8000) ``` ```html <form method="GET"> <p>Phone number:</p> <input name="phone_number" type="number"> <br><br> <input type="submit"> </form> ``` I want to be able to use the inputted phone number text as a variable in my python code when it is submitted. How do I do that?
2022/07/02
[ "https://Stackoverflow.com/questions/72842182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19409503/" ]
Just modified the above answer with a bracket. ```js const [reqDate, setreqDate] = useState(new Date()); <Controller name="reqDate" defaultValue={reqDate} control={control} render={ ({ field: { onChange, ...restField } }) => <LocalizationProvider dateAdapter={AdapterDateFns}> <DatePicker label="Request Date" onChange={(event) => { onChange(event); setreqDate(event); }} renderInput={(params) => <TextField {...params} />} {...restField} /> </LocalizationProvider> } /> ``` ```html ```
``` InputDate.propTypes = { name: PropTypes.string, label: PropTypes.string, }; export default function InputDate({ name, label }) { const { control } = useFormContext(); return ( <Controller name={name} control={control} render={({ field: { onChange, value }, fieldState: { error } }) => ( <LocalizationProvider dateAdapter={AdapterMoment} > <DesktopDatePicker label={label} control={control} inputFormat="DD-MM-YYYY" value={value} onChange={(event) => { onChange(event); }} renderInput={(params) => <TextField {...params} error={!!error} helperText={error?.message} />} /> </LocalizationProvider> )} /> ) } ```
48,399,812
I have a python script that has to be executed with start and end dates. I want to execute this file for each day in the year 2012, so I thought a while-loop inside a bash script would do the job but my bash-skills are not sufficient. This is what I tried: ``` day_start = 2012-01-01 while [ "$day_start" != 2013-01-01 ] ; do day_end =$(date -I -d "$day_start + 1 day") python script.py --since ="$day_start" --until = "$day_end" ; day_start =$(date -I -d "$day_start + 1 day") echo $day_start done ``` The error message I get is that python does not seem to like the "$bash-variable" input. Also, I thought this was the way to +1 for days inside bash, but I get an error for day\_end and day\_start as well. Can somebody help me out here? (Sorry if this is probably pretty basic!)
2018/01/23
[ "https://Stackoverflow.com/questions/48399812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7436993/" ]
Answer is simply stupid... Just restart your OS X. I don't know why, it looks like that operation system needs to rebuild some data after doing scenario from this question
Found submitted issue and solved it using the steps given here <https://github.com/desktop/desktop/issues/3625> * Open Keychain Access.app * Right click on login * Click locking * Click unlocking
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This will return i if i < x, otherwise it will return x. I like this because it is much more compact in many cases than the longer syntax which follows. ``` if (i < x) return i else return x ``` Is it possible to use this syntax in python and if so, how?
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
`a if b else c` syntax was introduced in Python 2.5. Most people have already upgraded to the recent version but in legacy code you may find another approach: ``` some_var = a<b and a or c ``` If you ever will be using this syntax remember that `a` must not evaluate to False.
Try this in Python: ``` return i if i < x else x ``` It's exactly the equivalent of the following expression in Java, C, C++ C# ``` return i < x ? i : x; ``` Read more about Python's [conditional expressions](http://docs.python.org/reference/expressions.html#conditional-expressions).
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This will return i if i < x, otherwise it will return x. I like this because it is much more compact in many cases than the longer syntax which follows. ``` if (i < x) return i else return x ``` Is it possible to use this syntax in python and if so, how?
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
You can use `(x if cond else y)`, e.g. ``` >>> x = 0 >>> y = 1 >>> print("a" if x < y else "b") a ``` That will work will [lambda function](http://www.python.org/dev/peps/pep-0308/) too.
`a if b else c` syntax was introduced in Python 2.5. Most people have already upgraded to the recent version but in legacy code you may find another approach: ``` some_var = a<b and a or c ``` If you ever will be using this syntax remember that `a` must not evaluate to False.
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This will return i if i < x, otherwise it will return x. I like this because it is much more compact in many cases than the longer syntax which follows. ``` if (i < x) return i else return x ``` Is it possible to use this syntax in python and if so, how?
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
`a if b else c` syntax was introduced in Python 2.5. Most people have already upgraded to the recent version but in legacy code you may find another approach: ``` some_var = a<b and a or c ``` If you ever will be using this syntax remember that `a` must not evaluate to False.
Ternary operator in python. > > a if b else c > > > ``` >>> a=1 >>> b=2 >>> a if a<b else b 1 >>> a if a>b else b 2 ```
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This will return i if i < x, otherwise it will return x. I like this because it is much more compact in many cases than the longer syntax which follows. ``` if (i < x) return i else return x ``` Is it possible to use this syntax in python and if so, how?
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
You can use `(x if cond else y)`, e.g. ``` >>> x = 0 >>> y = 1 >>> print("a" if x < y else "b") a ``` That will work will [lambda function](http://www.python.org/dev/peps/pep-0308/) too.
As the other answers state, Python's version for this is: `i if i < x else x` (of course for this particular example, one would prefer writing `min(i, x)` , as it is easier on the eyes) However, this expression syntax was just made available on Python 2.5 (I think it was around 2004). before that, the following idiom was used - but care should be taken, as it is error prone: `i < x and i or x` - because the logical operator "and" actually evaluates to the last true value on its chain - therefore, if the expression was true, `i < x and i` evaluates to `i` - and the `or` operator evaluates to first true value on the chain. On this case, if `i < x` would be false, so would `i< x and i` and the first true value would be `x`. It is easy to see how error prone this construct was, since if the boolean value of `i` would be false ( for example if i==0), than it would return x, even if `i < x` where true. I myself, back in those days, used to write this construct instead: (x, i)[i < x] The expression "i < x" ha a numerical value of "1" (true) or "0" (false) and I used this proeprty to have it work as an index to the previous tuple. The problem with this approach was that it would always evaluate both expressions on the tuple, even though it would use ony one of then (if the expressions where function calls this could get expensive, or even conflicting)
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This will return i if i < x, otherwise it will return x. I like this because it is much more compact in many cases than the longer syntax which follows. ``` if (i < x) return i else return x ``` Is it possible to use this syntax in python and if so, how?
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
You can use `(x if cond else y)`, e.g. ``` >>> x = 0 >>> y = 1 >>> print("a" if x < y else "b") a ``` That will work will [lambda function](http://www.python.org/dev/peps/pep-0308/) too.
Yes, it looks like this: ``` return i if i < x else x ``` It's called the conditional operator in python.
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This will return i if i < x, otherwise it will return x. I like this because it is much more compact in many cases than the longer syntax which follows. ``` if (i < x) return i else return x ``` Is it possible to use this syntax in python and if so, how?
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
Yes, it looks like this: ``` return i if i < x else x ``` It's called the conditional operator in python.
Ternary operator in python. > > a if b else c > > > ``` >>> a=1 >>> b=2 >>> a if a<b else b 1 >>> a if a>b else b 2 ```
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This will return i if i < x, otherwise it will return x. I like this because it is much more compact in many cases than the longer syntax which follows. ``` if (i < x) return i else return x ``` Is it possible to use this syntax in python and if so, how?
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
`a if b else c` syntax was introduced in Python 2.5. Most people have already upgraded to the recent version but in legacy code you may find another approach: ``` some_var = a<b and a or c ``` If you ever will be using this syntax remember that `a` must not evaluate to False.
As the other answers state, Python's version for this is: `i if i < x else x` (of course for this particular example, one would prefer writing `min(i, x)` , as it is easier on the eyes) However, this expression syntax was just made available on Python 2.5 (I think it was around 2004). before that, the following idiom was used - but care should be taken, as it is error prone: `i < x and i or x` - because the logical operator "and" actually evaluates to the last true value on its chain - therefore, if the expression was true, `i < x and i` evaluates to `i` - and the `or` operator evaluates to first true value on the chain. On this case, if `i < x` would be false, so would `i< x and i` and the first true value would be `x`. It is easy to see how error prone this construct was, since if the boolean value of `i` would be false ( for example if i==0), than it would return x, even if `i < x` where true. I myself, back in those days, used to write this construct instead: (x, i)[i < x] The expression "i < x" ha a numerical value of "1" (true) or "0" (false) and I used this proeprty to have it work as an index to the previous tuple. The problem with this approach was that it would always evaluate both expressions on the tuple, even though it would use ony one of then (if the expressions where function calls this could get expensive, or even conflicting)
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This will return i if i < x, otherwise it will return x. I like this because it is much more compact in many cases than the longer syntax which follows. ``` if (i < x) return i else return x ``` Is it possible to use this syntax in python and if so, how?
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
You can use `(x if cond else y)`, e.g. ``` >>> x = 0 >>> y = 1 >>> print("a" if x < y else "b") a ``` That will work will [lambda function](http://www.python.org/dev/peps/pep-0308/) too.
Ternary operator in python. > > a if b else c > > > ``` >>> a=1 >>> b=2 >>> a if a<b else b 1 >>> a if a>b else b 2 ```
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This will return i if i < x, otherwise it will return x. I like this because it is much more compact in many cases than the longer syntax which follows. ``` if (i < x) return i else return x ``` Is it possible to use this syntax in python and if so, how?
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
You can use `(x if cond else y)`, e.g. ``` >>> x = 0 >>> y = 1 >>> print("a" if x < y else "b") a ``` That will work will [lambda function](http://www.python.org/dev/peps/pep-0308/) too.
Try this in Python: ``` return i if i < x else x ``` It's exactly the equivalent of the following expression in Java, C, C++ C# ``` return i < x ? i : x; ``` Read more about Python's [conditional expressions](http://docs.python.org/reference/expressions.html#conditional-expressions).
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This will return i if i < x, otherwise it will return x. I like this because it is much more compact in many cases than the longer syntax which follows. ``` if (i < x) return i else return x ``` Is it possible to use this syntax in python and if so, how?
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
Yes, it looks like this: ``` return i if i < x else x ``` It's called the conditional operator in python.
Try this in Python: ``` return i if i < x else x ``` It's exactly the equivalent of the following expression in Java, C, C++ C# ``` return i < x ? i : x; ``` Read more about Python's [conditional expressions](http://docs.python.org/reference/expressions.html#conditional-expressions).
44,781,806
I seem to be breaking `tkinter` on linux by using some multi-threading. As far as I can see, I am managing to trigger a garbage collection on a thread which is not the main GUI thread. This is causing `__del__` to be run on a `tk.StringVar` instance, which tries to call the `tcl` stack from the wrong thread, causing chaos on linux. The code below is the minimal example I've been able to come up with. Notice that I'm not doing any real work with `matplotlib`, but I can't trigger the problem otherwise. The `__del__` method on `Widget` verifies that the `Widget` instance is being deleted from the other thread. Typical output is: ``` Running off thread on 140653207140096 Being deleted... <__main__.Widget object .!widget2> 140653210118576 Thread is 140653207140096 ... (omitted stack from from `matplotlib` File "/nfs/see-fs-02_users/matmdpd/anaconda3/lib/python3.6/site-packages/matplotlib/text.py", line 218, in __init__ elif is_string_like(fontproperties): File "/nfs/see-fs-02_users/matmdpd/anaconda3/lib/python3.6/site-packages/matplotlib/cbook.py", line 693, in is_string_like obj + '' File "tk_threading.py", line 27, in __del__ traceback.print_stack() ... Exception ignored in: <bound method Variable.__del__ of <tkinter.StringVar object at 0x7fec60a02ac8>> Traceback (most recent call last): File "/nfs/see-fs-02_users/matmdpd/anaconda3/lib/python3.6/tkinter/__init__.py", line 335, in __del__ if self._tk.getboolean(self._tk.call("info", "exists", self._name)): _tkinter.TclError: out of stack space (infinite loop?) ``` By modifying the `tkinter` library code, I can verify that `__del__` is being called from the same place as `Widget.__del__`. > > Is my conclusion here correct? How can I stop this happening?? > > > I really, really want to call `matplotlib` code from a separate thread, because I need to produce some complex plots which are slow to render, so making them off-thread, generating an image, and then displaying the image in a `tk.Canvas` widget seemed like an elegant solution. Minimal example: ``` import tkinter as tk import traceback import threading import matplotlib matplotlib.use('Agg') import matplotlib.figure as figure from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas class Widget(tk.Frame): def __init__(self, parent): super().__init__(parent) self.var = tk.StringVar() #tk.Entry(self, textvariable=self.var).grid() self._thing = tk.Frame(self) def task(): print("Running off thread on", threading.get_ident()) fig = figure.Figure(figsize=(5,5)) FigureCanvas(fig) fig.add_subplot(1,1,1) print("All done off thread...") #import gc #gc.collect() threading.Thread(target=task).start() def __del__(self): print("Being deleted...", self.__repr__(), id(self)) print("Thread is", threading.get_ident()) traceback.print_stack() root = tk.Tk() frame = Widget(root) frame.grid(row=1, column=0) def click(): global frame frame.destroy() frame = Widget(root) frame.grid(row=1, column=0) tk.Button(root, text="Click me", command=click).grid(row=0, column=0) root.mainloop() ``` Notice that in the example, I don't need the `tk.Entry` widget. *However* if I comment out the line `self._thing = tk.Frame(self)` then I *cannot* recreate the problem! I don't understand this... If I uncomment then `gc` lines, then also the problem goes away (which fits with my conclusion...) *Update:* This seem to work the same way on Windows. `tkinter` on Windows seems more tolerant of being called on the "wrong" thread, so I don't get the `_tkinter.TclError` exception. But I can see the `__del__` destructor being called on the non-main thread.
2017/06/27
[ "https://Stackoverflow.com/questions/44781806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3403507/" ]
I had exactly the same problem It was a nightmare to find the cause of the issue. I exaustivelly verified that no tkinter object was being called from any thread. I made a mechanism based in queues to handle tkinter objects in threads. There are many examples on the web on how to do that, or... search for a module 'mttkinter', a thread safe wrapper for Tkinter) In a effort to force garbage collection, I used the "gc" method in the exit function of every TopLevel window of my App. ``` #garbage collector import gc ... gc.collect() ``` but for some reason, closing a toplevel window continued to reproduce the problem. Anyway... it was precisely using some prints in the aforementioned "mttkinter" module that I detected that, in spite the widgets are being created in the main thread, they could be garbage collected when garbage collector is triggered inside another thread. It looks like that the garbage collector gathers all the garbage without any distinction of its provenience (mainthread or other threads?). Someone please correct me if I'm wrong. My solution was to call the garbage collector explicitly using the queue as well. ``` PutInQueue(gc.collect) ``` Where "PutInQueue" belongs to a module created by me to handle tkinter object and other kind of objects with thread safety. Hope this report can be of great usefullness to someone or, it it is the case, to expose any eventual bug in garbage collector.
Tkinter is not thread safe. Calling Tkinter objects in a thread may cause things such as "The **del** method on Widget verifies that the Widget instance is being deleted from the other thread." You can use locking and queues to make it done properly. Check this example: [Tkinter: How to use threads to preventing main event loop from "freezing"](https://stackoverflow.com/questions/16745507/tkinter-how-to-use-threads-to-preventing-main-event-loop-from-freezing) and this example (there are many many other examples you can find): [Mutli-threading python with Tkinter](https://stackoverflow.com/questions/14379106/mutli-threading-python-with-tkinter) Hope this will put you in the right direction.
72,882,082
Can someone explain me what is going on here and how to prevent this? I have a **main.py** with the following code: ```python import utils import torch if __name__ == "__main__": # Foo print("Foo") # Bar utils.bar() model = torch.hub.load("ultralytics/yolov5", "yolov5s") ``` I outsourced some functions into a module named **utils.py**: ```python def bar(): print("Bar") ``` When I run this I get the following output: ``` (venv) jan@xxxxx test % python main.py Foo Bar Using cache found in /Users/jan/.cache/torch/hub/ultralytics_yolov5_master Traceback (most recent call last): File "/Users/jan/PycharmProjects/test/main.py", line 12, in <module> model = torch.hub.load("ultralytics/yolov5", "yolov5s") File "/Users/jan/PycharmProjects/test/venv/lib/python3.10/site-packages/torch/hub.py", line 540, in load model = _load_local(repo_or_dir, model, *args, **kwargs) File "/Users/jan/PycharmProjects/test/venv/lib/python3.10/site-packages/torch/hub.py", line 569, in _load_local model = entry(*args, **kwargs) File "/Users/jan/.cache/torch/hub/ultralytics_yolov5_master/hubconf.py", line 81, in yolov5s return _create('yolov5s', pretrained, channels, classes, autoshape, _verbose, device) File "/Users/jan/.cache/torch/hub/ultralytics_yolov5_master/hubconf.py", line 31, in _create from models.common import AutoShape, DetectMultiBackend File "/Users/jan/.cache/torch/hub/ultralytics_yolov5_master/models/common.py", line 24, in <module> from utils.dataloaders import exif_transpose, letterbox ModuleNotFoundError: No module named 'utils.dataloaders'; 'utils' is not a package ``` So it seems like the **torch** package I imported has also a **utils** resource (package) and searches for a module named "utils.dataloaders". Okay. But why is it searching in my utils module? And why isn't it continuing searching in its own package if it doesn't find a matching resource in my code? And last but not least: How can I prevent this situation? I changed `import utils` to `import utils as ut` and call my function with `ut.bar()` but it doesn't make any difference. The only thing that worked is to **rename** my `utils.py` to something else but this cannot be the solution... Thanks for your help. Cheers, Jan
2022/07/06
[ "https://Stackoverflow.com/questions/72882082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4875142/" ]
It is not `DELETE * FROM`, but `DELETE FROM`. ``` DELETE FROM mlode WHERE kd >= DATE '2019-01-01'; ```
``` BEGIN TRANSACTION DELETE FROM [TABLE] WHERE [DATEFIELD] > DATEFROMPARTS(2018, 12, 30) COMMIT TRANSACTION ```
19,699,314
Below is my test code. When running with python2.7 it shows that the program won't receive any signal until all spawned threads finish. While with python3.2, only the main thread's sigintHandler gets called. I'am confused with how python handles threads and signal, so how do I spawn a thread and do signal handling within that thread? Is it possible at all? ``` from __future__ import print_function from threading import Thread import signal, os, sys from time import sleep def sigintHandler(signo, _): print("signal %d caught"%signo) def fn(): print("thread sleeping") sleep(10) print("thread awakes") signal.signal(signal.SIGINT, sigintHandler) ls = [] for i in range(5): t = Thread(target=fn) ls.append(t) t.start() print("All threads up, pid=%d"%os.getpid()) for i in ls: i.join() while True: sleep(20) ```
2013/10/31
[ "https://Stackoverflow.com/questions/19699314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/922727/" ]
You can give like ``` $(this).datepicker({ "dateFormat": 'mm/dd/yy', "changeMonth": true, "changeYear": true, "yearRange": year + ":" + year }); ```
Read [yearRange](http://api.jqueryui.com/datepicker/#option-yearRange) ``` var year_text = year + ":" + year ; ``` or ``` "yearRange": year + ":" + year ```
19,699,314
Below is my test code. When running with python2.7 it shows that the program won't receive any signal until all spawned threads finish. While with python3.2, only the main thread's sigintHandler gets called. I'am confused with how python handles threads and signal, so how do I spawn a thread and do signal handling within that thread? Is it possible at all? ``` from __future__ import print_function from threading import Thread import signal, os, sys from time import sleep def sigintHandler(signo, _): print("signal %d caught"%signo) def fn(): print("thread sleeping") sleep(10) print("thread awakes") signal.signal(signal.SIGINT, sigintHandler) ls = [] for i in range(5): t = Thread(target=fn) ls.append(t) t.start() print("All threads up, pid=%d"%os.getpid()) for i in ls: i.join() while True: sleep(20) ```
2013/10/31
[ "https://Stackoverflow.com/questions/19699314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/922727/" ]
You can give like ``` $(this).datepicker({ "dateFormat": 'mm/dd/yy', "changeMonth": true, "changeYear": true, "yearRange": year + ":" + year }); ```
You can set it like this ``` $(function() { var minYear=1990; var maxYear=2000; $( "#datepicker" ).datepicker({ yearRange: minYear+':'+ maxYear, changeYear: true }); }); ``` [CHECK THIS LIVE JSFIDDLE DEMO](http://jsfiddle.net/kGjdL/457/)
48,577,536
**Background** I would like to do mini-batch training of "stateful" LSTMs in Keras. My input training data is in a large matrix "X" whose dimensions are m x n where ```python m = number-of-subsequences n = number-of-time-steps-per-sequence ``` Each row of X contains a subsequence which picks up where the subsequence on the preceding row leaves off. So given a long sequence of data, ```python Data = ( t01, t02, t03, ... ) ``` where "tK" means the token at position K in the original data, the sequence is layed out in X like so: ```python X = [ t01 t02 t03 t04 t05 t06 t07 t08 t09 t10 t11 t12 t13 t14 t15 t16 t17 t18 t19 t20 t21 t22 t23 t24 ] ``` **Question** My question is about what happens when I do mini-batch training on data layed out this way with stateful LSTMs. Specifically, mini-batch training typically trains on "contiguous" groups of rows at a time. So if I use a mini-batch size of 2, then X would be split into three mini-batches X1, X2 and X3 where ```python X1 = [ t01 t02 t03 t04 t05 t06 t07 t08 ] X2 = [ t09 t10 t11 t12 t13 t14 t15 t16 ] X3 = [ t17 t18 t19 t20 t21 t22 t23 t25 ] ``` Notice that this type of mini-batching does not agree with training **stateful** LSTMs since the hidden states produced by processing the last column of the previous batch are not the hidden states that correspond to the time-step before the first column of the subsequent batch. To see this, notice that the mini-batches will be processed as though from left-to-right like this: ```python ------ X1 ------+------- X2 ------+------- X3 ----- t01 t02 t03 t04 | t09 t10 t11 t12 | t17 t18 t19 t20 t05 t06 t07 t08 | t13 t14 t15 t16 | t21 t22 t23 t24 ``` implying that ```python - Token t04 comes immediately before t09 - Token t08 comes immediately before t13 - Token t12 comes immediately before t17 - Token t16 comes immediately before t21 ``` But I want mini-batching to group rows so that we get this kind of temporal alignment across mini-batches: ```python ------ X1 ------+------- X2 ------+------- X3 ----- t01 t02 t03 t04 | t05 t06 t07 t08 | t09 t10 t11 t12 t13 t14 t15 t16 | t17 t18 t19 t20 | t21 t22 t23 t24 ``` What is the standard way to accomplish this when training LSTMs in Keras? Thanks for any pointers here.
2018/02/02
[ "https://Stackoverflow.com/questions/48577536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4441470/" ]
You can set you ViewHolder class as [`inner`](https://kotlinlang.org/docs/reference/nested-classes.html)
Use the `companion object`: ``` class MyAdapter(private val dataList: ArrayList<String>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() { class ViewHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener { fun bindData() { //some statements } override fun onClick(p0: View?) { Log.d(TAG, "") } } companion object { val TAG: String? = MyAdapter::class.simpleName } } ```
48,577,536
**Background** I would like to do mini-batch training of "stateful" LSTMs in Keras. My input training data is in a large matrix "X" whose dimensions are m x n where ```python m = number-of-subsequences n = number-of-time-steps-per-sequence ``` Each row of X contains a subsequence which picks up where the subsequence on the preceding row leaves off. So given a long sequence of data, ```python Data = ( t01, t02, t03, ... ) ``` where "tK" means the token at position K in the original data, the sequence is layed out in X like so: ```python X = [ t01 t02 t03 t04 t05 t06 t07 t08 t09 t10 t11 t12 t13 t14 t15 t16 t17 t18 t19 t20 t21 t22 t23 t24 ] ``` **Question** My question is about what happens when I do mini-batch training on data layed out this way with stateful LSTMs. Specifically, mini-batch training typically trains on "contiguous" groups of rows at a time. So if I use a mini-batch size of 2, then X would be split into three mini-batches X1, X2 and X3 where ```python X1 = [ t01 t02 t03 t04 t05 t06 t07 t08 ] X2 = [ t09 t10 t11 t12 t13 t14 t15 t16 ] X3 = [ t17 t18 t19 t20 t21 t22 t23 t25 ] ``` Notice that this type of mini-batching does not agree with training **stateful** LSTMs since the hidden states produced by processing the last column of the previous batch are not the hidden states that correspond to the time-step before the first column of the subsequent batch. To see this, notice that the mini-batches will be processed as though from left-to-right like this: ```python ------ X1 ------+------- X2 ------+------- X3 ----- t01 t02 t03 t04 | t09 t10 t11 t12 | t17 t18 t19 t20 t05 t06 t07 t08 | t13 t14 t15 t16 | t21 t22 t23 t24 ``` implying that ```python - Token t04 comes immediately before t09 - Token t08 comes immediately before t13 - Token t12 comes immediately before t17 - Token t16 comes immediately before t21 ``` But I want mini-batching to group rows so that we get this kind of temporal alignment across mini-batches: ```python ------ X1 ------+------- X2 ------+------- X3 ----- t01 t02 t03 t04 | t05 t06 t07 t08 | t09 t10 t11 t12 t13 t14 t15 t16 | t17 t18 t19 t20 | t21 t22 t23 t24 ``` What is the standard way to accomplish this when training LSTMs in Keras? Thanks for any pointers here.
2018/02/02
[ "https://Stackoverflow.com/questions/48577536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4441470/" ]
You can set you ViewHolder class as [`inner`](https://kotlinlang.org/docs/reference/nested-classes.html)
You can also put ``` private val TAG: String? = MyAdapter::class.simpleName ``` on top level of the file.
48,577,536
**Background** I would like to do mini-batch training of "stateful" LSTMs in Keras. My input training data is in a large matrix "X" whose dimensions are m x n where ```python m = number-of-subsequences n = number-of-time-steps-per-sequence ``` Each row of X contains a subsequence which picks up where the subsequence on the preceding row leaves off. So given a long sequence of data, ```python Data = ( t01, t02, t03, ... ) ``` where "tK" means the token at position K in the original data, the sequence is layed out in X like so: ```python X = [ t01 t02 t03 t04 t05 t06 t07 t08 t09 t10 t11 t12 t13 t14 t15 t16 t17 t18 t19 t20 t21 t22 t23 t24 ] ``` **Question** My question is about what happens when I do mini-batch training on data layed out this way with stateful LSTMs. Specifically, mini-batch training typically trains on "contiguous" groups of rows at a time. So if I use a mini-batch size of 2, then X would be split into three mini-batches X1, X2 and X3 where ```python X1 = [ t01 t02 t03 t04 t05 t06 t07 t08 ] X2 = [ t09 t10 t11 t12 t13 t14 t15 t16 ] X3 = [ t17 t18 t19 t20 t21 t22 t23 t25 ] ``` Notice that this type of mini-batching does not agree with training **stateful** LSTMs since the hidden states produced by processing the last column of the previous batch are not the hidden states that correspond to the time-step before the first column of the subsequent batch. To see this, notice that the mini-batches will be processed as though from left-to-right like this: ```python ------ X1 ------+------- X2 ------+------- X3 ----- t01 t02 t03 t04 | t09 t10 t11 t12 | t17 t18 t19 t20 t05 t06 t07 t08 | t13 t14 t15 t16 | t21 t22 t23 t24 ``` implying that ```python - Token t04 comes immediately before t09 - Token t08 comes immediately before t13 - Token t12 comes immediately before t17 - Token t16 comes immediately before t21 ``` But I want mini-batching to group rows so that we get this kind of temporal alignment across mini-batches: ```python ------ X1 ------+------- X2 ------+------- X3 ----- t01 t02 t03 t04 | t05 t06 t07 t08 | t09 t10 t11 t12 t13 t14 t15 t16 | t17 t18 t19 t20 | t21 t22 t23 t24 ``` What is the standard way to accomplish this when training LSTMs in Keras? Thanks for any pointers here.
2018/02/02
[ "https://Stackoverflow.com/questions/48577536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4441470/" ]
Use the `companion object`: ``` class MyAdapter(private val dataList: ArrayList<String>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() { class ViewHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener { fun bindData() { //some statements } override fun onClick(p0: View?) { Log.d(TAG, "") } } companion object { val TAG: String? = MyAdapter::class.simpleName } } ```
You can also put ``` private val TAG: String? = MyAdapter::class.simpleName ``` on top level of the file.
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I have tried both Py 2.5.5 and Py 2.6.4 and same thing. So Whenever I do some straight forward logging like: ``` logging.debug(u'new value %s' % group) ``` this calls the models group.**unicode**(): return unicode(group.name) My unicode methods all looks like this: ``` def __unicode__(self): return u'%s - %s (%s)' % (self.group, self.user.get_full_name(), self.role) ``` This works even if group.name is XXX or ÄÄÄ (requiring unicode). But when I for some reason want to log a set, list, dictionary, django-query set and the individual instances in e.g. the list might be unicode or not I get into trouble... So this will get me a UnicodeDecodingError whenever a group.name requires unicode like Luleå (my hometown) ``` logging.debug(u'new groups %s' % list_of_groups) ``` Typically I get an error like this: ``` Exception Type: UnicodeDecodeError Exception Value: ('ascii', '<RBACInstanceRoleSet: s2 | \xc3\x84\xc3\x96\xc3\x96\xc3\x85\xc3\x85\xc3\x85 Gruppen>]', 106, 107, 'ordinal not in range(128)') ``` But if I do `print list_of_groups` everything gets out nice on terminal So, my understanding is that the list starts to generate itself and does repr() on all its elements and they return their values - in this case it should be 's2 | ÅÄÖÖ', then the list presents itself as (ascii, the-stuff-in-the-list) and then when trying to Decode the *ascii* into unicode this will of course not work -- since one of the elements in the list has returened a u'...' of itself when repr was done on it. But why is this????´ And why do things work and unicode/ascii is handled correctly whenever I log simple things like group.name and so or group and the **unicode** methods are called. Whenever I get lazy and want to log a list, set or other things go bad whenever a unicode character is encountered... Some more examples that work and fail. If `group.name` I go to the model field and `group` calls the `__unicode__()` ``` logging.debug("1. group: %s " % group.name) # WORKS logging.debug(u"2. group: %s " % group) # WORKS logging.debug("3. group: %s " % group) # FAILS logging.debug(u"4. group: %s " % group.name) # WORKS logging.debug("5. group: %s " % group.name) # WORKS ``` ...and I really thought I had a grip on Unicode ;-(
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
I can't reproduce your problem with a simple test: ``` Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> group = u'Luleå' >>> logging.warning('Group: %s', group) WARNING:root:Group: Luleå >>> logging.warning(u'Group: %s', group) WARNING:root:Group: Luleå >>> ``` So, as Daniel says, there is probably something which is not proper Unicode in what you're passing to logging. Also, I don't know what handlers you're using, but make sure if there are file handlers that you explicitly specify the output encoding to use, and if there are stream handlers you also wrap any output stream which needs it with an encoding wrapper such as is provided by the `codecs` module (and pass the wrapped stream to logging).
have you tried manually making any result unicode? ``` logging.debug(u'new groups %s' % unicode(list_of_groups("UTF-8")) ```
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I have tried both Py 2.5.5 and Py 2.6.4 and same thing. So Whenever I do some straight forward logging like: ``` logging.debug(u'new value %s' % group) ``` this calls the models group.**unicode**(): return unicode(group.name) My unicode methods all looks like this: ``` def __unicode__(self): return u'%s - %s (%s)' % (self.group, self.user.get_full_name(), self.role) ``` This works even if group.name is XXX or ÄÄÄ (requiring unicode). But when I for some reason want to log a set, list, dictionary, django-query set and the individual instances in e.g. the list might be unicode or not I get into trouble... So this will get me a UnicodeDecodingError whenever a group.name requires unicode like Luleå (my hometown) ``` logging.debug(u'new groups %s' % list_of_groups) ``` Typically I get an error like this: ``` Exception Type: UnicodeDecodeError Exception Value: ('ascii', '<RBACInstanceRoleSet: s2 | \xc3\x84\xc3\x96\xc3\x96\xc3\x85\xc3\x85\xc3\x85 Gruppen>]', 106, 107, 'ordinal not in range(128)') ``` But if I do `print list_of_groups` everything gets out nice on terminal So, my understanding is that the list starts to generate itself and does repr() on all its elements and they return their values - in this case it should be 's2 | ÅÄÖÖ', then the list presents itself as (ascii, the-stuff-in-the-list) and then when trying to Decode the *ascii* into unicode this will of course not work -- since one of the elements in the list has returened a u'...' of itself when repr was done on it. But why is this????´ And why do things work and unicode/ascii is handled correctly whenever I log simple things like group.name and so or group and the **unicode** methods are called. Whenever I get lazy and want to log a list, set or other things go bad whenever a unicode character is encountered... Some more examples that work and fail. If `group.name` I go to the model field and `group` calls the `__unicode__()` ``` logging.debug("1. group: %s " % group.name) # WORKS logging.debug(u"2. group: %s " % group) # WORKS logging.debug("3. group: %s " % group) # FAILS logging.debug(u"4. group: %s " % group.name) # WORKS logging.debug("5. group: %s " % group.name) # WORKS ``` ...and I really thought I had a grip on Unicode ;-(
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Here's my test code: ``` #-*- coding: utf-8 -*- class Wrap: def __init__(self, s): self.s = s def __repr__(self): return repr(self.s) def __unicode__(self): return unicode(self.s) def __str__(self): return str(self.s) s = 'hello' # a plaintext string u = 'ÅÄÖÖ'.decode('utf-8') l = [s,u] test0 = unicode(repr(l)) test1 = 'string %s' % l test2 = u'unicode %s' % l ``` The above works fine when you run it. However, if you change the declaration of **repr** to: def **repr**(self): return unicode(self.s) Then it aborts with: ``` Traceback (most recent call last): File "mytest.py", line 13, in <module> unicode(l) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) ``` So it looks like someone in the object hierarchy has a repr() implementation which is incorrectly returning a unicode string instead of a normal string. As someone else mentioned, when you do a format string like ``` 'format %s' % mylist ``` and mylist is a sequence, python automatically calls repr() on it rather than unicode() (since there is no "correct" way to represent a list as a unicode string). It may be django that's at fault here, or maybe you've implemented `__repr__` incorrectly in one of your models. #
I can't reproduce your problem with a simple test: ``` Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> group = u'Luleå' >>> logging.warning('Group: %s', group) WARNING:root:Group: Luleå >>> logging.warning(u'Group: %s', group) WARNING:root:Group: Luleå >>> ``` So, as Daniel says, there is probably something which is not proper Unicode in what you're passing to logging. Also, I don't know what handlers you're using, but make sure if there are file handlers that you explicitly specify the output encoding to use, and if there are stream handlers you also wrap any output stream which needs it with an encoding wrapper such as is provided by the `codecs` module (and pass the wrapped stream to logging).
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I have tried both Py 2.5.5 and Py 2.6.4 and same thing. So Whenever I do some straight forward logging like: ``` logging.debug(u'new value %s' % group) ``` this calls the models group.**unicode**(): return unicode(group.name) My unicode methods all looks like this: ``` def __unicode__(self): return u'%s - %s (%s)' % (self.group, self.user.get_full_name(), self.role) ``` This works even if group.name is XXX or ÄÄÄ (requiring unicode). But when I for some reason want to log a set, list, dictionary, django-query set and the individual instances in e.g. the list might be unicode or not I get into trouble... So this will get me a UnicodeDecodingError whenever a group.name requires unicode like Luleå (my hometown) ``` logging.debug(u'new groups %s' % list_of_groups) ``` Typically I get an error like this: ``` Exception Type: UnicodeDecodeError Exception Value: ('ascii', '<RBACInstanceRoleSet: s2 | \xc3\x84\xc3\x96\xc3\x96\xc3\x85\xc3\x85\xc3\x85 Gruppen>]', 106, 107, 'ordinal not in range(128)') ``` But if I do `print list_of_groups` everything gets out nice on terminal So, my understanding is that the list starts to generate itself and does repr() on all its elements and they return their values - in this case it should be 's2 | ÅÄÖÖ', then the list presents itself as (ascii, the-stuff-in-the-list) and then when trying to Decode the *ascii* into unicode this will of course not work -- since one of the elements in the list has returened a u'...' of itself when repr was done on it. But why is this????´ And why do things work and unicode/ascii is handled correctly whenever I log simple things like group.name and so or group and the **unicode** methods are called. Whenever I get lazy and want to log a list, set or other things go bad whenever a unicode character is encountered... Some more examples that work and fail. If `group.name` I go to the model field and `group` calls the `__unicode__()` ``` logging.debug("1. group: %s " % group.name) # WORKS logging.debug(u"2. group: %s " % group) # WORKS logging.debug("3. group: %s " % group) # FAILS logging.debug(u"4. group: %s " % group.name) # WORKS logging.debug("5. group: %s " % group.name) # WORKS ``` ...and I really thought I had a grip on Unicode ;-(
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Try to use this code in the top of your views.py ``` #-*- coding: utf-8 -*- ... ```
have you tried manually making any result unicode? ``` logging.debug(u'new groups %s' % unicode(list_of_groups("UTF-8")) ```
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I have tried both Py 2.5.5 and Py 2.6.4 and same thing. So Whenever I do some straight forward logging like: ``` logging.debug(u'new value %s' % group) ``` this calls the models group.**unicode**(): return unicode(group.name) My unicode methods all looks like this: ``` def __unicode__(self): return u'%s - %s (%s)' % (self.group, self.user.get_full_name(), self.role) ``` This works even if group.name is XXX or ÄÄÄ (requiring unicode). But when I for some reason want to log a set, list, dictionary, django-query set and the individual instances in e.g. the list might be unicode or not I get into trouble... So this will get me a UnicodeDecodingError whenever a group.name requires unicode like Luleå (my hometown) ``` logging.debug(u'new groups %s' % list_of_groups) ``` Typically I get an error like this: ``` Exception Type: UnicodeDecodeError Exception Value: ('ascii', '<RBACInstanceRoleSet: s2 | \xc3\x84\xc3\x96\xc3\x96\xc3\x85\xc3\x85\xc3\x85 Gruppen>]', 106, 107, 'ordinal not in range(128)') ``` But if I do `print list_of_groups` everything gets out nice on terminal So, my understanding is that the list starts to generate itself and does repr() on all its elements and they return their values - in this case it should be 's2 | ÅÄÖÖ', then the list presents itself as (ascii, the-stuff-in-the-list) and then when trying to Decode the *ascii* into unicode this will of course not work -- since one of the elements in the list has returened a u'...' of itself when repr was done on it. But why is this????´ And why do things work and unicode/ascii is handled correctly whenever I log simple things like group.name and so or group and the **unicode** methods are called. Whenever I get lazy and want to log a list, set or other things go bad whenever a unicode character is encountered... Some more examples that work and fail. If `group.name` I go to the model field and `group` calls the `__unicode__()` ``` logging.debug("1. group: %s " % group.name) # WORKS logging.debug(u"2. group: %s " % group) # WORKS logging.debug("3. group: %s " % group) # FAILS logging.debug(u"4. group: %s " % group.name) # WORKS logging.debug("5. group: %s " % group.name) # WORKS ``` ...and I really thought I had a grip on Unicode ;-(
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Try to use this code in the top of your views.py ``` #-*- coding: utf-8 -*- ... ```
I encountered the same issues: see <http://hustoknow.blogspot.com/2012/09/unicode-quirks-in-django.html>. You can declare a **str**() method to override the Django default behavior, which will help to avoid this issue. Or you always have to prefix the u' in front of your logging() statements.
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I have tried both Py 2.5.5 and Py 2.6.4 and same thing. So Whenever I do some straight forward logging like: ``` logging.debug(u'new value %s' % group) ``` this calls the models group.**unicode**(): return unicode(group.name) My unicode methods all looks like this: ``` def __unicode__(self): return u'%s - %s (%s)' % (self.group, self.user.get_full_name(), self.role) ``` This works even if group.name is XXX or ÄÄÄ (requiring unicode). But when I for some reason want to log a set, list, dictionary, django-query set and the individual instances in e.g. the list might be unicode or not I get into trouble... So this will get me a UnicodeDecodingError whenever a group.name requires unicode like Luleå (my hometown) ``` logging.debug(u'new groups %s' % list_of_groups) ``` Typically I get an error like this: ``` Exception Type: UnicodeDecodeError Exception Value: ('ascii', '<RBACInstanceRoleSet: s2 | \xc3\x84\xc3\x96\xc3\x96\xc3\x85\xc3\x85\xc3\x85 Gruppen>]', 106, 107, 'ordinal not in range(128)') ``` But if I do `print list_of_groups` everything gets out nice on terminal So, my understanding is that the list starts to generate itself and does repr() on all its elements and they return their values - in this case it should be 's2 | ÅÄÖÖ', then the list presents itself as (ascii, the-stuff-in-the-list) and then when trying to Decode the *ascii* into unicode this will of course not work -- since one of the elements in the list has returened a u'...' of itself when repr was done on it. But why is this????´ And why do things work and unicode/ascii is handled correctly whenever I log simple things like group.name and so or group and the **unicode** methods are called. Whenever I get lazy and want to log a list, set or other things go bad whenever a unicode character is encountered... Some more examples that work and fail. If `group.name` I go to the model field and `group` calls the `__unicode__()` ``` logging.debug("1. group: %s " % group.name) # WORKS logging.debug(u"2. group: %s " % group) # WORKS logging.debug("3. group: %s " % group) # FAILS logging.debug(u"4. group: %s " % group.name) # WORKS logging.debug("5. group: %s " % group.name) # WORKS ``` ...and I really thought I had a grip on Unicode ;-(
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
I can't reproduce your problem with a simple test: ``` Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> group = u'Luleå' >>> logging.warning('Group: %s', group) WARNING:root:Group: Luleå >>> logging.warning(u'Group: %s', group) WARNING:root:Group: Luleå >>> ``` So, as Daniel says, there is probably something which is not proper Unicode in what you're passing to logging. Also, I don't know what handlers you're using, but make sure if there are file handlers that you explicitly specify the output encoding to use, and if there are stream handlers you also wrap any output stream which needs it with an encoding wrapper such as is provided by the `codecs` module (and pass the wrapped stream to logging).
I think, that this bug of Python is the reason of described behavior <https://bugs.python.org/issue19846> Check locale settings, if you getting UnicodeDecodeError on Python 3. This answer <https://stackoverflow.com/a/40803148/4862792> helps me for windows, but on production with locale LANG\_C I`ve got this problem one more time
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I have tried both Py 2.5.5 and Py 2.6.4 and same thing. So Whenever I do some straight forward logging like: ``` logging.debug(u'new value %s' % group) ``` this calls the models group.**unicode**(): return unicode(group.name) My unicode methods all looks like this: ``` def __unicode__(self): return u'%s - %s (%s)' % (self.group, self.user.get_full_name(), self.role) ``` This works even if group.name is XXX or ÄÄÄ (requiring unicode). But when I for some reason want to log a set, list, dictionary, django-query set and the individual instances in e.g. the list might be unicode or not I get into trouble... So this will get me a UnicodeDecodingError whenever a group.name requires unicode like Luleå (my hometown) ``` logging.debug(u'new groups %s' % list_of_groups) ``` Typically I get an error like this: ``` Exception Type: UnicodeDecodeError Exception Value: ('ascii', '<RBACInstanceRoleSet: s2 | \xc3\x84\xc3\x96\xc3\x96\xc3\x85\xc3\x85\xc3\x85 Gruppen>]', 106, 107, 'ordinal not in range(128)') ``` But if I do `print list_of_groups` everything gets out nice on terminal So, my understanding is that the list starts to generate itself and does repr() on all its elements and they return their values - in this case it should be 's2 | ÅÄÖÖ', then the list presents itself as (ascii, the-stuff-in-the-list) and then when trying to Decode the *ascii* into unicode this will of course not work -- since one of the elements in the list has returened a u'...' of itself when repr was done on it. But why is this????´ And why do things work and unicode/ascii is handled correctly whenever I log simple things like group.name and so or group and the **unicode** methods are called. Whenever I get lazy and want to log a list, set or other things go bad whenever a unicode character is encountered... Some more examples that work and fail. If `group.name` I go to the model field and `group` calls the `__unicode__()` ``` logging.debug("1. group: %s " % group.name) # WORKS logging.debug(u"2. group: %s " % group) # WORKS logging.debug("3. group: %s " % group) # FAILS logging.debug(u"4. group: %s " % group.name) # WORKS logging.debug("5. group: %s " % group.name) # WORKS ``` ...and I really thought I had a grip on Unicode ;-(
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Here's my test code: ``` #-*- coding: utf-8 -*- class Wrap: def __init__(self, s): self.s = s def __repr__(self): return repr(self.s) def __unicode__(self): return unicode(self.s) def __str__(self): return str(self.s) s = 'hello' # a plaintext string u = 'ÅÄÖÖ'.decode('utf-8') l = [s,u] test0 = unicode(repr(l)) test1 = 'string %s' % l test2 = u'unicode %s' % l ``` The above works fine when you run it. However, if you change the declaration of **repr** to: def **repr**(self): return unicode(self.s) Then it aborts with: ``` Traceback (most recent call last): File "mytest.py", line 13, in <module> unicode(l) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) ``` So it looks like someone in the object hierarchy has a repr() implementation which is incorrectly returning a unicode string instead of a normal string. As someone else mentioned, when you do a format string like ``` 'format %s' % mylist ``` and mylist is a sequence, python automatically calls repr() on it rather than unicode() (since there is no "correct" way to represent a list as a unicode string). It may be django that's at fault here, or maybe you've implemented `__repr__` incorrectly in one of your models. #
have you tried manually making any result unicode? ``` logging.debug(u'new groups %s' % unicode(list_of_groups("UTF-8")) ```
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I have tried both Py 2.5.5 and Py 2.6.4 and same thing. So Whenever I do some straight forward logging like: ``` logging.debug(u'new value %s' % group) ``` this calls the models group.**unicode**(): return unicode(group.name) My unicode methods all looks like this: ``` def __unicode__(self): return u'%s - %s (%s)' % (self.group, self.user.get_full_name(), self.role) ``` This works even if group.name is XXX or ÄÄÄ (requiring unicode). But when I for some reason want to log a set, list, dictionary, django-query set and the individual instances in e.g. the list might be unicode or not I get into trouble... So this will get me a UnicodeDecodingError whenever a group.name requires unicode like Luleå (my hometown) ``` logging.debug(u'new groups %s' % list_of_groups) ``` Typically I get an error like this: ``` Exception Type: UnicodeDecodeError Exception Value: ('ascii', '<RBACInstanceRoleSet: s2 | \xc3\x84\xc3\x96\xc3\x96\xc3\x85\xc3\x85\xc3\x85 Gruppen>]', 106, 107, 'ordinal not in range(128)') ``` But if I do `print list_of_groups` everything gets out nice on terminal So, my understanding is that the list starts to generate itself and does repr() on all its elements and they return their values - in this case it should be 's2 | ÅÄÖÖ', then the list presents itself as (ascii, the-stuff-in-the-list) and then when trying to Decode the *ascii* into unicode this will of course not work -- since one of the elements in the list has returened a u'...' of itself when repr was done on it. But why is this????´ And why do things work and unicode/ascii is handled correctly whenever I log simple things like group.name and so or group and the **unicode** methods are called. Whenever I get lazy and want to log a list, set or other things go bad whenever a unicode character is encountered... Some more examples that work and fail. If `group.name` I go to the model field and `group` calls the `__unicode__()` ``` logging.debug("1. group: %s " % group.name) # WORKS logging.debug(u"2. group: %s " % group) # WORKS logging.debug("3. group: %s " % group) # FAILS logging.debug(u"4. group: %s " % group.name) # WORKS logging.debug("5. group: %s " % group.name) # WORKS ``` ...and I really thought I had a grip on Unicode ;-(
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Try to use this code in the top of your views.py ``` #-*- coding: utf-8 -*- ... ```
I think, that this bug of Python is the reason of described behavior <https://bugs.python.org/issue19846> Check locale settings, if you getting UnicodeDecodeError on Python 3. This answer <https://stackoverflow.com/a/40803148/4862792> helps me for windows, but on production with locale LANG\_C I`ve got this problem one more time
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I have tried both Py 2.5.5 and Py 2.6.4 and same thing. So Whenever I do some straight forward logging like: ``` logging.debug(u'new value %s' % group) ``` this calls the models group.**unicode**(): return unicode(group.name) My unicode methods all looks like this: ``` def __unicode__(self): return u'%s - %s (%s)' % (self.group, self.user.get_full_name(), self.role) ``` This works even if group.name is XXX or ÄÄÄ (requiring unicode). But when I for some reason want to log a set, list, dictionary, django-query set and the individual instances in e.g. the list might be unicode or not I get into trouble... So this will get me a UnicodeDecodingError whenever a group.name requires unicode like Luleå (my hometown) ``` logging.debug(u'new groups %s' % list_of_groups) ``` Typically I get an error like this: ``` Exception Type: UnicodeDecodeError Exception Value: ('ascii', '<RBACInstanceRoleSet: s2 | \xc3\x84\xc3\x96\xc3\x96\xc3\x85\xc3\x85\xc3\x85 Gruppen>]', 106, 107, 'ordinal not in range(128)') ``` But if I do `print list_of_groups` everything gets out nice on terminal So, my understanding is that the list starts to generate itself and does repr() on all its elements and they return their values - in this case it should be 's2 | ÅÄÖÖ', then the list presents itself as (ascii, the-stuff-in-the-list) and then when trying to Decode the *ascii* into unicode this will of course not work -- since one of the elements in the list has returened a u'...' of itself when repr was done on it. But why is this????´ And why do things work and unicode/ascii is handled correctly whenever I log simple things like group.name and so or group and the **unicode** methods are called. Whenever I get lazy and want to log a list, set or other things go bad whenever a unicode character is encountered... Some more examples that work and fail. If `group.name` I go to the model field and `group` calls the `__unicode__()` ``` logging.debug("1. group: %s " % group.name) # WORKS logging.debug(u"2. group: %s " % group) # WORKS logging.debug("3. group: %s " % group) # FAILS logging.debug(u"4. group: %s " % group.name) # WORKS logging.debug("5. group: %s " % group.name) # WORKS ``` ...and I really thought I had a grip on Unicode ;-(
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Try to use this code in the top of your views.py ``` #-*- coding: utf-8 -*- ... ```
Check: ``` import locale locale.getpreferredencoding() ``` must be 'utf8'. I have 'cp1252'. Helped me add to manage.py: ``` import _locale _locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8']) ``` Windows 10, Django 1.10.3, Python 3.5.2, fixed problems with russian language
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I have tried both Py 2.5.5 and Py 2.6.4 and same thing. So Whenever I do some straight forward logging like: ``` logging.debug(u'new value %s' % group) ``` this calls the models group.**unicode**(): return unicode(group.name) My unicode methods all looks like this: ``` def __unicode__(self): return u'%s - %s (%s)' % (self.group, self.user.get_full_name(), self.role) ``` This works even if group.name is XXX or ÄÄÄ (requiring unicode). But when I for some reason want to log a set, list, dictionary, django-query set and the individual instances in e.g. the list might be unicode or not I get into trouble... So this will get me a UnicodeDecodingError whenever a group.name requires unicode like Luleå (my hometown) ``` logging.debug(u'new groups %s' % list_of_groups) ``` Typically I get an error like this: ``` Exception Type: UnicodeDecodeError Exception Value: ('ascii', '<RBACInstanceRoleSet: s2 | \xc3\x84\xc3\x96\xc3\x96\xc3\x85\xc3\x85\xc3\x85 Gruppen>]', 106, 107, 'ordinal not in range(128)') ``` But if I do `print list_of_groups` everything gets out nice on terminal So, my understanding is that the list starts to generate itself and does repr() on all its elements and they return their values - in this case it should be 's2 | ÅÄÖÖ', then the list presents itself as (ascii, the-stuff-in-the-list) and then when trying to Decode the *ascii* into unicode this will of course not work -- since one of the elements in the list has returened a u'...' of itself when repr was done on it. But why is this????´ And why do things work and unicode/ascii is handled correctly whenever I log simple things like group.name and so or group and the **unicode** methods are called. Whenever I get lazy and want to log a list, set or other things go bad whenever a unicode character is encountered... Some more examples that work and fail. If `group.name` I go to the model field and `group` calls the `__unicode__()` ``` logging.debug("1. group: %s " % group.name) # WORKS logging.debug(u"2. group: %s " % group) # WORKS logging.debug("3. group: %s " % group) # FAILS logging.debug(u"4. group: %s " % group.name) # WORKS logging.debug("5. group: %s " % group.name) # WORKS ``` ...and I really thought I had a grip on Unicode ;-(
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Here's my test code: ``` #-*- coding: utf-8 -*- class Wrap: def __init__(self, s): self.s = s def __repr__(self): return repr(self.s) def __unicode__(self): return unicode(self.s) def __str__(self): return str(self.s) s = 'hello' # a plaintext string u = 'ÅÄÖÖ'.decode('utf-8') l = [s,u] test0 = unicode(repr(l)) test1 = 'string %s' % l test2 = u'unicode %s' % l ``` The above works fine when you run it. However, if you change the declaration of **repr** to: def **repr**(self): return unicode(self.s) Then it aborts with: ``` Traceback (most recent call last): File "mytest.py", line 13, in <module> unicode(l) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) ``` So it looks like someone in the object hierarchy has a repr() implementation which is incorrectly returning a unicode string instead of a normal string. As someone else mentioned, when you do a format string like ``` 'format %s' % mylist ``` and mylist is a sequence, python automatically calls repr() on it rather than unicode() (since there is no "correct" way to represent a list as a unicode string). It may be django that's at fault here, or maybe you've implemented `__repr__` incorrectly in one of your models. #
Try to use this code in the top of your views.py ``` #-*- coding: utf-8 -*- ... ```
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I have tried both Py 2.5.5 and Py 2.6.4 and same thing. So Whenever I do some straight forward logging like: ``` logging.debug(u'new value %s' % group) ``` this calls the models group.**unicode**(): return unicode(group.name) My unicode methods all looks like this: ``` def __unicode__(self): return u'%s - %s (%s)' % (self.group, self.user.get_full_name(), self.role) ``` This works even if group.name is XXX or ÄÄÄ (requiring unicode). But when I for some reason want to log a set, list, dictionary, django-query set and the individual instances in e.g. the list might be unicode or not I get into trouble... So this will get me a UnicodeDecodingError whenever a group.name requires unicode like Luleå (my hometown) ``` logging.debug(u'new groups %s' % list_of_groups) ``` Typically I get an error like this: ``` Exception Type: UnicodeDecodeError Exception Value: ('ascii', '<RBACInstanceRoleSet: s2 | \xc3\x84\xc3\x96\xc3\x96\xc3\x85\xc3\x85\xc3\x85 Gruppen>]', 106, 107, 'ordinal not in range(128)') ``` But if I do `print list_of_groups` everything gets out nice on terminal So, my understanding is that the list starts to generate itself and does repr() on all its elements and they return their values - in this case it should be 's2 | ÅÄÖÖ', then the list presents itself as (ascii, the-stuff-in-the-list) and then when trying to Decode the *ascii* into unicode this will of course not work -- since one of the elements in the list has returened a u'...' of itself when repr was done on it. But why is this????´ And why do things work and unicode/ascii is handled correctly whenever I log simple things like group.name and so or group and the **unicode** methods are called. Whenever I get lazy and want to log a list, set or other things go bad whenever a unicode character is encountered... Some more examples that work and fail. If `group.name` I go to the model field and `group` calls the `__unicode__()` ``` logging.debug("1. group: %s " % group.name) # WORKS logging.debug(u"2. group: %s " % group) # WORKS logging.debug("3. group: %s " % group) # FAILS logging.debug(u"4. group: %s " % group.name) # WORKS logging.debug("5. group: %s " % group.name) # WORKS ``` ...and I really thought I had a grip on Unicode ;-(
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Try to use this code in the top of your views.py ``` #-*- coding: utf-8 -*- ... ```
I don't understand what it is you don't understand, if you see what I mean. Your middle paragraph: > > So, my understanding is that the list starts to generate itself and does repr() on all its elements and they return their values - in this case it should be 's2 | ÅÄÖÖ', then the list presents itself as (ascii, the-stuff-in-the-list) and then when trying to Decode the ascii into unicode this will of course not work -- since one of the elements in the list has returened a u'...' of itself when repr was done on it. > > > explains exactly what is going on - outputting a list isn't the same as printing all its elements, because under the hood all it does is call repr() on each element in the list. Rather than outputting the raw list, you could log a list comprehension which calls unicode on each element, which would fix it.
46,591,968
im new to python and im failing to achieve this. I have two lists of lists: ``` list1 = [['user1', 'id1'], ['user2', 'id2'], ['user3', 'id3']...] list2 = [['id1', 'group1'], ['id1', 'group2'], ['id2', 'group1'], ['id2', 'group4']...] ``` And what i need is a single list like this: ``` [['user1','id1','group1'],['user1','id1','group2'],['user2','id2','group1']] ``` I suppose I could iterate all the lists and compare values but i think there must be some built-in function that allows me to saerch a value in a list of lists and return the key or something like that. But i cant find anything for multidimensional lists. Note that the idN value in the first list not necessarily exists in the second one. Thanks for your help!
2017/10/05
[ "https://Stackoverflow.com/questions/46591968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8419741/" ]
There's no such thing in python. There are methods for multidimensional arrays in `numpy`, but they are not really suitable for text. Your second list functions as a dictionary, so make one ``` dict2 = {key:value for key, value in list2} ``` and then ``` new_list = [[a, b, dict2[b]] for a, b in list1] ```
If you have to use lists of lists, you can use a comprehension to achieve this. ``` list1 = [['user1', 'id1'], ['user2', 'id2']] list2 = [['id1', 'group1'], ['id1', 'group2'], ['id2', 'group1'], ['id2', 'group4']] listOut = [[x[0],x[1],y[1]] for x in list1 for y in list2 if x[1] == y[0]] output => [['user1', 'id1', 'group1'], ['user1', 'id1', 'group2'], ['user2', 'id2', 'group1'], ['user2', 'id2', 'group4']] ```
46,591,968
im new to python and im failing to achieve this. I have two lists of lists: ``` list1 = [['user1', 'id1'], ['user2', 'id2'], ['user3', 'id3']...] list2 = [['id1', 'group1'], ['id1', 'group2'], ['id2', 'group1'], ['id2', 'group4']...] ``` And what i need is a single list like this: ``` [['user1','id1','group1'],['user1','id1','group2'],['user2','id2','group1']] ``` I suppose I could iterate all the lists and compare values but i think there must be some built-in function that allows me to saerch a value in a list of lists and return the key or something like that. But i cant find anything for multidimensional lists. Note that the idN value in the first list not necessarily exists in the second one. Thanks for your help!
2017/10/05
[ "https://Stackoverflow.com/questions/46591968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8419741/" ]
There's no such thing in python. There are methods for multidimensional arrays in `numpy`, but they are not really suitable for text. Your second list functions as a dictionary, so make one ``` dict2 = {key:value for key, value in list2} ``` and then ``` new_list = [[a, b, dict2[b]] for a, b in list1] ```
You can try this code : ``` list1 = [['user1', 'id1'], ['user2', 'id2'], ['user3', 'id3']] list2 = [['id1', 'group1'], ['id1', 'group2'], ['id2', 'group1'], ['id2', 'group4']] final_list=[] for sublist in list1: for item in sublist: for sublist1 in list2: for item1 in sublist1: if item==item1: final_list.append(("".join(sublist[:1]),item1,"".join(sublist1[1:]))) print(final_list) ``` output: ``` [('user1', 'id1', 'group1'), ('user1', 'id1', 'group2'), ('user2', 'id2', 'group1'), ('user2', 'id2', 'group4')] ```
57,660,887
I just need contexts to be an Array ie., 'contexts' :[{}] instead of 'contexts':{} Below is my python code which helps in converting python data-frame to required JSON format This is the sample df for one row ``` name type aim context xxx xxx specs 67646546 United States of America data = {'entities':[]} for key,grp in df.groupby('name'): for idx, row in grp.iterrows(): temp_dict_alpha = {'name':key,'type':row['type'],'data' :{'contexts':{'attributes':{},'context':{'dcountry':row['dcountry']}}}} attr_row = row[~row.index.isin(['name','type'])] for idx2,row2 in attr_row.iteritems(): dict_temp = {} dict_temp[idx2] = {'values':[]} dict_temp[idx2]['values'].append({'value':row2,'source':'internal','locale':'en_Us'}) temp_dict_alpha['data']['contexts']['attributes'].update(dict_temp) data['entities'].append(temp_dict_alpha) print(json.dumps(data, indent = 4)) ``` Desired output: ``` { "entities": [{ "name": "XXX XXX", "type": "specs", "data": { "contexts": [{ "attributes": { "aim": { "values": [{ "value": 67646546, "source": "internal", "locale": "en_Us" } ] } }, "context": { "country": "United States of America" } } ] } } ] } ``` However I am getting below output ``` { "entities": [{ "name": "XXX XXX", "type": "specs", "data": { "contexts": { "attributes": { "aim": { "values": [{ "value": 67646546, "source": "internal", "locale": "en_Us" } ] } }, "context": { "country": "United States of America" } } } } ] } ``` Can any one please suggest ways for solving this problem using Python.
2019/08/26
[ "https://Stackoverflow.com/questions/57660887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11922956/" ]
I think this does it: ``` import pandas as pd import json df = pd.DataFrame([['xxx xxx','specs','67646546','United States of America']], columns = ['name', 'type', 'aim', 'context' ]) data = {'entities':[]} for key,grp in df.groupby('name'): for idx, row in grp.iterrows(): temp_dict_alpha = {'name':key,'type':row['type'],'data' :{'contexts':[{'attributes':{},'context':{'country':row['context']}}]}} attr_row = row[~row.index.isin(['name','type'])] for idx2,row2 in attr_row.iteritems(): if idx2 != 'aim': continue dict_temp = {} dict_temp[idx2] = {'values':[]} dict_temp[idx2]['values'].append({'value':row2,'source':'internal','locale':'en_Us'}) temp_dict_alpha['data']['contexts'][0]['attributes'].update(dict_temp) data['entities'].append(temp_dict_alpha) print(json.dumps(data, indent = 4)) ``` **Output:** ``` { "entities": [ { "name": "xxx xxx", "type": "specs", "data": { "contexts": [ { "attributes": { "aim": { "values": [ { "value": "67646546", "source": "internal", "locale": "en_Us" } ] } }, "context": { "country": "United States of America" } } ] } } ] } ```
The problem is here in the following code ``` temp_dict_alpha = {'name':key,'type':row['type'],'data' :{'contexts':{'attributes':{},'context':{'dcountry':row['dcountry']}}}} ``` As you can see , you are already creating a `contexts` `dict` and assigning values to it. What you could do is something like this ``` contextObj = {'attributes':{},'context':{'dcountry':row['dcountry']}} contextList = [] for idx, row in grp.iterrows(): temp_dict_alpha = {'name':key,'type':row['type'],'data' :{'contexts':{'attributes':{},'context':{'dcountry':row['dcountry']}}}} attr_row = row[~row.index.isin(['name','type'])] for idx2,row2 in attr_row.iteritems(): dict_temp = {} dict_temp[idx2] = {'values':[]} dict_temp[idx2]['values'].append({'value':row2,'source':'internal','locale':'en_Us'}) contextObj['attributes'].update(dict_temp) contextList.append(contextObj) ``` Please Note - This code will have logical errors and might not run ( as it is difficult for me , to understand the logic behind it). But here is what you need to do . You need to create a list of objects, which is not what you are doing. You are trying to manipulate an object and when its JSON dumped , you are getting an object back instead of a list. What you need is a list. You create context object for each and every iteration and keep on appending them to the local list `contextList` that we created earlier. Once when the for loop terminates, you can update your original object by using the `contextList` and you will have a list of objects instead of and `object` which you are having now.
3,764,791
Is there any fb tag i can use to wrap around my html anchor tag so that if the user isn't logged in, they will get prompted to login before getting access to the link? I'm using python/django in backend. Thanks, David
2010/09/21
[ "https://Stackoverflow.com/questions/3764791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225128/" ]
This is just an interpretation question, but I would say that you would take the decimal representation of a number, and count the total number of digits that are 6, 4, or 9. For example: * 100 --> 0 * 4 --> 1 * 469 --> 3 * 444 --> 3 Get it now?
One interpretation - example: Given `678799391`, the number of digits would be `0` for `4`, `1` for `6` and `3` for `9`. The sum of the occurences would be `0 + 1 + 3 = 4`.
3,764,791
Is there any fb tag i can use to wrap around my html anchor tag so that if the user isn't logged in, they will get prompted to login before getting access to the link? I'm using python/django in backend. Thanks, David
2010/09/21
[ "https://Stackoverflow.com/questions/3764791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225128/" ]
This is just an interpretation question, but I would say that you would take the decimal representation of a number, and count the total number of digits that are 6, 4, or 9. For example: * 100 --> 0 * 4 --> 1 * 469 --> 3 * 444 --> 3 Get it now?
Convert the whole number to a list and check each one individually. ``` (define (number->list x) (string->list (number->string x)) (define (6-4-or-9 x) (cond ((= x 6) true)) ((= x 4) true)) ((= x 9) true)))) (define (count-6-4-9 x) (cond ((6-4-or-9 (car (number->list x))))....... ``` I'm sure you can see where that's going. It's pretty crude, and I'm not sure it's really idiomatic, but it should work. The idea is is that you convert the number to a list, check to first digit, if it's six, four or nine, recursively call the procedure on the cdr of the number list converted back to a string + 1...
3,764,791
Is there any fb tag i can use to wrap around my html anchor tag so that if the user isn't logged in, they will get prompted to login before getting access to the link? I'm using python/django in backend. Thanks, David
2010/09/21
[ "https://Stackoverflow.com/questions/3764791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225128/" ]
This is just an interpretation question, but I would say that you would take the decimal representation of a number, and count the total number of digits that are 6, 4, or 9. For example: * 100 --> 0 * 4 --> 1 * 469 --> 3 * 444 --> 3 Get it now?
If you are not using lists, you can work with modulo `%` of 10 and dividing whole numbers `/` with 10. Below is the recursive solution : ``` (define (digits n) (if(not (< n 1)) (+ 1 (digits (/ n 10))) 0)) ```
3,764,791
Is there any fb tag i can use to wrap around my html anchor tag so that if the user isn't logged in, they will get prompted to login before getting access to the link? I'm using python/django in backend. Thanks, David
2010/09/21
[ "https://Stackoverflow.com/questions/3764791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225128/" ]
This is just an interpretation question, but I would say that you would take the decimal representation of a number, and count the total number of digits that are 6, 4, or 9. For example: * 100 --> 0 * 4 --> 1 * 469 --> 3 * 444 --> 3 Get it now?
First, we must understand what the question is asking: It is asking you to write a procedure that counts the number of times the numbers 4, 6, or 9 show up in another inputted number. For instance, inputting `10345` should return `1`. Let's see why: The digits of `10345` are `1`, `0`, `3`, `4`, and `5`. We have to ask, "How many times do `4`, `6`, or `9` show up?" Well, there are no `6`'s or `9`'s in `10345`. However, there is one `4`. Therefore, the procedure should return `1`. Another example: `(digit-count 14289)` Let's break it up like we did before. The digits of `14289` are `1`, `4`, `2`, `8`, and `9`. There are no `6`'s. There are, however, `1`'s and `9`'s. How many? There is one `1` and one `9`. Since there are two (total) of the desired digits present (desired digits are `4`, `6`, and `9`), `(digit-count 14289)` should return `2`. Some more examples: `(digit-count 144)` --> `2` (there are two `4`'s) `(digit-count 1)` --> `0` (there are no `4`'s, `6`'s, or `9`'s) `(digit-count 1262)` --> `1` (there is one `6`) Now, let's start defining. We can take advantage of the `appearances` function, which takes two inputs and returns how many times the first input *appears* in the second. For example: `(appearances 'a 'amsterdam)` returns `2` because there are two `a`'s in `amsterdam`. Using `appearances`, here is our definition (finally!): ``` (define (count469 num) (+ (appearances 4 num) (appearances 6 num) (appearances 9 num))) ``` This function returns the sum of the `appearances` of 4, the `appearances` of 6, and the `appearances` of 9. Please feel free to reply with any feedback or questions!
60,578,442
When I tried to add value of language python3 returns error that this object is not JSON serializible. models: ``` from django.db import models from django.contrib.auth.models import AbstractUser, AbstractBaseUser class Admin(AbstractUser): class Meta(AbstractUser.Meta): pass class HahaUser(AbstractBaseUser): is_admin = models.BooleanField(default=False, verbose_name='is administrator?') born = models.PositiveSmallIntegerField(verbose_name='born year') rating = models.PositiveIntegerField(default=0, verbose_name='user rating') email = models.EmailField(verbose_name='email') nickname = models.CharField(max_length=32, verbose_name='useraname') password = models.CharField(max_length=100, verbose_name='password') # on forms add widget=forms.PasswordInput language = models.ForeignKey('Language', on_delete=models.PROTECT) country = models.ForeignKey('Country', on_delete=models.PROTECT) def __str__(self): return self.nickname class Meta: verbose_name = 'User' verbose_name_plural = 'Users' ordering = ['nickname'] class Language(models.Model): name = models.CharField(max_length=20, verbose_name='language name') def __str__(self): return self.name class Meta: verbose_name = 'Language' verbose_name_plural = 'Languages' class Country(models.Model): name_ua = models.CharField(max_length=20, verbose_name='country name in Ukranian') name_en = models.CharField(max_length=20, verbose_name='country name in English') name_ru = models.CharField(max_length=20, verbose_name='country name in Russian') def __str__(self): return self.name_en class Meta: verbose_name = 'Country' verbose_name_plural = 'Countries' ``` Serializers: ``` from rest_framework import serializers from main import models class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True, required=True) class Meta: model = models.HahaUser fields = ['nickname', 'password', 'password2', 'language', 'country', 'email', 'born'] extra_kwargs = { 'password': {'write_only': True} } def save(self): account = models.HahaUser.objects.create( email=self.validated_data['email'], nickname=self.validated_data['nickname'], language=self.validated_data['language'], born=self.validated_data['born'], country=self.validated_data['country'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) account.set_password(password) account.save() return account ``` views: ``` from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import RegistrationSerializer @api_view(['POST',]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = 'Successfully registrated a new user.' data['email'] = account.email data['nickname'] = account.nickname data['language'] = account.language data['born'] = account.born data['country'] = account.country else: data = serializer.errors return Response(data) ``` Full text of error: ``` Internal Server Error: /api/account/register/ Traceback (most recent call last): File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/rest_framework/response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/rest_framework/renderers.py", line 103, in render allow_nan=not self.strict, separators=separators File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/rest_framework/utils/json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "/usr/lib/python3.6/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/usr/lib/python3.6/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.6/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/rest_framework/utils/encoders.py", line 67, in default return super().default(obj) File "/usr/lib/python3.6/json/encoder.py", line 180, in default o.__class__.__name__) TypeError: Object of type 'Language' is not JSON serializable ``` I tried a lot of things: - add **json** method to language model - post data to field language\_id - create LanguageSerializer and work using it but nothing work Hope to your help))
2020/03/07
[ "https://Stackoverflow.com/questions/60578442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13023793/" ]
The result of account.language is an instance. So, in your `registration_view`, data['language'] got an instance rather than string or number. That's the reason why data's language is not JSON serializable. Based on your requirements, you can change it to `data['language'] = account.language.name`
As exception says, `language` is an object of `Language` model and it's not a primitive type. So you should use some attributes of Language model like `language_id` or `language_name` instead of language object. ```py from rest_framework import serializers from main import models class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True, required=True) language_name = serializers.CharField(source='language.name') class Meta: model = models.HahaUser fields = ['nickname', 'password', 'password2', 'language_name', 'country', 'email', 'born'] extra_kwargs = { 'password': {'write_only': True} } def save(self): account = models.HahaUser.objects.create( email=self.validated_data['email'], nickname=self.validated_data['nickname'], language=self.validated_data['language_name'], born=self.validated_data['born'], country=self.validated_data['country'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) account.set_password(password) account.save() return account ``` **NOTE:** If you fix Language serializable error, You'll get another exception for `Country` too.
60,578,442
When I tried to add value of language python3 returns error that this object is not JSON serializible. models: ``` from django.db import models from django.contrib.auth.models import AbstractUser, AbstractBaseUser class Admin(AbstractUser): class Meta(AbstractUser.Meta): pass class HahaUser(AbstractBaseUser): is_admin = models.BooleanField(default=False, verbose_name='is administrator?') born = models.PositiveSmallIntegerField(verbose_name='born year') rating = models.PositiveIntegerField(default=0, verbose_name='user rating') email = models.EmailField(verbose_name='email') nickname = models.CharField(max_length=32, verbose_name='useraname') password = models.CharField(max_length=100, verbose_name='password') # on forms add widget=forms.PasswordInput language = models.ForeignKey('Language', on_delete=models.PROTECT) country = models.ForeignKey('Country', on_delete=models.PROTECT) def __str__(self): return self.nickname class Meta: verbose_name = 'User' verbose_name_plural = 'Users' ordering = ['nickname'] class Language(models.Model): name = models.CharField(max_length=20, verbose_name='language name') def __str__(self): return self.name class Meta: verbose_name = 'Language' verbose_name_plural = 'Languages' class Country(models.Model): name_ua = models.CharField(max_length=20, verbose_name='country name in Ukranian') name_en = models.CharField(max_length=20, verbose_name='country name in English') name_ru = models.CharField(max_length=20, verbose_name='country name in Russian') def __str__(self): return self.name_en class Meta: verbose_name = 'Country' verbose_name_plural = 'Countries' ``` Serializers: ``` from rest_framework import serializers from main import models class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True, required=True) class Meta: model = models.HahaUser fields = ['nickname', 'password', 'password2', 'language', 'country', 'email', 'born'] extra_kwargs = { 'password': {'write_only': True} } def save(self): account = models.HahaUser.objects.create( email=self.validated_data['email'], nickname=self.validated_data['nickname'], language=self.validated_data['language'], born=self.validated_data['born'], country=self.validated_data['country'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) account.set_password(password) account.save() return account ``` views: ``` from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import RegistrationSerializer @api_view(['POST',]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = 'Successfully registrated a new user.' data['email'] = account.email data['nickname'] = account.nickname data['language'] = account.language data['born'] = account.born data['country'] = account.country else: data = serializer.errors return Response(data) ``` Full text of error: ``` Internal Server Error: /api/account/register/ Traceback (most recent call last): File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/rest_framework/response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/rest_framework/renderers.py", line 103, in render allow_nan=not self.strict, separators=separators File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/rest_framework/utils/json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "/usr/lib/python3.6/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/usr/lib/python3.6/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.6/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/rest_framework/utils/encoders.py", line 67, in default return super().default(obj) File "/usr/lib/python3.6/json/encoder.py", line 180, in default o.__class__.__name__) TypeError: Object of type 'Language' is not JSON serializable ``` I tried a lot of things: - add **json** method to language model - post data to field language\_id - create LanguageSerializer and work using it but nothing work Hope to your help))
2020/03/07
[ "https://Stackoverflow.com/questions/60578442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13023793/" ]
As exception says, `language` is an object of `Language` model and it's not a primitive type. So you should use some attributes of Language model like `language_id` or `language_name` instead of language object. ```py from rest_framework import serializers from main import models class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True, required=True) language_name = serializers.CharField(source='language.name') class Meta: model = models.HahaUser fields = ['nickname', 'password', 'password2', 'language_name', 'country', 'email', 'born'] extra_kwargs = { 'password': {'write_only': True} } def save(self): account = models.HahaUser.objects.create( email=self.validated_data['email'], nickname=self.validated_data['nickname'], language=self.validated_data['language_name'], born=self.validated_data['born'], country=self.validated_data['country'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) account.set_password(password) account.save() return account ``` **NOTE:** If you fix Language serializable error, You'll get another exception for `Country` too.
Thank you for help, but I'd solve it myself. I just add str() to foreign keys on my view where I generate JSON response. ``` from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import RegistrationSerializer @api_view(['POST',]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = 'Successfully registrated a new user.' data['email'] = account.email data['nickname'] = account.nickname data['language'] = str(account.language) data['born'] = account.born data['country'] = str(account.country) else: data = serializer.errors return Response(data) ```
60,578,442
When I tried to add value of language python3 returns error that this object is not JSON serializible. models: ``` from django.db import models from django.contrib.auth.models import AbstractUser, AbstractBaseUser class Admin(AbstractUser): class Meta(AbstractUser.Meta): pass class HahaUser(AbstractBaseUser): is_admin = models.BooleanField(default=False, verbose_name='is administrator?') born = models.PositiveSmallIntegerField(verbose_name='born year') rating = models.PositiveIntegerField(default=0, verbose_name='user rating') email = models.EmailField(verbose_name='email') nickname = models.CharField(max_length=32, verbose_name='useraname') password = models.CharField(max_length=100, verbose_name='password') # on forms add widget=forms.PasswordInput language = models.ForeignKey('Language', on_delete=models.PROTECT) country = models.ForeignKey('Country', on_delete=models.PROTECT) def __str__(self): return self.nickname class Meta: verbose_name = 'User' verbose_name_plural = 'Users' ordering = ['nickname'] class Language(models.Model): name = models.CharField(max_length=20, verbose_name='language name') def __str__(self): return self.name class Meta: verbose_name = 'Language' verbose_name_plural = 'Languages' class Country(models.Model): name_ua = models.CharField(max_length=20, verbose_name='country name in Ukranian') name_en = models.CharField(max_length=20, verbose_name='country name in English') name_ru = models.CharField(max_length=20, verbose_name='country name in Russian') def __str__(self): return self.name_en class Meta: verbose_name = 'Country' verbose_name_plural = 'Countries' ``` Serializers: ``` from rest_framework import serializers from main import models class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True, required=True) class Meta: model = models.HahaUser fields = ['nickname', 'password', 'password2', 'language', 'country', 'email', 'born'] extra_kwargs = { 'password': {'write_only': True} } def save(self): account = models.HahaUser.objects.create( email=self.validated_data['email'], nickname=self.validated_data['nickname'], language=self.validated_data['language'], born=self.validated_data['born'], country=self.validated_data['country'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) account.set_password(password) account.save() return account ``` views: ``` from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import RegistrationSerializer @api_view(['POST',]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = 'Successfully registrated a new user.' data['email'] = account.email data['nickname'] = account.nickname data['language'] = account.language data['born'] = account.born data['country'] = account.country else: data = serializer.errors return Response(data) ``` Full text of error: ``` Internal Server Error: /api/account/register/ Traceback (most recent call last): File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/rest_framework/response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/rest_framework/renderers.py", line 103, in render allow_nan=not self.strict, separators=separators File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/rest_framework/utils/json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "/usr/lib/python3.6/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/usr/lib/python3.6/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.6/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/home/dima/Стільниця/hahachat/lib/python3.6/site-packages/rest_framework/utils/encoders.py", line 67, in default return super().default(obj) File "/usr/lib/python3.6/json/encoder.py", line 180, in default o.__class__.__name__) TypeError: Object of type 'Language' is not JSON serializable ``` I tried a lot of things: - add **json** method to language model - post data to field language\_id - create LanguageSerializer and work using it but nothing work Hope to your help))
2020/03/07
[ "https://Stackoverflow.com/questions/60578442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13023793/" ]
The result of account.language is an instance. So, in your `registration_view`, data['language'] got an instance rather than string or number. That's the reason why data's language is not JSON serializable. Based on your requirements, you can change it to `data['language'] = account.language.name`
Thank you for help, but I'd solve it myself. I just add str() to foreign keys on my view where I generate JSON response. ``` from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import RegistrationSerializer @api_view(['POST',]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = 'Successfully registrated a new user.' data['email'] = account.email data['nickname'] = account.nickname data['language'] = str(account.language) data['born'] = account.born data['country'] = str(account.country) else: data = serializer.errors return Response(data) ```
47,978,878
Hi I am using APScheduler in a Django project. How can I plan a call of a function in python when the job is done? A callback function. I store job as Django models in DB. As it completes, I want to mark it as `completed=1` in the table.
2017/12/26
[ "https://Stackoverflow.com/questions/47978878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4537090/" ]
The easiest and generic way to do it would be to add your callback function to the end of the scheduled job. You can also build on top of the scheduler class to include a self.function\_callback() at the end of the tasks. Quick example: ``` def tick(): print('Tick! The time is: %s' % datetime.now()) time.sleep(10) function_cb() def function_cb(): print "CallBack Function" #Do Something if __name__ == '__main__': scheduler = AsyncIOScheduler() scheduler.add_job(tick, 'interval', seconds=2) scheduler.start() print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) # Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed. try: asyncio.get_event_loop().run_forever() except (KeyboardInterrupt, SystemExit): pass scheduler.shutdown(wait=False) ```
[Listener](https://apscheduler.readthedocs.io/en/latest/userguide.html#scheduler-events) allows to hook various [events](https://apscheduler.readthedocs.io/en/latest/modules/events.html#event-codes) of APScheduler. I have succeeded to get the *next run time* of my job using EVENT\_JOB\_SUBMITTED. (Updated) I confirmed whether it is able to hook these events. ``` from datetime import datetime import os from logging import getLogger, StreamHandler, Filter, basicConfig, INFO from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR logger = getLogger(__name__) logger.setLevel(INFO) def tick(): now = datetime.now() logger.info('Tick! The time is: %s' % now) if now.second % 2 == 0: raise Exception('now.second % 2 == 0') if __name__ == '__main__': sh = StreamHandler() sh.addFilter(Filter('__main__')) basicConfig( handlers = [sh], format='[%(asctime)s] %(name)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) def my_listener(event): if event.exception: logger.info('The job crashed') else: logger.info('The job worked') scheduler = BlockingScheduler() scheduler.add_job(tick, 'interval', seconds=3) scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR) print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) try: scheduler.start() except (KeyboardInterrupt, SystemExit): pass ``` When this code is executed, the output is as follows: ``` Interrupt: Press ENTER or type command to continue Press Ctrl+C to exit [2019-11-30 09:24:12] __main__ INFO: Tick! The time is: 2019-11-30 09:24:12.663142 [2019-11-30 09:24:12] __main__ INFO: The job crashed [2019-11-30 09:24:15] __main__ INFO: Tick! The time is: 2019-11-30 09:24:15.665845 [2019-11-30 09:24:15] __main__ INFO: The job worked [2019-11-30 09:24:18] __main__ INFO: Tick! The time is: 2019-11-30 09:24:18.663215 [2019-11-30 09:24:18] __main__ INFO: The job crashed ```
1,780,066
hopefully someone here can shed some light on my issue :D I've been creating a Windows XP service in python that is designed to monitor/repair selected Windows/Application/Service settings, atm I have been focusing on default DCOM settings. The idea is to backup our default configuration within another registry key for reference. Every 30 minutes (currently every 30 seconds for testing) I would like the service to query the current windows default DCOM settings from the registry and compare the results to the default configuration. If discrepancies are found, the service will replace the current windows settings with the custom configuration settings. I have already created/tested my class to handle the registry checking/repairing and so far it runs flawlessly.. Until I compile it to an exe and run it as a service. The service itself starts up just fine and it seems to loop every 30 seconds as defined, but my module to handle the registry checking/repairing does not seem to get run as specified. I created a log file and was able to obtain the following error: Traceback (most recent call last): File "DCOMMon.pyc", line 52, in RepairDCOM File "DCOMMon.pyc", line 97, in GetDefaultDCOM File "pywmi.pyc", line 396, in **call** File "pywmi.pyc", line 189, in handle\_com\_error x\_wmi: -0x7ffdfff7 - Exception occurred. Error in: SWbemObjectEx -0x7ffbfe10 - When I stop the service and run the exe manually, specifying the debug argument: **DCOMMon.exe debug**, the service starts up and runs just fine, performing all tasks as expected. The only differences that I can see is that the service starts the process as the SYSTEM user instead of the logged on user which leads me to believe (just guessing here) that it might be some sort of missed permission/policy for the SYSTEM user? I have tested running the service as another user but there was no difference there either. Other thoughts were to add the wmi service to the dependencies of my service but truthfully I have no idea what that would do :P This is the first time I've attempted to create a windows service in python, without using something like srvany.exe. I have spent the better part of last night and today trying to google around and find some information regarding py2exe and wmi compatibility but so far the suggestions I have found have not helped solve the above issue. Any suggestions would be appreciated. PS: Don't hate me for the poor logging, I cut/pasted my logger from a different scripts and I have not made the appropriate changes, it might double up each line :P. The log file can be found here: "%WINDIR%\system32\DCOMMon.log" **UPDATE** I have tried to split this project up into two exe files instead of one. Let the service make and external call to the other exe to run the wmi registry portion. Again, when running with the **debug** arg it works just fine, but when I start it as a service it logs the same error message. More and more this is starting to look like a permission issue an not a program issue :( **UPDATE** **DCOMMon.py - Requires pywin32, wmi (renamed to pywmi),** ``` # DCOMMon.py import win32api, win32service, win32serviceutil, win32event, win32evtlogutil, win32traceutil import logging, logging.handlers, os, re, sys, thread, time, traceback, pywmi # pywmi == wmi module renamed as suggested in online post import _winreg as reg DCOM_DEFAULT_CONFIGURATION = ["EnableDCOM", "EnableRemoteConnect", "LegacyAuthenticationLevel", "LegacyImpersonationLevel", "DefaultAccessPermission", "DefaultLaunchPermission", "MachineAccessRestriction", "MachineLaunchRestriction"] DCOM_DEFAULT_ACCESS_PERMISSION = [1, 0, 4, 128, 92, 0, 0, 0, 108, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 2, 0, 72, 0, 3, 0, 0, 0, 0, 0, 24, 0, 7, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 0, 0, 20, 0, 7, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 5, 7, 0, 0, 0, 0, 0, 20, 0, 7, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0] DCOM_DEFAULT_LAUNCH_PERMISSION = [1, 0, 4, 128, 132, 0, 0, 0, 148, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 2, 0, 112, 0, 5, 0, 0, 0, 0, 0, 24, 0, 31, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 0, 0, 20, 0, 31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 5, 7, 0, 0, 0, 0, 0, 20, 0, 31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 20, 0, 31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 5, 4, 0, 0, 0, 0, 0, 20, 0, 31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0] DCOM_MACHINE_ACCESS_RESTRICTION = [1, 0, 4, 128, 68, 0, 0, 0, 84, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 2, 0, 48, 0, 2, 0, 0, 0, 0, 0, 20, 0, 3, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 5, 7, 0, 0, 0, 0, 0, 20, 0, 7, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0] DCOM_MACHINE_LAUNCH_RESTRICTION = [1, 0, 4, 128, 72, 0, 0, 0, 88, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 2, 0, 52, 0, 2, 0, 0, 0, 0, 0, 24, 0, 31, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 0, 0, 20, 0, 31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0] COMPUTER = os.environ["COMPUTERNAME"] REGISTRY = pywmi.WMI(COMPUTER, namespace="root/default").StdRegProv LOGFILE = os.getcwd() + "\\DCOMMon.log" def Logger(title, filename): logger = logging.getLogger(title) logger.setLevel(logging.DEBUG) handler = logging.handlers.RotatingFileHandler(filename, maxBytes=0, backupCount=0) handler.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) return logger def LogIt(filename=LOGFILE): #try: # if os.path.exists(filename): # os.remove(filename) #except: # pass log = Logger("DCOMMon", filename) tb = str(traceback.format_exc()).split("\n") log.error("") for i, a in enumerate(tb): if a.strip() != "": log.error(a) class Monitor: def RepairDCOM(self): try: repaired = {} dict1 = self.GetDefaultDCOM() dict2 = self.GetCurrentDCOM() compared = self.CompareDCOM(dict1, dict2) for dobj in DCOM_DEFAULT_CONFIGURATION: try: compared[dobj] if dobj == "LegacyAuthenticationLevel" or dobj == "LegacyImpersonationLevel": REGISTRY.SetDWORDValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=dobj, uValue=dict1[dobj]) elif dobj == "DefaultAccessPermission" or dobj == "DefaultLaunchPermission" or \ dobj == "MachineAccessRestriction" or dobj == "MachineLaunchRestriction": REGISTRY.SetBinaryValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=dobj, uValue=dict1[dobj]) elif dobj == "EnableDCOM" or dobj == "EnableRemoteConnect": REGISTRY.SetStringValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=dobj, sValue=dict1[dobj]) except KeyError: pass except: LogIt(LOGFILE) def CompareDCOM(self, dict1, dict2): compare = {} for (key, value) in dict2.iteritems(): try: if dict1[key] != value: compare[key] = value except KeyError: compare[key] = value return compare def GetCurrentDCOM(self): current = {} for name in REGISTRY.EnumValues(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole")[1]: value = REGISTRY.GetStringValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=str(name))[1] if value: current[str(name)] = str(value) else: value = REGISTRY.GetDWORDValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=str(name))[1] if not value: value = REGISTRY.GetBinaryValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=str(name))[1] current[str(name)] = value return current def GetDefaultDCOM(self): default = {} # Get Default DCOM Settings for name in REGISTRY.EnumValues(hDefKey=reg.HKEY_CURRENT_USER, sSubKeyName="Software\\DCOMMon")[1]: value = REGISTRY.GetStringValue(hDefKey=reg.HKEY_CURRENT_USER, sSubKeyName="Software\\DCOMMon", sValueName=str(name))[1] if value: default[str(name)] = str(value) else: value = REGISTRY.GetDWORDValue(hDefKey=reg.HKEY_CURRENT_USER, sSubKeyName="Software\\DCOMMon", sValueName=str(name))[1] if not value: value = REGISTRY.GetBinaryValue(hDefKey=reg.HKEY_CURRENT_USER, sSubKeyName="Software\\DCOMMon", sValueName=str(name))[1] default[str(name)] = value return default class DCOMMon(win32serviceutil.ServiceFramework): _svc_name_ = "DCOMMon" _svc_display_name_ = "DCOM Monitoring Service" _svc_description_ = "DCOM Monitoring Service" _svc_deps_ = ["EventLog"] def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.isAlive = True def SvcDoRun(self): import servicemanager servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ': DCOM Monitoring Service - Service Started')) self.timeout=30000 # In milliseconds while self.isAlive: rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout) if rc == win32event.WAIT_OBJECT_0: break else: servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ': DCOM Monitoring Service - Examining DCOM Configuration')) Monitor().RepairDCOM() servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, ': DCOM Monitoring Service - Service Stopped')) return def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) LOG.close() self.isAlive = False return #def ctrlHandler(ctrlType): # return True if __name__ == '__main__': # win32api.SetConsoleCtrlHandler(ctrlHandler, True) #print Monitor().RepairDCOM() win32serviceutil.HandleCommandLine(DCOMMon) ``` **DCOMMon\_setup.py - Requires py2exe (self executable, no need for py2exe arg)** ``` # DCOMMon_setup.py (self executable, no need for py2exe arg) # Usage: # DCOMMon.exe install # DCOMMon.exe start # DCOMMon.exe stop # DCOMMon.exe remove # DCOMMon.exe debug # you can see output of this program running python site-packages\win32\lib\win32traceutil try: # (snippet I found somewhere, searching something??) # if this doesn't work, try import modulefinder import py2exe.mf as modulefinder import win32com, sys for p in win32com.__path__[1:]: modulefinder.AddPackagePath("win32com", p) for extra in ["win32com.shell"]: #,"win32com.mapi" __import__(extra) m = sys.modules[extra] for p in m.__path__[1:]: modulefinder.AddPackagePath(extra, p) except ImportError: print "NOT FOUND" from distutils.core import setup import py2exe, sys if len(sys.argv) == 1: sys.argv.append("py2exe") #sys.argv.append("-q") class Target: def __init__(self, **kw): self.__dict__.update(kw) # for the versioninfo resources self.version = "1.0.0.1" self.language = "English (Canada)" self.company_name = "Whoever" self.copyright = "Nobody" self.name = "Nobody Home" myservice = Target( description = 'DCOM Monitoring Service', modules = ['DCOMMon'], cmdline_style='pywin32' #dest_base = 'DCOMMon' ) setup( options = {"py2exe": {"compressed": 1, "bundle_files": 1, "ascii": 1, "packages": ["encodings"]} }, console=["DCOMMon.py"], zipfile = None, service=[myservice] ) ```
2009/11/22
[ "https://Stackoverflow.com/questions/1780066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/94071/" ]
So I guess it's time to admit my stupidity.... :P It turns out this was not a python issue, py2exe issue, nor a WMI issue. :( This was more or less a simple permission issue. So simple I overlooked it for the better part of a month. :( Rule of thumb, if you want to create a service that calls to specific registry keys to obtain (in this case) default configuration settings.... maybe... **JUST MAYBE....** One should place their default key within the **"HKEY\_LOCAL\_MACHINE"**, instead of **"HKEY\_CURRENT\_USER"**?? :P Yeah, it's that simple... I should have remembered this rule from other projects I have worked on in the past. When you are running as the Local System account, simply put, there is no **"HKEY\_CURRENT\_USER"** subkey to access. If you absolutely have to access a specific user's **"HKEY\_CURRENT\_USER"** subkey, I would guess the only way would be to impersonate the user. Luckily for me this is not necessary for what I am attempting to accomplish. The below link provided me with what I needed to jog my memory and fix the issue: <http://msdn.microsoft.com/en-us/library/ms684190%28VS.85%29.aspx> So to make a long story short, I migrated all of my default values over to **"HKEY\_LOCAL\_MACHINE\SOFTWARE"** subkey and my service is working perfectly. :D Thanks for your help guys but this problem is solved ;)
I am not an expert at this, but here are my two cents worth: [This article](http://www.firebirdsql.org/devel/python/docs/3.3.0/installation.html) tells me that you might need to be logged in as someone with the required target system permissions. However, I find that a little excessive. Have you tried compiling your script from the command line while running the command prompt as the administrator of the computer - so that you can unlock all permissions (on Windows Vista and Windows 7, this is achieved by right clicking on the command prompt icon in the start menu and clicking on "run as administrator"). Hope this helps
69,153,402
Lets say I have a list that references another list, as follows: ``` list1 = [1,2,3,4,5] list2 = [list1[0], list1[1], list1[2]] ``` I wish to interact with list1 through list2, as follows: ``` list2[1] = 'a' print(list1[1]) ``` and that result should be 'a'. Is this possible? Help me python geniuses
2021/09/12
[ "https://Stackoverflow.com/questions/69153402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14272990/" ]
What we do is not derive `ListOfSomething` from the list base class. We would make `ListOfSomething` the singleton and have a generic list class. ```cpp class ListOfSomething { public: static ListOfSomething& instance() { static ListOfSomething los; return los; } // Obtain a reference to the list. ListOf<Something>& get_list() { return the_list; } private: // Hide the constructor to force the use of the singleton instance. ListOfSomething() {} // The actual list of objects. ListOf<Something> the_list; // Add your properties. }; ``` An alternative would be to pass the type of the derived class to the base class. It is a bit obfuscated but will work. This is often used in [singleton base classes](https://stackoverflow.com/questions/41328038/singleton-template-as-base-class-in-c). ```cpp template <class T, class L> class ListOf<T> { public: // I would advice to return a reference not a pointer. static L& method() { static L list; return L; } private: // Hide the constructor. ListOf(); ~ListOf(); }; ``` Next in your derived class: ``` class ListOfSomething : public ListOf<Something, ListOfSomething> { // To allow the construction of this object with private constructor in the base class. friend class ListOf<Something, ListOfSomething>; public: // Add your public functions here. private: // Hide the constructor and destructor. ListOfSomething(); ~ListOfSomething(); }; ```
As explained by Bart, the trick here is to pass the name of the derived class as a template parameter. Here is the final form of the class that works as originally desired: ``` template <class T> class ListOf<T> { public: static T *method(); }; ``` and you invoke it like this ``` class ListOfSomething : public ListOf<ListOfSomething> { public: int payload; }; ``` Thus, the compiler is happy with: ``` ListOfSomething *ptr; ptr = ListOfSomething::method(); ```
45,561,366
I'm a beginner at video processing using python. I have a raw video data captured from a camera and I need to check whether the video has bright or dark frames in it. So far what I have achieved is I can read the raw video using numpy in python. Below is my code. ``` import numpy as np fd = open('my_video_file.raw', 'rb') rows = 4800 cols = 6400 f = np.fromfile(fd, dtype=np.uint8,count = rows*cols) im = f.reshape((rows,cols)) #notice row, column format print im fd.close() ``` Output : ``` [[ 81 82 58 ..., 0 0 0] [ 0 0 0 ..., 0 0 0] [ 0 0 0 ..., 0 0 0] ..., [141 128 136 ..., 1 2 2] [ 40 39 35 ..., 192 192 192] [190 190 190 ..., 74 60 60]] ``` Based on the array or numpy output , is it possible to check whether the raw video data has dark(less bright) frames or not. Also please tell me what does the numpy output (print im) mean ? If you have any links which I can refer to, its most welcome.
2017/08/08
[ "https://Stackoverflow.com/questions/45561366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4680053/" ]
If you have colorfull frames with red, green and blue channels, i.e NxMx3 matrix then you can convert this matrix from RGB representation to HSV (Hue, Saturation, Value) representation which is also will be NxMx3 matrix. Then you can take Value page from this matrix, i.e. third channel of this matrix and calculate average of all elements in this matrix. Put any threshold like 0.5 and if average is less than this value then this frame can be considered as dark. Read about HSV [here](https://en.wikipedia.org/wiki/HSL_and_HSV). To convert RGB vector to HSV vector you can use [matplotlib.colors.rgb\_to\_hsv(arr)](http://matplotlib.org/api/colors_api.html#matplotlib.colors.rgb_to_hsv) function.
Just a little insight on your problem. (You might want to read up a little more on digital image representation, [e.g. here](http://pippin.gimp.org/image_processing/chap_dir.html)). The frames of your video are read in in `uint8` format, i.e. pixels are encoded with values ranging from 0 to 255. In general, higher values represent brighter pixels. Depending on your video you can have colored or non-colored frames as mentioned by @Batyrkhan Saduanov. So what you want to do is define minimum and maximum levels to declare a frame as "dark" or "bright". In case of a non-colored you can easily use the mean pixel values of each frame, an asign threshold levels as in: ![if](https://latex.codecogs.com/gif.latex?img%20%3D%20%5Cleft%5C%7B%5Cbegin%7Bmatrix%7D%20%5Ctextup%7B%22bright%22%20if%20%7D%5Cfrac%7B1%7D%7Bx%5Ccdot%20y%7D%5Csum_%7Bx%2Cy%7D%28img_%7Bx%2Cy%7D%29%20%3E%20thr_%7Bbright%7D%5C%5C%20%5Ctextup%7B%22dark%22%20if%20%7D%5Cfrac%7B1%7D%7Bx%5Ccdot%20y%7D%5Csum_%7Bx%2Cy%7D%28img_%7Bx%2Cy%7D%29%20%3C%20thr_%7Bdark%7D%5C%5C%20%5Ctextup%7B%22normal%22%20otherwise%7D%20%5Cend%7Bmatrix%7D%5Cright.)
55,713,339
I'm trying to implement the following formula in python for X and Y points [![enter image description here](https://i.stack.imgur.com/Lv0au.png)](https://i.stack.imgur.com/Lv0au.png) I have tried following approach ``` def f(c): """This function computes the curvature of the leaf.""" tt = c n = (tt[0]*tt[3] - tt[1]*tt[2]) d = (tt[0]**2 + tt[1]**2) k = n/d R = 1/k # Radius of Curvature return R ``` There is something incorrect as it is not giving me correct result. I think I'm making some mistake while computing derivatives in first two lines. How can I fix that? Here are some of the points which are in a data frame: ``` pts = pd.DataFrame({'x': x, 'y': y}) x y 0.089631 97.710199 0.089831 97.904541 0.090030 98.099313 0.090229 98.294513 0.090428 98.490142 0.090627 98.686200 0.090827 98.882687 0.091026 99.079602 0.091225 99.276947 0.091424 99.474720 0.091623 99.672922 0.091822 99.871553 0.092022 100.070613 0.092221 100.270102 0.092420 100.470020 0.092619 100.670366 0.092818 100.871142 0.093017 101.072346 0.093217 101.273979 0.093416 101.476041 0.093615 101.678532 0.093814 101.881451 0.094013 102.084800 0.094213 102.288577 pts_x = np.gradient(x_c, t) # first derivatives pts_y = np.gradient(y_c, t) pts_xx = np.gradient(pts_x, t) # second derivatives pts_yy = np.gradient(pts_y, t) ``` After getting the derivatives I am putting the derivatives x\_prim, x\_prim\_prim, y\_prim, y\_prim\_prim in another dataframe using the following code: ``` d = pd.DataFrame({'x_prim': pts_x, 'y_prim': pts_y, 'x_prim_prim': pts_xx, 'y_prim_prim':pts_yy}) ``` after having everything in the data frame I am calling function for each row of the data frame to get curvature at that point using following code: ``` # Getting the curvature at each point for i in range(len(d)): temp = d.iloc[i] c_temp = f(temp) curv.append(c_temp) ```
2019/04/16
[ "https://Stackoverflow.com/questions/55713339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5347207/" ]
You do not specify exactly what the structure of the parameter `pts` is. But it seems that it is a two-dimensional array where each row has two values `x` and `y` and the rows are the points in your curve. That itself is problematic, since [the documentation](https://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html) is not quite clear on what exactly is returned in such a case. But you clearly are not getting the derivatives of `x` or `y`. If you supply only one array to `np.gradient` then numpy assumes that the points are evenly spaced with a distance of one. But that is probably not the case. The meaning of `x'` in your formula is the derivative of `x` *with respect to `t`*, the parameter variable for the curve (which is separate from the parameters to the computer functions). But you never supply the values of `t` to numpy. The values of `t` must be the second parameter passed to the `gradient` function. So to get your derivatives, split the `x`, `y`, and `t` values into separate one-dimensional arrays--lets call them `x` and `y` and `t`. Then get your first and second derivatives with ``` pts_x = np.gradient(x, t) # first derivatives pts_y = np.gradient(y, t) pts_xx = np.gradient(pts_x, t) # second derivatives pts_yy = np.gradient(pts_y, t) ``` Then continue from there. You no longer need the `t` values to calculate the curvatures, which is the point of the formula you are using. Note that `gradient` is not really designed to calculate the second derivatives, and it absolutely should not be used to calculate third or higher-order derivatives. More complex formulas are needed for those. Numpy's `gradient` uses "second order accurate central differences" which are pretty good for the first derivative, poor for the second derivative, and worthless for higher-order derivatives.
I think your problem is that x and y are arrays of double values. The array x is the independent variable; I'd expect it to be sorted into ascending order. If I evaluate y[i], I expect to get the value of the curve at x[i]. When you call that numpy function you get an array of derivative values that are the same shape as the (x, y) arrays. If there are n pairs from (x, y), then ``` y'[i] gives the value of the first derivative of y w.r.t. x at x[i]; y''[i] gives the value of the second derivative of y w.r.t. x at x[i]. ``` The curvature k will also be an array with n points: ``` k[i] = abs(x'[i]*y''[i] -y'[i]*x''[i])/(x'[i]**2 + y'[i]**2)**1.5 ``` Think of x and y as both being functions of a parameter t. x' = dx/dt, etc. This means curvature k is also a function of that parameter t. I like to have a well understood closed form solution available when I program a solution. ``` y(x) = sin(x) for 0 <= x <= pi y'(x) = cos(x) y''(x) = -sin(x) k = sin(x)/(1+(cos(x))**2)**1.5 ``` Now you have a nice formula for curvature as a function of x. If you want to parameterize it, use ``` x(t) = pi*t for 0 <= t <= 1 x'(t) = pi x''(t) = 0 ``` See if you can plot those and make your Python solution match it.
2,344,712
The hindrance we have to ship python is the large size of the standard library. Is there a minimal python distribution or an easy way to pick and choose what we want from the standard library? The platform is linux.
2010/02/26
[ "https://Stackoverflow.com/questions/2344712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282368/" ]
If all you want is to get the minimum subset you need (rather than build an `exe` which would constrain you to Windows systems), use the standard library module [modulefinder](http://docs.python.org/library/modulefinder.html) to list all modules your program requires (you'll get all dependencies, direct and indirect). Then you can `zip` all the relevant `.pyo` or `.pyc` files (depending on whether you run Python with or without the `-O` flag) and just use that zipfile as your `sys.path` (plus a directory for all the `.pyd` or `.so` native-code dynamic libraries you may need -- those need to live directly in the filesystem to let the OS load them in as needed, can't be loaded directly from a zipfile the way Python bytecode modules can, unfortunately).
Have you looked at [py2exe](http://www.py2exe.org/)? It provides a way to ship Python programs without requiring a Python installation.
2,344,712
The hindrance we have to ship python is the large size of the standard library. Is there a minimal python distribution or an easy way to pick and choose what we want from the standard library? The platform is linux.
2010/02/26
[ "https://Stackoverflow.com/questions/2344712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282368/" ]
Have you looked at [py2exe](http://www.py2exe.org/)? It provides a way to ship Python programs without requiring a Python installation.
Like Hank Gay and Alex Martelli suggest, you can use py2exe. In addition I would suggest looking into using something like [IronPython](http://ironpython.net/). Depending on your application, you can use libraries that are built into the .NET framework (or MONO if for Linux). This reduces your shipping size, but adds minimum requirements to your program. Further, if you are using functions from a library, you can use `from module import x` instead of doing a wildcard import. This reduces your ship size as well, but maybe not by too much Hope this helps
2,344,712
The hindrance we have to ship python is the large size of the standard library. Is there a minimal python distribution or an easy way to pick and choose what we want from the standard library? The platform is linux.
2010/02/26
[ "https://Stackoverflow.com/questions/2344712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282368/" ]
If all you want is to get the minimum subset you need (rather than build an `exe` which would constrain you to Windows systems), use the standard library module [modulefinder](http://docs.python.org/library/modulefinder.html) to list all modules your program requires (you'll get all dependencies, direct and indirect). Then you can `zip` all the relevant `.pyo` or `.pyc` files (depending on whether you run Python with or without the `-O` flag) and just use that zipfile as your `sys.path` (plus a directory for all the `.pyd` or `.so` native-code dynamic libraries you may need -- those need to live directly in the filesystem to let the OS load them in as needed, can't be loaded directly from a zipfile the way Python bytecode modules can, unfortunately).
Like Hank Gay and Alex Martelli suggest, you can use py2exe. In addition I would suggest looking into using something like [IronPython](http://ironpython.net/). Depending on your application, you can use libraries that are built into the .NET framework (or MONO if for Linux). This reduces your shipping size, but adds minimum requirements to your program. Further, if you are using functions from a library, you can use `from module import x` instead of doing a wildcard import. This reduces your ship size as well, but maybe not by too much Hope this helps
22,164,245
I'm using a java program to split an array among histogram bins. Now, I want to manually label the histogram bins. So - I want to convert some thing like the sequence: {-0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.5,1,1.5,2,2.5,4} into the following image - ![enter image description here](https://i.stack.imgur.com/HWb4W.png) Is there a way to do this using any software? I'm on Windows and some thing based on R, python, java or matlab would be awesome. I currently do it manually using mspaint.
2014/03/04
[ "https://Stackoverflow.com/questions/22164245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1826912/" ]
Well, the simplest approach is (Python): ``` import matplotlib.pyplot as plt d = [-0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.5,1,1.5,2,2.5,4] hist(d) plt.show() ``` As for putting special labels on the histogram, that's covered in the question: [Matplotlib - label each bin](https://stackoverflow.com/questions/6352740/matplotlib-label-each-bin). I'm guessing you want to keep it simple, so you can do this: ``` import matplotlib.pyplot as plt fig, ax = plt.subplots() d = [-0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.5,1,1.5,2,2.5,4] counts, bins, patches = ax.hist(d) ax.set_xticks(bins) plt.show() ```
On the java side, an useful (and not too big) library could be GRAL <http://trac.erichseifert.de/gral/> An histogram example is here: <http://trac.erichseifert.de/gral/browser/gral-examples/src/main/java/de/erichseifert/gral/examples/barplot/HistogramPlot.java> And specifically about axis rotation: <http://www.erichseifert.de/dev/gral/0.10/apidocs/de/erichseifert/gral/plots/axes/AxisRenderer.html#setLabelRotation%28double%29>
22,164,245
I'm using a java program to split an array among histogram bins. Now, I want to manually label the histogram bins. So - I want to convert some thing like the sequence: {-0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.5,1,1.5,2,2.5,4} into the following image - ![enter image description here](https://i.stack.imgur.com/HWb4W.png) Is there a way to do this using any software? I'm on Windows and some thing based on R, python, java or matlab would be awesome. I currently do it manually using mspaint.
2014/03/04
[ "https://Stackoverflow.com/questions/22164245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1826912/" ]
To arrange data in bins then display them with equal width bars you can use `matplotlib` in Python The previous Python answer doesn't bin the values, set them at equal distance nor handle (-infinity, 0.9) bin The code here hopefully does: ```py import matplotlib.pyplot as plt import numpy as np # data and bins d = [-0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, - 0.2, -0.1, 0, 0.1, 0.5, 1, 1.5, 2, 2.5, 4] bin_boundaries = [-0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.5, 1, 1.5, 2, 2.5, 4] # Account for (-inf, min(d)) bin added_inf = False min_d = min(d) if min_d < bin_boundaries[0]: bin_boundaries.insert(0, min_d) added_inf = True # Bin data fig, ax = plt.subplots() counts, bins, _ = ax.hist(d, bins=bin_boundaries) plt.close() # Generate tick labels and handle (-inf, min(d)) bin bins_str = [f"{bins[i]} to {bins[i+1]}" for i in range(len(bins) - 1)] if added_inf: bins_str[0] = f"-inf to {bins[1]}" else: bins = np.insert(bins, 0, [bins[0] - 1]) counts = np.insert(counts, 0, [0]) bins_str.insert(0, f"-inf to {bins[1]}") fig, ax = plt.subplots() # Ajdust size of plot fig.set_dpi(150) # Draw graph with bins_str as labels ax.bar(bins_str, counts, width=1.0) # Make labels vertical plt.xticks(rotation=90, ha='center') plt.show() plt.close() ```
On the java side, an useful (and not too big) library could be GRAL <http://trac.erichseifert.de/gral/> An histogram example is here: <http://trac.erichseifert.de/gral/browser/gral-examples/src/main/java/de/erichseifert/gral/examples/barplot/HistogramPlot.java> And specifically about axis rotation: <http://www.erichseifert.de/dev/gral/0.10/apidocs/de/erichseifert/gral/plots/axes/AxisRenderer.html#setLabelRotation%28double%29>
35,050,766
I am currently using Python and R together (using rmagic/rpy2) to help select different user input variables for a certain type of analysis. I have read a csv file and created a dataframe in R. What I have also done is allowed the users to input a number of variables of which the names must match those in the header (using Python). For example if I create a data frame as such `%R data1 <- read.csv(filename, header =T)` I then have a number of user input variables that are currently strings in pythons that would look like this. ``` var_1 = 'data1$age' var_2 = 'data1$sex' ``` How can I then use this string as runable code in R to reach into the correct column of the data frame as such: ``` %R variable1 <- data1$sex ``` Currently I have tried the assign function and others (I understand this might be far from the mark) but I always just get it coming out as such: ``` %R -i var_1 assign('variable1', var_1) %R print(variable1) "data1$age" ``` I understand that I could assign values etc in R but I'm questioning if it is possible to turn a string into a runnable bit of code that could reach into a data.frame.
2016/01/28
[ "https://Stackoverflow.com/questions/35050766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5849513/" ]
Consider having Python call the R script as child process via command line passing the string variables as arguments. In R, use the double bracket column reference to use strings: **Python** Script *(using subprocess module)* ``` import subprocess var_1 = 'age' var_2 = 'sex' Rfilename = '/path/to/SomeScript.R' # BELOW ASSUMES RScript IS A SYSTEM PATH VARIABLE p = subprocess.Popen(['RScript', Rfilename, var1, var2]) ``` **R** Script ``` args <-commandArgs(trailingOnly=T) var_1 <- as.character(args[1]) var_2 <- as.character(args[2]) data1 <- read.csv(filename, header =T) variable1 <- data1[[var_1]] variable2 <- data1[[var_2]] ```
Yes it is possible: ``` var_1 <- "head(iris$Species)" eval(parse(text=var_1)) # [1] setosa setosa setosa setosa setosa setosa # Levels: setosa versicolor virginica ```
54,396,064
I would like to ask how to exchange dates from loop in to an array in python? I need an array of irregular, random dates with hours. So, I prepared a solution: ``` import datetime import radar r2 =() for a in range(1,10): r2 = r2+(radar.random_datetime(start='1985-05-01', stop='1985-05-04'),) r3 = list(r2) print(r3) ``` As the result I get a list like: ``` [datetime.datetime(1985, 5, 3, 17, 59, 13), datetime.datetime(1985, 5, 2, 15, 58, 30), datetime.datetime(1985, 5, 2, 9, 46, 35), datetime.datetime(1985, 5, 3, 10, 5, 45), datetime.datetime(1985, 5, 2, 4, 34, 43), datetime.datetime(1985, 5, 3, 9, 52, 51), datetime.datetime(1985, 5, 2, 22, 7, 17), datetime.datetime(1985, 5, 1, 15, 28, 14), datetime.datetime(1985, 5, 3, 13, 33, 56)] ``` But I need strings in the list like: ``` list2 = ['1985-05-02 08:48:46','1985-05-02 10:47:56','1985-05-03 22:07:11', '1985-05-03 22:07:11','1985-05-01 03:23:43'] ```
2019/01/28
[ "https://Stackoverflow.com/questions/54396064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10842659/" ]
You can convert the datetime to a string with [`str()`](https://docs.python.org/3/library/stdtypes.html#str) like: ### Code: ``` str(radar.random_datetime(start='1985-05-01', stop='1985-05-04')) ``` ### Test Code: ``` import radar r2 = () for a in range(1, 10): r2 = r2 + (str( radar.random_datetime(start='1985-05-01', stop='1985-05-04')),) r3 = list(r2) print(r3) ``` ### Results: ``` ['1985-05-01 21:06:29', '1985-05-01 04:43:11', '1985-05-02 13:51:03', '1985-05-03 03:20:44', '1985-05-03 19:59:14', '1985-05-02 21:50:34', '1985-05-01 04:13:50', '1985-05-03 23:28:36', '1985-05-02 15:56:23'] ```
Use [strftime](http://docs.python.org/2/library/time.html#time.strftime) to convert the date generated by radar before adding it to the list. e.g. ``` import datetime import radar r2 =() for a in range(1,10): t=datetime.datetime(radar.random_datetime(start='1985-05-01', stop='1985-05-04')) r2 = r2+(t.strftime('%Y-%m-%d %H:%M:%S'),) r3 = list(r2) print(r3) ```
23,086,078
I have list that has 20 coordinates (x and y coordinates). I can calculate the distance between any two coordinates, but I have a hard time writing an algorithm that will iterate through the list and calculate the distance between the first node and every other node. for example, ``` ListOfCoordinates = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)] ``` In this case I need a for loop that will interate the list and calculate the distance between the first coordinate and the second coordinates, distance between first coordinate and third coordinate, etc. I am in need of an algorithm to help me out, then I will transform it into a python code. Thanks Thanks for ll the feedback. It's been helpful.
2014/04/15
[ "https://Stackoverflow.com/questions/23086078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3536195/" ]
Whenever you need something combinatorics-oriented ("I need first and second, then first and third, then...") chances are the `itertools` module has what you need. ``` from math import hypot def distance(p1,p2): """Euclidean distance between two points.""" x1,y1 = p1 x2,y2 = p2 return hypot(x2 - x1, y2 - y1) from itertools import combinations list_of_coords = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)] [distance(*combo) for combo in combinations(list_of_coords,2)] Out[29]: [2.8284271247461903, 5.656854249492381, 8.48528137423857, 11.313708498984761, 14.142135623730951, 2.8284271247461903, 5.656854249492381, 8.48528137423857, 11.313708498984761, 2.8284271247461903, 5.656854249492381, 8.48528137423857, 2.8284271247461903, 5.656854249492381, 2.8284271247461903] ``` edit: Your question is a bit confusing. Just in case you only want the first point compared against the other points: ``` from itertools import repeat pts = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)] [distance(*pair) for pair in zip(repeat(pts[0]),pts[1:])] Out[32]: [2.8284271247461903, 5.656854249492381, 8.48528137423857, 11.313708498984761, 14.142135623730951] ``` But usually in this type of problem you care about *all* the combinations so I'll leave the first answer up there.
``` In [6]: l = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)] In [7]: def distance(a, b): return (a[0] - b[0], a[1] - b[1]) ...: In [8]: for m in l[1:]: print(distance(l[0], m)) ...: (-2, -2) (-4, -4) (-6, -6) (-8, -8) (-10, -10) ``` Of course you would have to adapt `distance` to your needs.
23,086,078
I have list that has 20 coordinates (x and y coordinates). I can calculate the distance between any two coordinates, but I have a hard time writing an algorithm that will iterate through the list and calculate the distance between the first node and every other node. for example, ``` ListOfCoordinates = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)] ``` In this case I need a for loop that will interate the list and calculate the distance between the first coordinate and the second coordinates, distance between first coordinate and third coordinate, etc. I am in need of an algorithm to help me out, then I will transform it into a python code. Thanks Thanks for ll the feedback. It's been helpful.
2014/04/15
[ "https://Stackoverflow.com/questions/23086078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3536195/" ]
Whenever you need something combinatorics-oriented ("I need first and second, then first and third, then...") chances are the `itertools` module has what you need. ``` from math import hypot def distance(p1,p2): """Euclidean distance between two points.""" x1,y1 = p1 x2,y2 = p2 return hypot(x2 - x1, y2 - y1) from itertools import combinations list_of_coords = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)] [distance(*combo) for combo in combinations(list_of_coords,2)] Out[29]: [2.8284271247461903, 5.656854249492381, 8.48528137423857, 11.313708498984761, 14.142135623730951, 2.8284271247461903, 5.656854249492381, 8.48528137423857, 11.313708498984761, 2.8284271247461903, 5.656854249492381, 8.48528137423857, 2.8284271247461903, 5.656854249492381, 2.8284271247461903] ``` edit: Your question is a bit confusing. Just in case you only want the first point compared against the other points: ``` from itertools import repeat pts = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)] [distance(*pair) for pair in zip(repeat(pts[0]),pts[1:])] Out[32]: [2.8284271247461903, 5.656854249492381, 8.48528137423857, 11.313708498984761, 14.142135623730951] ``` But usually in this type of problem you care about *all* the combinations so I'll leave the first answer up there.
You can create a `distance` function that takes two tuples, which are coordinate pairs, as parameters. ``` def distance(p1, p2): return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) ``` Since you only need an algorithm to calculate distances between the *first* node and every other node, create a loop that cycles through each of your `ListOfCoordinates`: ``` for i in range(1, len(ListOfCoordinates)): # you can use print or return, depending on your needs print distance(ListOfCoordinates[0], ListOfCoordinates[i]) ```
23,086,078
I have list that has 20 coordinates (x and y coordinates). I can calculate the distance between any two coordinates, but I have a hard time writing an algorithm that will iterate through the list and calculate the distance between the first node and every other node. for example, ``` ListOfCoordinates = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)] ``` In this case I need a for loop that will interate the list and calculate the distance between the first coordinate and the second coordinates, distance between first coordinate and third coordinate, etc. I am in need of an algorithm to help me out, then I will transform it into a python code. Thanks Thanks for ll the feedback. It's been helpful.
2014/04/15
[ "https://Stackoverflow.com/questions/23086078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3536195/" ]
Whenever you need something combinatorics-oriented ("I need first and second, then first and third, then...") chances are the `itertools` module has what you need. ``` from math import hypot def distance(p1,p2): """Euclidean distance between two points.""" x1,y1 = p1 x2,y2 = p2 return hypot(x2 - x1, y2 - y1) from itertools import combinations list_of_coords = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)] [distance(*combo) for combo in combinations(list_of_coords,2)] Out[29]: [2.8284271247461903, 5.656854249492381, 8.48528137423857, 11.313708498984761, 14.142135623730951, 2.8284271247461903, 5.656854249492381, 8.48528137423857, 11.313708498984761, 2.8284271247461903, 5.656854249492381, 8.48528137423857, 2.8284271247461903, 5.656854249492381, 2.8284271247461903] ``` edit: Your question is a bit confusing. Just in case you only want the first point compared against the other points: ``` from itertools import repeat pts = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)] [distance(*pair) for pair in zip(repeat(pts[0]),pts[1:])] Out[32]: [2.8284271247461903, 5.656854249492381, 8.48528137423857, 11.313708498984761, 14.142135623730951] ``` But usually in this type of problem you care about *all* the combinations so I'll leave the first answer up there.
I wanted a single line script to do this. The following script did the job for me. ``` import numpy as np yd = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)] distances_matrix = np.array([np.linalg.norm((item*np.ones((len(yd),len(item))))-yd,axis=1) for item in yd]) print(distances_matrix) output: [[ 0. 2.82842712 5.65685425 8.48528137 11.3137085 14.14213562] [ 2.82842712 0. 2.82842712 5.65685425 8.48528137 11.3137085 ] [ 5.65685425 2.82842712 0. 2.82842712 5.65685425 8.48528137] [ 8.48528137 5.65685425 2.82842712 0. 2.82842712 5.65685425] [11.3137085 8.48528137 5.65685425 2.82842712 0. 2.82842712] [14.14213562 11.3137085 8.48528137 5.65685425 2.82842712 0. ]] #Distance between coordinates with indices 2 and 4 print(distance_matrix[2,4]) output: 5.656854249492381 ``` Note: Here, I am using the Euclidean distance calculated only using Numpy. This solution should work for most cases. But it isn't recommended when the array/list is too large and it is not viable to make a copy of the same in the memory.
74,180,904
I am learning python and I am almost done with making tick tack toe but the code for checking if the game is a tie seems more complicated then it needs to be. is there a way of simplifying this? ``` if a1 != " " and a2 != " " and a3 != " " and b1 != " " and b2 != " " and b3 != " " and c1 != " " and c2 != " " and c3 != " ": board() print("its a tie!") quit() ```
2022/10/24
[ "https://Stackoverflow.com/questions/74180904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20321517/" ]
I think there is no implemented method in the SDK for that but after looking a bit, I found this one: [request](https://cloud.google.com/storage/docs/json_api/v1/objects/list#request) You could try to execute an HTTP GET specifying the parameters (you can find an example of the use of parameters here: [query\_parameters](https://cloud.google.com/storage/docs/json_api#query_parameters))
By default the google API iterators manage page size for you. The RowIterator returns a single row by default, backed internally by fetched pages that rely on the backend to select an appropriate size. If however you want to specify a fixed max page size, you can use the [`google.golang.org/api/iterator`](https://pkg.go.dev/google.golang.org/api/iterator) package to iterate by pages while specifying a specific size. The size, in this case, corresponds to `maxResults` for BigQuery's query APIs. See <https://github.com/googleapis/google-cloud-go/wiki/Iterator-Guidelines> for more general information about advanced iterator usage. Here's a quick test to demonstrate with the RowIterator in bigquery. It executes a query that returns a row for each day in October, and iterates by page: ``` func TestQueryPager(t *testing.T) { ctx := context.Background() pageSize := 5 client, err := bigquery.NewClient(ctx, "your-project-id here") if err != nil { t.Fatal(err) } defer client.Close() q := client.Query("SELECT * FROM UNNEST(GENERATE_DATE_ARRAY('2022-10-01','2022-10-31', INTERVAL 1 DAY)) as d") it, err := q.Read(ctx) if err != nil { t.Fatalf("query failure: %v", err) } pager := iterator.NewPager(it, pageSize, "") var fetchedPages int for { var rows [][]bigquery.Value nextToken, err := pager.NextPage(&rows) if err != nil { t.Fatalf("NextPage: %v", err) } fetchedPages = fetchedPages + 1 if len(rows) > pageSize { t.Errorf("page size exceeded, got %d want %d", len(rows), pageSize) } t.Logf("(next token %s) page size: %d", nextToken, len(rows)) if nextToken == "" { break } } wantPages := 7 if fetchedPages != wantPages { t.Fatalf("fetched %d pages, wanted %d pages", fetchedPages, wantPages) } } ```
18,004,605
I got stuck on another part of this exercise. The program that is being coded allows you to drill phrases (It gives you a piece of code, you write out the English translation) and I'm confused on how the "convert" function works. Full code: <http://learnpythonthehardway.org/book/ex41.html> ``` def convert(snippet, phrase): class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))] other_names = random.sample(WORDS, snippet.count("***")) results = [] param_names = [] for i in range(0, snippet.count("@@@")): param_count = random.randint(1,3) param_names.append(', '.join(random.sample(WORDS, param_count))) for sentence in snippet, phrase: result = sentence[:] # fake class names for word in class_names: result = result.replace("%%%", word, 1) # fake other names for word in other_names: result = result.replace("***", word, 1) # fake parameter lists for word in param_names: result = result.replace("@@@", word, 1) results.append(result) return results ``` I'm pretty lost. Is "w" from `w.capitalize()` a file itself, or is it just referring to the objects in the list? I'm also not sure why the `.count()` function is in the argument for `.sample()` (or what `.sample()` really does). What is the purpose of the first for\_loop? Thank you for any and all help - I'm sorry for the barrage of questions.
2013/08/01
[ "https://Stackoverflow.com/questions/18004605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2640186/" ]
If it can help you, ``` class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))] ``` is equivalent to ``` class_names = [] for w in random.sample(WORDS, snippet.count("%%%")): class_names.append(w.capitalize()) ``` The .count() will return the number of occurence of "%%%" in the snippet string, so the random.sample will select a subset of N elements from the WORDS list where N is the element of "%%%" in the snippet string.
`w.capitalize()` is like `.uppercase()`, but it only captilizes the first character.
17,708,683
I'm trying to deploy a Flask app on a Linode VPS running Ubuntu 10.10. I've been following this tutorial (<https://library.linode.com/web-servers/nginx/python-uwsgi/ubuntu-10.10-maverick#sph_configure-nginx>) but I keep getting a 502 Bad Gateway error. Here this is /etc/default/uwsgi: ``` PYTHONPATH=/var/www/reframeit-im MODULE=wsgi ``` Here is /var/www/reframeit-im/wsgi.py: ``` # add the application directory to the python path import sys sys.path.append("/var/www/reframeit-im") # run flask app from reframeit import app as application ``` Here is the app's nginx config file, which is symlinked to the /sites-enabled directory (/opt/nginx/conf/sites-enabled/reframeit-im): ``` server { listen 80; server_name www.reframeit-im.coshx.com reframeit-im.coshx.com; access_log /var/www/reframeit-im/logs/access.log; error_log /var/www/reframeit-im/logs/error.log; location / { include uwsgi_params; uwsgi_pass 127.0.0.1:9001; } } ``` I checked the nginx error logs for the app and I found this: ``` 2013/07/17 19:30:19 [error] 20037#0: *1 upstream prematurely closed connection while reading response header from upstream, client: 70.88.168.82, server: www.reframeit-im.coshx.com, request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://127.0.0.1:9001", host: "reframeit-im.coshx.com" ``` Is there something wrong with my configuration?
2013/07/17
[ "https://Stackoverflow.com/questions/17708683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2193598/" ]
With `uwsgi_pass 127.0.0.1:9001;` you declared to Nginx your intent to talk to uWSGI through TCP socket, but have not warned uWSGI about it. Try adding a corresponding socket line to your `/etc/default/uwsgi` file: ``` PYTHONPATH=/var/www/reframeit-im MODULE=wsgi socket=127.0.0.1:9001 ```
Please add "protocol = uwsgi" apart from what Flavio has suggested. As below ``` PYTHONPATH=/var/www/reframeit-im MODULE=wsgi socket=127.0.0.1:9001 protocol = uwsgi ```
66,996,147
I have a python list that looks like this: ``` my_list = [2, 4, 1 ,0, 3] ``` My goal is to iterate over this list in a manner where the next index is the current value and then to append all the index in another list and then stop the iteration once a cycle is over. Hence, > > Starting from 0 it contains the value 2 so you go to index 2. > > Index 2 contains the value 1 so you go to index 1 > > Index 1 contains the value 4 so you go to index 4 > > Index 4 contains the value 3 so you go to index 3 > > Index 3 contains the value 0 so you go to index 0 > > > and the new\_list looks like this: ``` new_list = [0,2,1,4,3] ``` My attempt: ``` In [14]: my_list = [2,4,1,0,3] In [15]: new_list =[] In [16]: for i,j in enumerate(my_list): ...: if i in new_list: ...: break ...: else: ...: new_list.append(i) ...: i=j ...: print(new_list) [0, 1, 2, 3, 4] ``` This is obviously not working. Specifically, that **i=j** line has no effect since the for loop goes back to the initial counter. How can I achieve this?
2021/04/08
[ "https://Stackoverflow.com/questions/66996147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1813039/" ]
A `while` loop is a better structure here; set `i` to point to the first element in `my_list` and then iterate until you find `i` in `new_list`: ```py my_list = [2,4,1,0,3] new_list = [] i = 0 while i not in new_list: new_list.append(i) i = my_list[i] print(new_list) ``` Output: ```py [0, 2, 1, 4, 3] ``` Note the code assumes that all values in `my_list` are valid indexes into `my_list`. If this is not the case, you would need to add a test for that and break the loop at that point. For example: ```py my_list = [2,4,5,0,3] new_list = [] i = 0 while i not in new_list: new_list.append(i) i = my_list[i] if i not in range(len(my_list)): break print(new_list) ``` Output: ```py [0, 2] ```
You can try this. using variable swapping you can reassign rather than appending and creating a new variable ``` my_list = [2,4,1,0,3] n= len(my_list) for i in range(n-1): for j in range(0,n-i-1): if my_list[j] > my_list[j+1]: my_list[j], my_list[j+1] = my_list[j+1],my_list[j] print(my_list) ```
35,132,569
What I'm trying to do is build a regressor based on a value in a feature. That is to say, I have some columns where one of them is more important (let's suppose it is `gender`) (of course it is different from the target value Y). I want to say: - If the `gender` is Male then use the randomForest regressor - Else use another regressor Do you have any idea about if this is possible using `sklearn` or any other library in python?
2016/02/01
[ "https://Stackoverflow.com/questions/35132569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3497084/" ]
You might be able to implement your own regressor. Let us assume that `gender` is the first feature. Then you could do something like ``` class MyRegressor(): '''uses different regressors internally''' def __init__(self): self.randomForest = initializeRandomForest() self.kNN = initializekNN() def fit(self, X, y): '''calls the appropriate regressors''' X1 = X[X[:,0] == 1] y1 = y[X[:,0] == 1] X2 = X[X[:,0] != 1] y2 = y[X[:,0] != 1] self.randomForest.fit(X1, y1) self.kNN.fit(X2, y2) def predict(self, X): '''predicts values using regressors internally''' results = np.zeros(X.shape[0]) results[X[:,0]==1] = self.randomForest.predict(X[X[:,0] == 1]) results[X[:,0]!=1] = self.kNN.predict(X[X[:,0] != 1]) return results ```
I personally am new to Python but I would use the data type of a list. I would then proceed to making a membership check and reference the list you just wrote. Then proceed to say that if member = true then run/use randomForest regressor. If false use/run another regressor.
60,873,608
Need substition for using label/goto -used in languages like C,..- in python So basically, I am a newb at python (and honestly, programming).I have been experimenting with super basic stuff and have hit a "roadblock". ``` print("Hello User!") print("Welcome to your BMI Calculator.") print("Please choose your system of measurement (Answer in terms of A or B):") print("A)Inches and Pounds") print("B)Meters and Kilograms") ans = str(input("Input:A or B")) if ans =="B": h = float(input("Please enter your height (in meters)")) w = float(input("Please enter your weight (in kilograms)")) bmi = w/(h**2) print("Your BMI is:") print(bmi) if bmi < 18.5: print("You are in the UNDERWEIGHT category.") elif 18.5 < bmi <24.9: print("You are in the HEALTHY-WEIGHT category.") else: print("You are in the OVERWEIGHT category.") print("THANK YOU FOR YOUR TIME.") elif ans =="A": h = float(input("Please enter your height (in inches)")) w = float(input("Please enter your weight (in pounds)")) bmi = (w*0.453592)/((h*0.0254)**2) print("Your BMI is:") print(bmi) if bmi < 18.5: print("You are in the UNDERWEIGHT category.") elif 18.5 < bmi <24.9: print("You are in the HEALTHY-WEIGHT category.") else: print("You are in the OVERWEIGHT category.") print("THANK YOU FOR YOUR TIME.") else: print("ERROR") ``` In the final else, I want it to go back to asking for input for the measurement system in case the user did not type 'A' or 'B' exactly. Some substitute for goto in python should work for that. Also, if there isn't a substitute for goto, the problem should be solved if it doesn't take any other input other than 'A' or 'B'. Thanks for your time.
2020/03/26
[ "https://Stackoverflow.com/questions/60873608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13130669/" ]
I don't recommend you start your programming career with `goto`, that's how you can get perfectly written `spaghetti code`. Let's review your use case here, you want to go back to asking user if he did not gave you an expected input, why not use a loop instead of `goto`? ``` ans = "unexpected" while(ans != "A" and ans != "B"): print("Hello User!") print("Welcome to your BMI Calculator.") print("Please choose your system of measurement (Answer in terms of A or B):") print("A)Inches and Pounds") print("B)Meters and Kilograms") ans = str(input("Input:A or B")) if ans =="B": h = float(input("Please enter your height (in meters)")) w = float(input("Please enter your weight (in kilograms)")) bmi = w/(h**2) print("Your BMI is:") print(bmi) if bmi < 18.5: print("You are in the UNDERWEIGHT category.") elif 18.5 < bmi <24.9: print("You are in the HEALTHY-WEIGHT category.") else: print("You are in the OVERWEIGHT category.") print("THANK YOU FOR YOUR TIME.") elif ans =="A": h = float(input("Please enter your height (in inches)")) w = float(input("Please enter your weight (in pounds)")) bmi = (w*0.453592)/((h*0.0254)**2) print("Your BMI is:") print(bmi) if bmi < 18.5: print("You are in the UNDERWEIGHT category.") elif 18.5 < bmi <24.9: print("You are in the HEALTHY-WEIGHT category.") else: print("You are in the OVERWEIGHT category.") print("THANK YOU FOR YOUR TIME.") ``` With that the user will be kept in the input state as long as he does not give you the desired input format.
Put everything in 'while (true)' starting with first 'if' statement. And remove last 'else' statement.
3,162,450
I am looking for references (tutorials, books, academic literature) concerning structuring unstructured text in a manner similar to the google calendar quick add button. I understand this may come under the NLP category, but I am interested only in the process of going from something like "Levi jeans size 32 A0b293" to: Brand: Levi, Size: 32, Category: Jeans, code: A0b293 I imagine it would be some combination of lexical parsing and machine learning techniques. I am rather language agnostic but if pushed would prefer python, Matlab or C++ references Thanks
2010/07/01
[ "https://Stackoverflow.com/questions/3162450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93580/" ]
You need to provide more information about the source of the text (the web? user input?), the domain (is it just clothes?), the potential formatting and vocabulary... Assuming worst case scenario you need to start learning NLP. A very good free book is the documentation of NLTK: <http://www.nltk.org/book> . It is also a very good introduction to Python and the SW is free (for various usages). Be warned: NLP is hard. It doesn't always work. It is not fun at times. The state of the art is no where near where you imagine it is. Assuming a better scenario (your text is semi-structured) - a good free tool is [pyparsing](http://pyparsing.wikispaces.com/). There is a book, plenty of examples and the resulting code is extremely attractive. I hope this helps...
Possibly look at "Collective Intelligence" by Toby Segaran. I seem to remember that addressing the basics of this in one chapter.
3,162,450
I am looking for references (tutorials, books, academic literature) concerning structuring unstructured text in a manner similar to the google calendar quick add button. I understand this may come under the NLP category, but I am interested only in the process of going from something like "Levi jeans size 32 A0b293" to: Brand: Levi, Size: 32, Category: Jeans, code: A0b293 I imagine it would be some combination of lexical parsing and machine learning techniques. I am rather language agnostic but if pushed would prefer python, Matlab or C++ references Thanks
2010/07/01
[ "https://Stackoverflow.com/questions/3162450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93580/" ]
You need to provide more information about the source of the text (the web? user input?), the domain (is it just clothes?), the potential formatting and vocabulary... Assuming worst case scenario you need to start learning NLP. A very good free book is the documentation of NLTK: <http://www.nltk.org/book> . It is also a very good introduction to Python and the SW is free (for various usages). Be warned: NLP is hard. It doesn't always work. It is not fun at times. The state of the art is no where near where you imagine it is. Assuming a better scenario (your text is semi-structured) - a good free tool is [pyparsing](http://pyparsing.wikispaces.com/). There is a book, plenty of examples and the resulting code is extremely attractive. I hope this helps...
After some researching I have found that this problem is commonly referred to as *Information Extraction* and have amassed a few papers and stored them in a Mendeley Collection <http://www.mendeley.com/research-papers/collections/3237331/Information-Extraction/> Also as Tai Weiss noted NLTK for python is a good starting point and [this](http://nltk.googlecode.com/svn/trunk/doc/book/ch07.html) chapter of the book, looks specifically at information extraction
3,162,450
I am looking for references (tutorials, books, academic literature) concerning structuring unstructured text in a manner similar to the google calendar quick add button. I understand this may come under the NLP category, but I am interested only in the process of going from something like "Levi jeans size 32 A0b293" to: Brand: Levi, Size: 32, Category: Jeans, code: A0b293 I imagine it would be some combination of lexical parsing and machine learning techniques. I am rather language agnostic but if pushed would prefer python, Matlab or C++ references Thanks
2010/07/01
[ "https://Stackoverflow.com/questions/3162450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93580/" ]
You need to provide more information about the source of the text (the web? user input?), the domain (is it just clothes?), the potential formatting and vocabulary... Assuming worst case scenario you need to start learning NLP. A very good free book is the documentation of NLTK: <http://www.nltk.org/book> . It is also a very good introduction to Python and the SW is free (for various usages). Be warned: NLP is hard. It doesn't always work. It is not fun at times. The state of the art is no where near where you imagine it is. Assuming a better scenario (your text is semi-structured) - a good free tool is [pyparsing](http://pyparsing.wikispaces.com/). There is a book, plenty of examples and the resulting code is extremely attractive. I hope this helps...
If you are only working for cases like the example you cited, you are better off using some manual rule-based that is 100% predictable and covers 90% of the cases it might encounter production.. You could enumerable lists of all possible brands and categories and detect which is which in an input string cos there's usually very little intersection in these two lists.. The other two could easily be detected and extracted using regular expressions. (1-3 digit numbers are always sizes, etc) Your problem domain doesn't seem big enough to warrant a more heavy duty approach such as statistical learning.
3,162,450
I am looking for references (tutorials, books, academic literature) concerning structuring unstructured text in a manner similar to the google calendar quick add button. I understand this may come under the NLP category, but I am interested only in the process of going from something like "Levi jeans size 32 A0b293" to: Brand: Levi, Size: 32, Category: Jeans, code: A0b293 I imagine it would be some combination of lexical parsing and machine learning techniques. I am rather language agnostic but if pushed would prefer python, Matlab or C++ references Thanks
2010/07/01
[ "https://Stackoverflow.com/questions/3162450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93580/" ]
Possibly look at "Collective Intelligence" by Toby Segaran. I seem to remember that addressing the basics of this in one chapter.
If you are only working for cases like the example you cited, you are better off using some manual rule-based that is 100% predictable and covers 90% of the cases it might encounter production.. You could enumerable lists of all possible brands and categories and detect which is which in an input string cos there's usually very little intersection in these two lists.. The other two could easily be detected and extracted using regular expressions. (1-3 digit numbers are always sizes, etc) Your problem domain doesn't seem big enough to warrant a more heavy duty approach such as statistical learning.
3,162,450
I am looking for references (tutorials, books, academic literature) concerning structuring unstructured text in a manner similar to the google calendar quick add button. I understand this may come under the NLP category, but I am interested only in the process of going from something like "Levi jeans size 32 A0b293" to: Brand: Levi, Size: 32, Category: Jeans, code: A0b293 I imagine it would be some combination of lexical parsing and machine learning techniques. I am rather language agnostic but if pushed would prefer python, Matlab or C++ references Thanks
2010/07/01
[ "https://Stackoverflow.com/questions/3162450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93580/" ]
After some researching I have found that this problem is commonly referred to as *Information Extraction* and have amassed a few papers and stored them in a Mendeley Collection <http://www.mendeley.com/research-papers/collections/3237331/Information-Extraction/> Also as Tai Weiss noted NLTK for python is a good starting point and [this](http://nltk.googlecode.com/svn/trunk/doc/book/ch07.html) chapter of the book, looks specifically at information extraction
If you are only working for cases like the example you cited, you are better off using some manual rule-based that is 100% predictable and covers 90% of the cases it might encounter production.. You could enumerable lists of all possible brands and categories and detect which is which in an input string cos there's usually very little intersection in these two lists.. The other two could easily be detected and extracted using regular expressions. (1-3 digit numbers are always sizes, etc) Your problem domain doesn't seem big enough to warrant a more heavy duty approach such as statistical learning.
68,890,393
I'm trying to install a Python package called "mudes" on another server using terminal. When I want to install it using ``` pip install mudes ``` or ``` pip3 install mudes ``` , I get the following error: ``` Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-hn4hol_z/spacy/ ``` I have also used ``` pip install --no-cache-dir mudes ``` , which resulted in the same error and ``` pip3 install --upgrade setuptools --user python ``` , which resulted in the following: ``` Requirement already up-to-date: setuptools in ./pythonProject/venv/lib/python3.6/site-packages Collecting python Could not find a version that satisfies the requirement python (from versions: ) No matching distribution found for python ``` How can I solve this problem?
2021/08/23
[ "https://Stackoverflow.com/questions/68890393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I had the same issue trying to install pycaret. I'm no expert so I don't know why but this work for me ``` pip3 install --upgrade pip ```
The setuptools might be outdated. Try running this command first and see if it helps. ``` pip install --upgrade setuptools ```
68,890,393
I'm trying to install a Python package called "mudes" on another server using terminal. When I want to install it using ``` pip install mudes ``` or ``` pip3 install mudes ``` , I get the following error: ``` Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-hn4hol_z/spacy/ ``` I have also used ``` pip install --no-cache-dir mudes ``` , which resulted in the same error and ``` pip3 install --upgrade setuptools --user python ``` , which resulted in the following: ``` Requirement already up-to-date: setuptools in ./pythonProject/venv/lib/python3.6/site-packages Collecting python Could not find a version that satisfies the requirement python (from versions: ) No matching distribution found for python ``` How can I solve this problem?
2021/08/23
[ "https://Stackoverflow.com/questions/68890393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I had the same issue trying to install pycaret. I'm no expert so I don't know why but this work for me ``` pip3 install --upgrade pip ```
Looks like spacy is not installed. ``` pip3 install spacy ``` It worked for me, check if it helps you.
46,510,770
I'm kind of new to python and I need to run a script all day. However, the memory used by the script keeps increasing over time until python crashes... I've tried stuff but nothing works :( Maybe I'm doing something wrong I don't know. Here's what my code looks like : ``` while True: try: import functions and modules... Init_Variables = ... def a bunch of functions... def clearall(): #Function to free memory all = [var for var in globals() if var[0] != "_" and var != gc] for var in all: del globals()[var] print('Cleared !') gc.collect() TimeLoop() #Getting out of "try" here because TimeLoop isn't defined anymore def TimeLoop(): for i in range (1,101): do stuff... # Free memory after 100 iterations ############################# clearall() TimeLoop() # Launches my function when i first start the script except Exception as e: print(e) continue break ``` After about 50.000 iterations of "do stuff..." python uses about 2GB of RAM and then crash :( I spent hours trying to solve this issue but nothing seems to work. Any help would be very much appreciated! :D
2017/10/01
[ "https://Stackoverflow.com/questions/46510770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8703130/" ]
The closest thing Xcode has is a button at the bottom of the project navigator to show only files with source-control status. Clicking the button shows files that have uncommitted changes. [![enter image description here](https://i.stack.imgur.com/PmT8M.png)](https://i.stack.imgur.com/PmT8M.png)
As Mark answered you can filter all the modified files, after that don't forget to turn on **Comparison**, so you can see where the code got changed. [![enter image description here](https://i.stack.imgur.com/Wmugd.png)](https://i.stack.imgur.com/Wmugd.png)
58,854,194
I'm getting the following error when using the [Microsoft Python Speech-to-Text Quickstart ("Quickstart: Recognize speech from an audio file")](https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/quickstarts/speech-to-text-from-file?tabs=linux&pivots=programming-language-python#sample-code) with the [azure-cognitiveservices-speech v1.8.0 SDK](https://pypi.org/project/azure-cognitiveservices-speech/). ``` RuntimeError: Exception with an error code: 0xa (SPXERR_INVALID_HEADER) ``` * Quickstart Code: <https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/quickstarts/speech-to-text-from-file?tabs=linux&pivots=programming-language-python#sample-code> * SDK: <https://pypi.org/project/azure-cognitiveservices-speech/> There are just 3 inputs to this file: * Azure Subscription Key * Azure Service Region * Filename I'm using the following test MP3 file: * <https://github.com/grokify/go-transcribe/blob/master/examples/mongodb-is-web-scale/web-scale_b2F-DItXtZs.mp3> Here's the full output: ``` Traceback (most recent call last): File "main.py", line 16, in <module> speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_input) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/azure/cognitiveservices/speech/speech.py", line 761, in __init__ self._impl = self._get_impl(impl.SpeechRecognizer, speech_config, audio_config) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/azure/cognitiveservices/speech/speech.py", line 547, in _get_impl _impl = reco_type._from_config(speech_config._impl, audio_config._impl) RuntimeError: Exception with an error code: 0xa (SPXERR_INVALID_HEADER) [CALL STACK BEGIN] 3 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106ad88d2 CreateModuleObject + 1136482 4 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106ad7f4f CreateModuleObject + 1134047 5 libMicrosoft.CognitiveServices.Speech.core.dylib 0x00000001069d1803 CreateModuleObject + 59027 6 libMicrosoft.CognitiveServices.Speech.core.dylib 0x00000001069d1503 CreateModuleObject + 58259 7 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106a11c64 CreateModuleObject + 322292 8 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106a10be5 CreateModuleObject + 318069 9 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106a0e5a2 CreateModuleObject + 308274 10 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106a0e7c3 CreateModuleObject + 308819 11 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106960bc7 recognizer_create_speech_recognizer_from_config + 3863 12 libMicrosoft.CognitiveServices.Speech.core.dylib 0x000000010695fd74 recognizer_create_speech_recognizer_from_config + 196 13 _speech_py_impl.so 0x00000001067ff35b PyInit__speech_py_impl + 814939 14 _speech_py_impl.so 0x000000010679b530 PyInit__speech_py_impl + 405808 15 Python 0x00000001060f65dc _PyMethodDef_RawFastCallKeywords + 668 16 Python 0x00000001060f5a5a _PyCFunction_FastCallKeywords + 42 17 Python 0x00000001061b45a4 call_function + 724 18 Python 0x00000001061b1576 _PyEval_EvalFrameDefault + 25190 19 Python 0x00000001060f5e90 function_code_fastcall + 128 20 Python 0x00000001061b45b2 call_function + 738 21 Python 0x00000001061b1576 _PyEval_EvalFrameDefault + 25190 22 Python 0x00000001061b50d6 _PyEval_EvalCodeWithName + 2422 23 Python 0x00000001060f55fb _PyFunction_FastCallDict + 523 24 Python 0x00000001060f68cf _PyObject_Call_Prepend + 143 25 Python 0x0000000106144d51 slot_tp_init + 145 26 Python 0x00000001061406a9 type_call + 297 27 Python 0x00000001060f5871 _PyObject_FastCallKeywords + 433 28 Python 0x00000001061b4474 call_function + 420 29 Python 0x00000001061b16bd _PyEval_EvalFrameDefault + 25517 30 Python 0x00000001061b50d6 _PyEval_EvalCodeWithName + 2422 31 Python 0x00000001061ab234 PyEval_EvalCode + 100 32 Python 0x00000001061e88f1 PyRun_FileExFlags + 209 33 Python 0x00000001061e816a PyRun_SimpleFileExFlags + 890 34 Python 0x00000001062079db pymain_main + 6875 35 Python 0x0000000106207f2a _Py_UnixMain + 58 36 libdyld.dylib 0x00007fff5d8aaed9 start + 1 37 ??? 0x0000000000000002 0x0 + 2 ``` Can anyone provide some pointers on what header this is referring to and how to resolve this.
2019/11/14
[ "https://Stackoverflow.com/questions/58854194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908967/" ]
mp3-encoded audio is not supported as an input format. Please use a WAV(PCM) file with 16-bit samples, 16 kHz sample rate, and a single channel (Mono).
The default audio streaming format is WAV (16kHz or 8kHz, 16-bit, and mono PCM). Outside of WAV / PCM, the compressed input formats listed below are also supported. However if you use C#/Java/C++/Objective C and if you want to use compressed audio formats such as **.mp3**, you can handle it by using **GStreamer** For more information follow this Microsoft documentation. <https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/how-to-use-codec-compressed-audio-input-streams>
58,854,194
I'm getting the following error when using the [Microsoft Python Speech-to-Text Quickstart ("Quickstart: Recognize speech from an audio file")](https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/quickstarts/speech-to-text-from-file?tabs=linux&pivots=programming-language-python#sample-code) with the [azure-cognitiveservices-speech v1.8.0 SDK](https://pypi.org/project/azure-cognitiveservices-speech/). ``` RuntimeError: Exception with an error code: 0xa (SPXERR_INVALID_HEADER) ``` * Quickstart Code: <https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/quickstarts/speech-to-text-from-file?tabs=linux&pivots=programming-language-python#sample-code> * SDK: <https://pypi.org/project/azure-cognitiveservices-speech/> There are just 3 inputs to this file: * Azure Subscription Key * Azure Service Region * Filename I'm using the following test MP3 file: * <https://github.com/grokify/go-transcribe/blob/master/examples/mongodb-is-web-scale/web-scale_b2F-DItXtZs.mp3> Here's the full output: ``` Traceback (most recent call last): File "main.py", line 16, in <module> speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_input) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/azure/cognitiveservices/speech/speech.py", line 761, in __init__ self._impl = self._get_impl(impl.SpeechRecognizer, speech_config, audio_config) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/azure/cognitiveservices/speech/speech.py", line 547, in _get_impl _impl = reco_type._from_config(speech_config._impl, audio_config._impl) RuntimeError: Exception with an error code: 0xa (SPXERR_INVALID_HEADER) [CALL STACK BEGIN] 3 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106ad88d2 CreateModuleObject + 1136482 4 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106ad7f4f CreateModuleObject + 1134047 5 libMicrosoft.CognitiveServices.Speech.core.dylib 0x00000001069d1803 CreateModuleObject + 59027 6 libMicrosoft.CognitiveServices.Speech.core.dylib 0x00000001069d1503 CreateModuleObject + 58259 7 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106a11c64 CreateModuleObject + 322292 8 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106a10be5 CreateModuleObject + 318069 9 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106a0e5a2 CreateModuleObject + 308274 10 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106a0e7c3 CreateModuleObject + 308819 11 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106960bc7 recognizer_create_speech_recognizer_from_config + 3863 12 libMicrosoft.CognitiveServices.Speech.core.dylib 0x000000010695fd74 recognizer_create_speech_recognizer_from_config + 196 13 _speech_py_impl.so 0x00000001067ff35b PyInit__speech_py_impl + 814939 14 _speech_py_impl.so 0x000000010679b530 PyInit__speech_py_impl + 405808 15 Python 0x00000001060f65dc _PyMethodDef_RawFastCallKeywords + 668 16 Python 0x00000001060f5a5a _PyCFunction_FastCallKeywords + 42 17 Python 0x00000001061b45a4 call_function + 724 18 Python 0x00000001061b1576 _PyEval_EvalFrameDefault + 25190 19 Python 0x00000001060f5e90 function_code_fastcall + 128 20 Python 0x00000001061b45b2 call_function + 738 21 Python 0x00000001061b1576 _PyEval_EvalFrameDefault + 25190 22 Python 0x00000001061b50d6 _PyEval_EvalCodeWithName + 2422 23 Python 0x00000001060f55fb _PyFunction_FastCallDict + 523 24 Python 0x00000001060f68cf _PyObject_Call_Prepend + 143 25 Python 0x0000000106144d51 slot_tp_init + 145 26 Python 0x00000001061406a9 type_call + 297 27 Python 0x00000001060f5871 _PyObject_FastCallKeywords + 433 28 Python 0x00000001061b4474 call_function + 420 29 Python 0x00000001061b16bd _PyEval_EvalFrameDefault + 25517 30 Python 0x00000001061b50d6 _PyEval_EvalCodeWithName + 2422 31 Python 0x00000001061ab234 PyEval_EvalCode + 100 32 Python 0x00000001061e88f1 PyRun_FileExFlags + 209 33 Python 0x00000001061e816a PyRun_SimpleFileExFlags + 890 34 Python 0x00000001062079db pymain_main + 6875 35 Python 0x0000000106207f2a _Py_UnixMain + 58 36 libdyld.dylib 0x00007fff5d8aaed9 start + 1 37 ??? 0x0000000000000002 0x0 + 2 ``` Can anyone provide some pointers on what header this is referring to and how to resolve this.
2019/11/14
[ "https://Stackoverflow.com/questions/58854194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908967/" ]
mp3-encoded audio is not supported as an input format. Please use a WAV(PCM) file with 16-bit samples, 16 kHz sample rate, and a single channel (Mono).
I guess there is no official method for usage of SDK with different formats (mp3 or different framerate) I'd like to use the Azure method that is able to use any type of audio file input Until now I am using my made-up method for dealing with this problem, first convert the proper file and delete it after finish my job. The original file is preserving: For **python**: ``` fname_buf = fname fname = self.AudioFileAdjust(fname,'test-it') # Do somethings if fname_buf != fname: self.AudioFileAdjust(fname,'remove') ``` Subfunction **AudioFileAdjust** (I am using pydub and pyaudio): ``` def AudioFileAdjust(self,fname,states=''): ''' check audio file format and if not appropriate create new buffer audio for use ''' if states == 'remove': os.remove(fname) else: # if the file format not useful for Azure, first need to change -> fr: 16000 must be audio_file = au.ReadAudioFile(fname) if audio_file.frame_rate != int(16000): #print('[Commend] changing the FrameRate') audio_file_e = au.SetFramerate(audio_file,int(16000)) #change fine name for use fname2 = fname.split(".")[0] + "_Conv_2" + ".wav" #without wav firstly and add additional au.ExportAudioFile(audio_file_e,fname2) #print('new file name: ', fname) fname = fname2 return fname ```
58,854,194
I'm getting the following error when using the [Microsoft Python Speech-to-Text Quickstart ("Quickstart: Recognize speech from an audio file")](https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/quickstarts/speech-to-text-from-file?tabs=linux&pivots=programming-language-python#sample-code) with the [azure-cognitiveservices-speech v1.8.0 SDK](https://pypi.org/project/azure-cognitiveservices-speech/). ``` RuntimeError: Exception with an error code: 0xa (SPXERR_INVALID_HEADER) ``` * Quickstart Code: <https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/quickstarts/speech-to-text-from-file?tabs=linux&pivots=programming-language-python#sample-code> * SDK: <https://pypi.org/project/azure-cognitiveservices-speech/> There are just 3 inputs to this file: * Azure Subscription Key * Azure Service Region * Filename I'm using the following test MP3 file: * <https://github.com/grokify/go-transcribe/blob/master/examples/mongodb-is-web-scale/web-scale_b2F-DItXtZs.mp3> Here's the full output: ``` Traceback (most recent call last): File "main.py", line 16, in <module> speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_input) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/azure/cognitiveservices/speech/speech.py", line 761, in __init__ self._impl = self._get_impl(impl.SpeechRecognizer, speech_config, audio_config) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/azure/cognitiveservices/speech/speech.py", line 547, in _get_impl _impl = reco_type._from_config(speech_config._impl, audio_config._impl) RuntimeError: Exception with an error code: 0xa (SPXERR_INVALID_HEADER) [CALL STACK BEGIN] 3 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106ad88d2 CreateModuleObject + 1136482 4 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106ad7f4f CreateModuleObject + 1134047 5 libMicrosoft.CognitiveServices.Speech.core.dylib 0x00000001069d1803 CreateModuleObject + 59027 6 libMicrosoft.CognitiveServices.Speech.core.dylib 0x00000001069d1503 CreateModuleObject + 58259 7 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106a11c64 CreateModuleObject + 322292 8 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106a10be5 CreateModuleObject + 318069 9 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106a0e5a2 CreateModuleObject + 308274 10 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106a0e7c3 CreateModuleObject + 308819 11 libMicrosoft.CognitiveServices.Speech.core.dylib 0x0000000106960bc7 recognizer_create_speech_recognizer_from_config + 3863 12 libMicrosoft.CognitiveServices.Speech.core.dylib 0x000000010695fd74 recognizer_create_speech_recognizer_from_config + 196 13 _speech_py_impl.so 0x00000001067ff35b PyInit__speech_py_impl + 814939 14 _speech_py_impl.so 0x000000010679b530 PyInit__speech_py_impl + 405808 15 Python 0x00000001060f65dc _PyMethodDef_RawFastCallKeywords + 668 16 Python 0x00000001060f5a5a _PyCFunction_FastCallKeywords + 42 17 Python 0x00000001061b45a4 call_function + 724 18 Python 0x00000001061b1576 _PyEval_EvalFrameDefault + 25190 19 Python 0x00000001060f5e90 function_code_fastcall + 128 20 Python 0x00000001061b45b2 call_function + 738 21 Python 0x00000001061b1576 _PyEval_EvalFrameDefault + 25190 22 Python 0x00000001061b50d6 _PyEval_EvalCodeWithName + 2422 23 Python 0x00000001060f55fb _PyFunction_FastCallDict + 523 24 Python 0x00000001060f68cf _PyObject_Call_Prepend + 143 25 Python 0x0000000106144d51 slot_tp_init + 145 26 Python 0x00000001061406a9 type_call + 297 27 Python 0x00000001060f5871 _PyObject_FastCallKeywords + 433 28 Python 0x00000001061b4474 call_function + 420 29 Python 0x00000001061b16bd _PyEval_EvalFrameDefault + 25517 30 Python 0x00000001061b50d6 _PyEval_EvalCodeWithName + 2422 31 Python 0x00000001061ab234 PyEval_EvalCode + 100 32 Python 0x00000001061e88f1 PyRun_FileExFlags + 209 33 Python 0x00000001061e816a PyRun_SimpleFileExFlags + 890 34 Python 0x00000001062079db pymain_main + 6875 35 Python 0x0000000106207f2a _Py_UnixMain + 58 36 libdyld.dylib 0x00007fff5d8aaed9 start + 1 37 ??? 0x0000000000000002 0x0 + 2 ``` Can anyone provide some pointers on what header this is referring to and how to resolve this.
2019/11/14
[ "https://Stackoverflow.com/questions/58854194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908967/" ]
The default audio streaming format is WAV (16kHz or 8kHz, 16-bit, and mono PCM). Outside of WAV / PCM, the compressed input formats listed below are also supported. However if you use C#/Java/C++/Objective C and if you want to use compressed audio formats such as **.mp3**, you can handle it by using **GStreamer** For more information follow this Microsoft documentation. <https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/how-to-use-codec-compressed-audio-input-streams>
I guess there is no official method for usage of SDK with different formats (mp3 or different framerate) I'd like to use the Azure method that is able to use any type of audio file input Until now I am using my made-up method for dealing with this problem, first convert the proper file and delete it after finish my job. The original file is preserving: For **python**: ``` fname_buf = fname fname = self.AudioFileAdjust(fname,'test-it') # Do somethings if fname_buf != fname: self.AudioFileAdjust(fname,'remove') ``` Subfunction **AudioFileAdjust** (I am using pydub and pyaudio): ``` def AudioFileAdjust(self,fname,states=''): ''' check audio file format and if not appropriate create new buffer audio for use ''' if states == 'remove': os.remove(fname) else: # if the file format not useful for Azure, first need to change -> fr: 16000 must be audio_file = au.ReadAudioFile(fname) if audio_file.frame_rate != int(16000): #print('[Commend] changing the FrameRate') audio_file_e = au.SetFramerate(audio_file,int(16000)) #change fine name for use fname2 = fname.split(".")[0] + "_Conv_2" + ".wav" #without wav firstly and add additional au.ExportAudioFile(audio_file_e,fname2) #print('new file name: ', fname) fname = fname2 return fname ```
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ | arial | 99854 | 5741 | | georgia | 52388 | 1955 | | verdana | 43219 | 2388 | | helvetica neue | 22179 | 1019 | | helvetica | 16753 | 1036 | | lucida grande | 15431 | 641 | | tahoma | 10038 | 594 | | trebuchet ms | 8868 | 417 | | palatino | 5794 | 177 | | lucida sans unicode | 3525 | 116 | | sans-serif | 2947 | 216 | | times new roman | 2554 | 161 | | proxima-nova | 2076 | 36 | | droid sans | 1773 | 78 | | calibri | 1735 | 64 | | open sans | 1479 | 60 | | segoe ui | 1273 | 57 | +---------------------+-----------+---------+ 17 rows in set (19.43 sec) ``` Notice: I don't know the max width for each column a priori, and yet I would like to be able to that without going over the table twice. Should I add to the query length() for each column? How does MySQL do it, in order to not impact severely the memory or processing time? *EDIT* I did not think it was relevant to the question but, this is the query I send: ``` SELECT font.font as font,count(textfont.textid) as documents, count(DISTINCT td.domain) as domains FROM textfont RIGHT JOIN font ON textfont.fontid = font.fontid RIGHT JOIN ( SELECT text.text as text,url.domain as domain, text.textid as textid FROM text RIGHT JOIN url ON text.texturl = url.urlid) as td ON textfont.textid = td.textid WHERE textfont.fontpriority <= 0 AND textfont.textlen > 100 GROUP BY font.font HAVING documents >= 1000 AND domains >= 10 ORDER BY 2 DESC; ``` And this is the python code I use: ``` import MySQLdb as mdb print "%s\t\t\t%s\t\t%s" % ("font","documents","domains") res = cur.execute(query , (font_priority,text_len,min_texts,min_domains)) for res in cur.fetchall(): print "%s\t\t\t%d\t\t%d" % (res[0],res[1],res[2]) ``` But this code produces a messy output due to different widths.
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
There is no need for an external library. The prints out the data with the column names. All lines with the 'columns' variable can be eliminated if you do not need the column names. ``` sql = "SELECT * FROM someTable" cursor.execute(sql) conn.commit() results = cursor.fetchall() widths = [] columns = [] tavnit = '|' separator = '+' for cd in cursor.description: widths.append(max(cd[2], len(cd[0]))) columns.append(cd[0]) for w in widths: tavnit += " %-"+"%ss |" % (w,) separator += '-'*w + '--+' print(separator) print(tavnit % tuple(columns)) print(separator) for row in results: print(tavnit % row) print(separator) ``` This is the output: ``` +--------+---------+---------------+------------+------------+ | ip_log | user_id | type_id | ip_address | time_stamp | +--------+---------+---------------+------------+------------+ | 227 | 1 | session_login | 10.0.0.2 | 1358760386 | | 140 | 1 | session_login | 10.0.0.2 | 1358321825 | | 98 | 1 | session_login | 10.0.0.2 | 1358157588 | +--------+---------+---------------+------------+------------+ ``` The magic lies in the third column of each `cursor.description` line (called `cd[2]` in the code). This column represents the length in characters of the longest value. Thus we size the displayed column as the greater between that and the length of the column header itself (`max(cd[2], len(cd[0]))`).
The data is in some list it seems, and are printing the header. Consider some formatting like this: ``` res = ['trebuchet ms', 8868, 417] res = ['lucida sans unicode', 3525, 116] ``` and ``` print(' {0[0]:20s} {0[1]:10d} {0[2]:10d}'.format(res)) ``` give you ``` trebuchet ms 8868 417 lucida sans unicode 3525 116 ``` Notice the indexing into the list is done inside the string, `format` only needs to supply the list or tuple. *Alternatively*, you could specify widths programatically: ``` wid1 = 20 wid2 = 10 wid3 = 10 print(' {:{}s} {:{}d} {:{}d}'.format(res[0], wid1, res[1], wid2, res[2], wid3)) ``` which gives identical output as above. You'd have to adjust the field widths as required and loop through the list for each line of data instead of made up sample lines. Numbers are automatically right justified, string automatically left. Advantage, to some, is of course that this doesn't rely on any external libraries, and is done with what Python already provides. Learn More About String Formatting [here](https://www.python.org/dev/peps/pep-3101/)
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ | arial | 99854 | 5741 | | georgia | 52388 | 1955 | | verdana | 43219 | 2388 | | helvetica neue | 22179 | 1019 | | helvetica | 16753 | 1036 | | lucida grande | 15431 | 641 | | tahoma | 10038 | 594 | | trebuchet ms | 8868 | 417 | | palatino | 5794 | 177 | | lucida sans unicode | 3525 | 116 | | sans-serif | 2947 | 216 | | times new roman | 2554 | 161 | | proxima-nova | 2076 | 36 | | droid sans | 1773 | 78 | | calibri | 1735 | 64 | | open sans | 1479 | 60 | | segoe ui | 1273 | 57 | +---------------------+-----------+---------+ 17 rows in set (19.43 sec) ``` Notice: I don't know the max width for each column a priori, and yet I would like to be able to that without going over the table twice. Should I add to the query length() for each column? How does MySQL do it, in order to not impact severely the memory or processing time? *EDIT* I did not think it was relevant to the question but, this is the query I send: ``` SELECT font.font as font,count(textfont.textid) as documents, count(DISTINCT td.domain) as domains FROM textfont RIGHT JOIN font ON textfont.fontid = font.fontid RIGHT JOIN ( SELECT text.text as text,url.domain as domain, text.textid as textid FROM text RIGHT JOIN url ON text.texturl = url.urlid) as td ON textfont.textid = td.textid WHERE textfont.fontpriority <= 0 AND textfont.textlen > 100 GROUP BY font.font HAVING documents >= 1000 AND domains >= 10 ORDER BY 2 DESC; ``` And this is the python code I use: ``` import MySQLdb as mdb print "%s\t\t\t%s\t\t%s" % ("font","documents","domains") res = cur.execute(query , (font_priority,text_len,min_texts,min_domains)) for res in cur.fetchall(): print "%s\t\t\t%d\t\t%d" % (res[0],res[1],res[2]) ``` But this code produces a messy output due to different widths.
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
There is no need for an external library. The prints out the data with the column names. All lines with the 'columns' variable can be eliminated if you do not need the column names. ``` sql = "SELECT * FROM someTable" cursor.execute(sql) conn.commit() results = cursor.fetchall() widths = [] columns = [] tavnit = '|' separator = '+' for cd in cursor.description: widths.append(max(cd[2], len(cd[0]))) columns.append(cd[0]) for w in widths: tavnit += " %-"+"%ss |" % (w,) separator += '-'*w + '--+' print(separator) print(tavnit % tuple(columns)) print(separator) for row in results: print(tavnit % row) print(separator) ``` This is the output: ``` +--------+---------+---------------+------------+------------+ | ip_log | user_id | type_id | ip_address | time_stamp | +--------+---------+---------------+------------+------------+ | 227 | 1 | session_login | 10.0.0.2 | 1358760386 | | 140 | 1 | session_login | 10.0.0.2 | 1358321825 | | 98 | 1 | session_login | 10.0.0.2 | 1358157588 | +--------+---------+---------------+------------+------------+ ``` The magic lies in the third column of each `cursor.description` line (called `cd[2]` in the code). This column represents the length in characters of the longest value. Thus we size the displayed column as the greater between that and the length of the column header itself (`max(cd[2], len(cd[0]))`).
You need to do two passes: 1. Calculate the column widths 2. Print the table So ``` table = cur.fetchall() widths = [0]*len(table[0]) # Assuming there is always one row for row in table: widths = [max(w,len(c)) for w,c in zip(widths,row)] ``` Now you can print the table trivially. Remember the `string.rjust` method when printing the numbers. **Update** A more functional way of calculating `widths` is: ``` sizetable = [map(len,row) for row in table] widths = map(max, zip(*sizetable)) ```
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ | arial | 99854 | 5741 | | georgia | 52388 | 1955 | | verdana | 43219 | 2388 | | helvetica neue | 22179 | 1019 | | helvetica | 16753 | 1036 | | lucida grande | 15431 | 641 | | tahoma | 10038 | 594 | | trebuchet ms | 8868 | 417 | | palatino | 5794 | 177 | | lucida sans unicode | 3525 | 116 | | sans-serif | 2947 | 216 | | times new roman | 2554 | 161 | | proxima-nova | 2076 | 36 | | droid sans | 1773 | 78 | | calibri | 1735 | 64 | | open sans | 1479 | 60 | | segoe ui | 1273 | 57 | +---------------------+-----------+---------+ 17 rows in set (19.43 sec) ``` Notice: I don't know the max width for each column a priori, and yet I would like to be able to that without going over the table twice. Should I add to the query length() for each column? How does MySQL do it, in order to not impact severely the memory or processing time? *EDIT* I did not think it was relevant to the question but, this is the query I send: ``` SELECT font.font as font,count(textfont.textid) as documents, count(DISTINCT td.domain) as domains FROM textfont RIGHT JOIN font ON textfont.fontid = font.fontid RIGHT JOIN ( SELECT text.text as text,url.domain as domain, text.textid as textid FROM text RIGHT JOIN url ON text.texturl = url.urlid) as td ON textfont.textid = td.textid WHERE textfont.fontpriority <= 0 AND textfont.textlen > 100 GROUP BY font.font HAVING documents >= 1000 AND domains >= 10 ORDER BY 2 DESC; ``` And this is the python code I use: ``` import MySQLdb as mdb print "%s\t\t\t%s\t\t%s" % ("font","documents","domains") res = cur.execute(query , (font_priority,text_len,min_texts,min_domains)) for res in cur.fetchall(): print "%s\t\t\t%d\t\t%d" % (res[0],res[1],res[2]) ``` But this code produces a messy output due to different widths.
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
Best and easiest way to print MySQL results into MySQL Table format using Python Library `tabulate` `user@system$ pip install tabulate` **Python Code:** ``` import mysql.connector from tabulate import tabulate mydb = mysql.connector.connect( host="localhost", user="root", passwd="password", database="testDB" ) mycursor = mydb.cursor() mycursor.execute("SELECT emp_name, salary FROM emp_table") myresult = mycursor.fetchall() print(tabulate(myresult, headers=['EmpName', 'EmpSalary'], tablefmt='psql')) ``` **Output:** ``` user@system:~$ python python_mysql.py +------------+-------------+ | EmpName | EmpSalary | |------------+-------------| | Ram | 400 | | Dipankar | 100 | | Santhosh | 200 | | Nirmal | 470 | | Santu | 340 | | Shiva | 100 | | Karthik | 500 | +------------+-------------+ ```
I modified [dotancohen's answer](https://stackoverflow.com/a/20383011/4795539) so only the resulting list of dict is needed as input. This is useful if you already have a library method returning results: ``` def format_table(self, results:list): if not len(results): return [] widths = [] max_widths = {} tavnit = '|' separator = '+' report = [] # add col headers length to widths for key in results[0].keys(): max_widths[key] = len(key) # add max content lengths to widths for row in results: for key in row.keys(): if len(str(row[key])) > max_widths[key]: max_widths[key] = len(str(row[key])) for key in results[0].keys(): widths.append(max_widths[key]) for w in widths: tavnit += " %-" + "%s.%ss |" % (w, w) separator += '-' * w + '--+' # build report report.append(separator) report.append(tavnit % tuple(results[0].keys())) report.append(separator) for row in results: report.append(tavnit % tuple(row.values())) report.append(separator) return report ```
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ | arial | 99854 | 5741 | | georgia | 52388 | 1955 | | verdana | 43219 | 2388 | | helvetica neue | 22179 | 1019 | | helvetica | 16753 | 1036 | | lucida grande | 15431 | 641 | | tahoma | 10038 | 594 | | trebuchet ms | 8868 | 417 | | palatino | 5794 | 177 | | lucida sans unicode | 3525 | 116 | | sans-serif | 2947 | 216 | | times new roman | 2554 | 161 | | proxima-nova | 2076 | 36 | | droid sans | 1773 | 78 | | calibri | 1735 | 64 | | open sans | 1479 | 60 | | segoe ui | 1273 | 57 | +---------------------+-----------+---------+ 17 rows in set (19.43 sec) ``` Notice: I don't know the max width for each column a priori, and yet I would like to be able to that without going over the table twice. Should I add to the query length() for each column? How does MySQL do it, in order to not impact severely the memory or processing time? *EDIT* I did not think it was relevant to the question but, this is the query I send: ``` SELECT font.font as font,count(textfont.textid) as documents, count(DISTINCT td.domain) as domains FROM textfont RIGHT JOIN font ON textfont.fontid = font.fontid RIGHT JOIN ( SELECT text.text as text,url.domain as domain, text.textid as textid FROM text RIGHT JOIN url ON text.texturl = url.urlid) as td ON textfont.textid = td.textid WHERE textfont.fontpriority <= 0 AND textfont.textlen > 100 GROUP BY font.font HAVING documents >= 1000 AND domains >= 10 ORDER BY 2 DESC; ``` And this is the python code I use: ``` import MySQLdb as mdb print "%s\t\t\t%s\t\t%s" % ("font","documents","domains") res = cur.execute(query , (font_priority,text_len,min_texts,min_domains)) for res in cur.fetchall(): print "%s\t\t\t%d\t\t%d" % (res[0],res[1],res[2]) ``` But this code produces a messy output due to different widths.
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
Best and easiest way to print MySQL results into MySQL Table format using Python Library `tabulate` `user@system$ pip install tabulate` **Python Code:** ``` import mysql.connector from tabulate import tabulate mydb = mysql.connector.connect( host="localhost", user="root", passwd="password", database="testDB" ) mycursor = mydb.cursor() mycursor.execute("SELECT emp_name, salary FROM emp_table") myresult = mycursor.fetchall() print(tabulate(myresult, headers=['EmpName', 'EmpSalary'], tablefmt='psql')) ``` **Output:** ``` user@system:~$ python python_mysql.py +------------+-------------+ | EmpName | EmpSalary | |------------+-------------| | Ram | 400 | | Dipankar | 100 | | Santhosh | 200 | | Nirmal | 470 | | Santu | 340 | | Shiva | 100 | | Karthik | 500 | +------------+-------------+ ```
The data is in some list it seems, and are printing the header. Consider some formatting like this: ``` res = ['trebuchet ms', 8868, 417] res = ['lucida sans unicode', 3525, 116] ``` and ``` print(' {0[0]:20s} {0[1]:10d} {0[2]:10d}'.format(res)) ``` give you ``` trebuchet ms 8868 417 lucida sans unicode 3525 116 ``` Notice the indexing into the list is done inside the string, `format` only needs to supply the list or tuple. *Alternatively*, you could specify widths programatically: ``` wid1 = 20 wid2 = 10 wid3 = 10 print(' {:{}s} {:{}d} {:{}d}'.format(res[0], wid1, res[1], wid2, res[2], wid3)) ``` which gives identical output as above. You'd have to adjust the field widths as required and loop through the list for each line of data instead of made up sample lines. Numbers are automatically right justified, string automatically left. Advantage, to some, is of course that this doesn't rely on any external libraries, and is done with what Python already provides. Learn More About String Formatting [here](https://www.python.org/dev/peps/pep-3101/)
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ | arial | 99854 | 5741 | | georgia | 52388 | 1955 | | verdana | 43219 | 2388 | | helvetica neue | 22179 | 1019 | | helvetica | 16753 | 1036 | | lucida grande | 15431 | 641 | | tahoma | 10038 | 594 | | trebuchet ms | 8868 | 417 | | palatino | 5794 | 177 | | lucida sans unicode | 3525 | 116 | | sans-serif | 2947 | 216 | | times new roman | 2554 | 161 | | proxima-nova | 2076 | 36 | | droid sans | 1773 | 78 | | calibri | 1735 | 64 | | open sans | 1479 | 60 | | segoe ui | 1273 | 57 | +---------------------+-----------+---------+ 17 rows in set (19.43 sec) ``` Notice: I don't know the max width for each column a priori, and yet I would like to be able to that without going over the table twice. Should I add to the query length() for each column? How does MySQL do it, in order to not impact severely the memory or processing time? *EDIT* I did not think it was relevant to the question but, this is the query I send: ``` SELECT font.font as font,count(textfont.textid) as documents, count(DISTINCT td.domain) as domains FROM textfont RIGHT JOIN font ON textfont.fontid = font.fontid RIGHT JOIN ( SELECT text.text as text,url.domain as domain, text.textid as textid FROM text RIGHT JOIN url ON text.texturl = url.urlid) as td ON textfont.textid = td.textid WHERE textfont.fontpriority <= 0 AND textfont.textlen > 100 GROUP BY font.font HAVING documents >= 1000 AND domains >= 10 ORDER BY 2 DESC; ``` And this is the python code I use: ``` import MySQLdb as mdb print "%s\t\t\t%s\t\t%s" % ("font","documents","domains") res = cur.execute(query , (font_priority,text_len,min_texts,min_domains)) for res in cur.fetchall(): print "%s\t\t\t%d\t\t%d" % (res[0],res[1],res[2]) ``` But this code produces a messy output due to different widths.
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
There is no need for an external library. The prints out the data with the column names. All lines with the 'columns' variable can be eliminated if you do not need the column names. ``` sql = "SELECT * FROM someTable" cursor.execute(sql) conn.commit() results = cursor.fetchall() widths = [] columns = [] tavnit = '|' separator = '+' for cd in cursor.description: widths.append(max(cd[2], len(cd[0]))) columns.append(cd[0]) for w in widths: tavnit += " %-"+"%ss |" % (w,) separator += '-'*w + '--+' print(separator) print(tavnit % tuple(columns)) print(separator) for row in results: print(tavnit % row) print(separator) ``` This is the output: ``` +--------+---------+---------------+------------+------------+ | ip_log | user_id | type_id | ip_address | time_stamp | +--------+---------+---------------+------------+------------+ | 227 | 1 | session_login | 10.0.0.2 | 1358760386 | | 140 | 1 | session_login | 10.0.0.2 | 1358321825 | | 98 | 1 | session_login | 10.0.0.2 | 1358157588 | +--------+---------+---------------+------------+------------+ ``` The magic lies in the third column of each `cursor.description` line (called `cd[2]` in the code). This column represents the length in characters of the longest value. Thus we size the displayed column as the greater between that and the length of the column header itself (`max(cd[2], len(cd[0]))`).
I modified [dotancohen's answer](https://stackoverflow.com/a/20383011/4795539) so only the resulting list of dict is needed as input. This is useful if you already have a library method returning results: ``` def format_table(self, results:list): if not len(results): return [] widths = [] max_widths = {} tavnit = '|' separator = '+' report = [] # add col headers length to widths for key in results[0].keys(): max_widths[key] = len(key) # add max content lengths to widths for row in results: for key in row.keys(): if len(str(row[key])) > max_widths[key]: max_widths[key] = len(str(row[key])) for key in results[0].keys(): widths.append(max_widths[key]) for w in widths: tavnit += " %-" + "%s.%ss |" % (w, w) separator += '-' * w + '--+' # build report report.append(separator) report.append(tavnit % tuple(results[0].keys())) report.append(separator) for row in results: report.append(tavnit % tuple(row.values())) report.append(separator) return report ```
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ | arial | 99854 | 5741 | | georgia | 52388 | 1955 | | verdana | 43219 | 2388 | | helvetica neue | 22179 | 1019 | | helvetica | 16753 | 1036 | | lucida grande | 15431 | 641 | | tahoma | 10038 | 594 | | trebuchet ms | 8868 | 417 | | palatino | 5794 | 177 | | lucida sans unicode | 3525 | 116 | | sans-serif | 2947 | 216 | | times new roman | 2554 | 161 | | proxima-nova | 2076 | 36 | | droid sans | 1773 | 78 | | calibri | 1735 | 64 | | open sans | 1479 | 60 | | segoe ui | 1273 | 57 | +---------------------+-----------+---------+ 17 rows in set (19.43 sec) ``` Notice: I don't know the max width for each column a priori, and yet I would like to be able to that without going over the table twice. Should I add to the query length() for each column? How does MySQL do it, in order to not impact severely the memory or processing time? *EDIT* I did not think it was relevant to the question but, this is the query I send: ``` SELECT font.font as font,count(textfont.textid) as documents, count(DISTINCT td.domain) as domains FROM textfont RIGHT JOIN font ON textfont.fontid = font.fontid RIGHT JOIN ( SELECT text.text as text,url.domain as domain, text.textid as textid FROM text RIGHT JOIN url ON text.texturl = url.urlid) as td ON textfont.textid = td.textid WHERE textfont.fontpriority <= 0 AND textfont.textlen > 100 GROUP BY font.font HAVING documents >= 1000 AND domains >= 10 ORDER BY 2 DESC; ``` And this is the python code I use: ``` import MySQLdb as mdb print "%s\t\t\t%s\t\t%s" % ("font","documents","domains") res = cur.execute(query , (font_priority,text_len,min_texts,min_domains)) for res in cur.fetchall(): print "%s\t\t\t%d\t\t%d" % (res[0],res[1],res[2]) ``` But this code produces a messy output due to different widths.
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
The data is in some list it seems, and are printing the header. Consider some formatting like this: ``` res = ['trebuchet ms', 8868, 417] res = ['lucida sans unicode', 3525, 116] ``` and ``` print(' {0[0]:20s} {0[1]:10d} {0[2]:10d}'.format(res)) ``` give you ``` trebuchet ms 8868 417 lucida sans unicode 3525 116 ``` Notice the indexing into the list is done inside the string, `format` only needs to supply the list or tuple. *Alternatively*, you could specify widths programatically: ``` wid1 = 20 wid2 = 10 wid3 = 10 print(' {:{}s} {:{}d} {:{}d}'.format(res[0], wid1, res[1], wid2, res[2], wid3)) ``` which gives identical output as above. You'd have to adjust the field widths as required and loop through the list for each line of data instead of made up sample lines. Numbers are automatically right justified, string automatically left. Advantage, to some, is of course that this doesn't rely on any external libraries, and is done with what Python already provides. Learn More About String Formatting [here](https://www.python.org/dev/peps/pep-3101/)
I modified [dotancohen's answer](https://stackoverflow.com/a/20383011/4795539) so only the resulting list of dict is needed as input. This is useful if you already have a library method returning results: ``` def format_table(self, results:list): if not len(results): return [] widths = [] max_widths = {} tavnit = '|' separator = '+' report = [] # add col headers length to widths for key in results[0].keys(): max_widths[key] = len(key) # add max content lengths to widths for row in results: for key in row.keys(): if len(str(row[key])) > max_widths[key]: max_widths[key] = len(str(row[key])) for key in results[0].keys(): widths.append(max_widths[key]) for w in widths: tavnit += " %-" + "%s.%ss |" % (w, w) separator += '-' * w + '--+' # build report report.append(separator) report.append(tavnit % tuple(results[0].keys())) report.append(separator) for row in results: report.append(tavnit % tuple(row.values())) report.append(separator) return report ```
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ | arial | 99854 | 5741 | | georgia | 52388 | 1955 | | verdana | 43219 | 2388 | | helvetica neue | 22179 | 1019 | | helvetica | 16753 | 1036 | | lucida grande | 15431 | 641 | | tahoma | 10038 | 594 | | trebuchet ms | 8868 | 417 | | palatino | 5794 | 177 | | lucida sans unicode | 3525 | 116 | | sans-serif | 2947 | 216 | | times new roman | 2554 | 161 | | proxima-nova | 2076 | 36 | | droid sans | 1773 | 78 | | calibri | 1735 | 64 | | open sans | 1479 | 60 | | segoe ui | 1273 | 57 | +---------------------+-----------+---------+ 17 rows in set (19.43 sec) ``` Notice: I don't know the max width for each column a priori, and yet I would like to be able to that without going over the table twice. Should I add to the query length() for each column? How does MySQL do it, in order to not impact severely the memory or processing time? *EDIT* I did not think it was relevant to the question but, this is the query I send: ``` SELECT font.font as font,count(textfont.textid) as documents, count(DISTINCT td.domain) as domains FROM textfont RIGHT JOIN font ON textfont.fontid = font.fontid RIGHT JOIN ( SELECT text.text as text,url.domain as domain, text.textid as textid FROM text RIGHT JOIN url ON text.texturl = url.urlid) as td ON textfont.textid = td.textid WHERE textfont.fontpriority <= 0 AND textfont.textlen > 100 GROUP BY font.font HAVING documents >= 1000 AND domains >= 10 ORDER BY 2 DESC; ``` And this is the python code I use: ``` import MySQLdb as mdb print "%s\t\t\t%s\t\t%s" % ("font","documents","domains") res = cur.execute(query , (font_priority,text_len,min_texts,min_domains)) for res in cur.fetchall(): print "%s\t\t\t%d\t\t%d" % (res[0],res[1],res[2]) ``` But this code produces a messy output due to different widths.
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
Use [`prettytable`](http://code.google.com/p/prettytable/) ``` x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"]) x.set_field_align("City name", "l") # Left align city names x.set_padding_width(1) # One space between column edges and contents (default) x.add_row(["Adelaide",1295, 1158259, 600.5]) x.add_row(["Brisbane",5905, 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) print x +-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ | Adelaide | 1295 | 1158259 | 600.5 | | Brisbane | 5905 | 1857594 | 1146.4 | | Darwin | 112 | 120900 | 1714.7 | | Hobart | 1357 | 205556 | 619.5 | | Sydney | 2058 | 4336374 | 1214.8 | | Melbourne | 1566 | 3806092 | 646.9 | | Perth | 5386 | 1554769 | 869.4 | +-----------+------+------------+-----------------+ ```
Best and easiest way to print MySQL results into MySQL Table format using Python Library `tabulate` `user@system$ pip install tabulate` **Python Code:** ``` import mysql.connector from tabulate import tabulate mydb = mysql.connector.connect( host="localhost", user="root", passwd="password", database="testDB" ) mycursor = mydb.cursor() mycursor.execute("SELECT emp_name, salary FROM emp_table") myresult = mycursor.fetchall() print(tabulate(myresult, headers=['EmpName', 'EmpSalary'], tablefmt='psql')) ``` **Output:** ``` user@system:~$ python python_mysql.py +------------+-------------+ | EmpName | EmpSalary | |------------+-------------| | Ram | 400 | | Dipankar | 100 | | Santhosh | 200 | | Nirmal | 470 | | Santu | 340 | | Shiva | 100 | | Karthik | 500 | +------------+-------------+ ```
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ | arial | 99854 | 5741 | | georgia | 52388 | 1955 | | verdana | 43219 | 2388 | | helvetica neue | 22179 | 1019 | | helvetica | 16753 | 1036 | | lucida grande | 15431 | 641 | | tahoma | 10038 | 594 | | trebuchet ms | 8868 | 417 | | palatino | 5794 | 177 | | lucida sans unicode | 3525 | 116 | | sans-serif | 2947 | 216 | | times new roman | 2554 | 161 | | proxima-nova | 2076 | 36 | | droid sans | 1773 | 78 | | calibri | 1735 | 64 | | open sans | 1479 | 60 | | segoe ui | 1273 | 57 | +---------------------+-----------+---------+ 17 rows in set (19.43 sec) ``` Notice: I don't know the max width for each column a priori, and yet I would like to be able to that without going over the table twice. Should I add to the query length() for each column? How does MySQL do it, in order to not impact severely the memory or processing time? *EDIT* I did not think it was relevant to the question but, this is the query I send: ``` SELECT font.font as font,count(textfont.textid) as documents, count(DISTINCT td.domain) as domains FROM textfont RIGHT JOIN font ON textfont.fontid = font.fontid RIGHT JOIN ( SELECT text.text as text,url.domain as domain, text.textid as textid FROM text RIGHT JOIN url ON text.texturl = url.urlid) as td ON textfont.textid = td.textid WHERE textfont.fontpriority <= 0 AND textfont.textlen > 100 GROUP BY font.font HAVING documents >= 1000 AND domains >= 10 ORDER BY 2 DESC; ``` And this is the python code I use: ``` import MySQLdb as mdb print "%s\t\t\t%s\t\t%s" % ("font","documents","domains") res = cur.execute(query , (font_priority,text_len,min_texts,min_domains)) for res in cur.fetchall(): print "%s\t\t\t%d\t\t%d" % (res[0],res[1],res[2]) ``` But this code produces a messy output due to different widths.
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
Best and easiest way to print MySQL results into MySQL Table format using Python Library `tabulate` `user@system$ pip install tabulate` **Python Code:** ``` import mysql.connector from tabulate import tabulate mydb = mysql.connector.connect( host="localhost", user="root", passwd="password", database="testDB" ) mycursor = mydb.cursor() mycursor.execute("SELECT emp_name, salary FROM emp_table") myresult = mycursor.fetchall() print(tabulate(myresult, headers=['EmpName', 'EmpSalary'], tablefmt='psql')) ``` **Output:** ``` user@system:~$ python python_mysql.py +------------+-------------+ | EmpName | EmpSalary | |------------+-------------| | Ram | 400 | | Dipankar | 100 | | Santhosh | 200 | | Nirmal | 470 | | Santu | 340 | | Shiva | 100 | | Karthik | 500 | +------------+-------------+ ```
You need to do two passes: 1. Calculate the column widths 2. Print the table So ``` table = cur.fetchall() widths = [0]*len(table[0]) # Assuming there is always one row for row in table: widths = [max(w,len(c)) for w,c in zip(widths,row)] ``` Now you can print the table trivially. Remember the `string.rjust` method when printing the numbers. **Update** A more functional way of calculating `widths` is: ``` sizetable = [map(len,row) for row in table] widths = map(max, zip(*sizetable)) ```
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ | arial | 99854 | 5741 | | georgia | 52388 | 1955 | | verdana | 43219 | 2388 | | helvetica neue | 22179 | 1019 | | helvetica | 16753 | 1036 | | lucida grande | 15431 | 641 | | tahoma | 10038 | 594 | | trebuchet ms | 8868 | 417 | | palatino | 5794 | 177 | | lucida sans unicode | 3525 | 116 | | sans-serif | 2947 | 216 | | times new roman | 2554 | 161 | | proxima-nova | 2076 | 36 | | droid sans | 1773 | 78 | | calibri | 1735 | 64 | | open sans | 1479 | 60 | | segoe ui | 1273 | 57 | +---------------------+-----------+---------+ 17 rows in set (19.43 sec) ``` Notice: I don't know the max width for each column a priori, and yet I would like to be able to that without going over the table twice. Should I add to the query length() for each column? How does MySQL do it, in order to not impact severely the memory or processing time? *EDIT* I did not think it was relevant to the question but, this is the query I send: ``` SELECT font.font as font,count(textfont.textid) as documents, count(DISTINCT td.domain) as domains FROM textfont RIGHT JOIN font ON textfont.fontid = font.fontid RIGHT JOIN ( SELECT text.text as text,url.domain as domain, text.textid as textid FROM text RIGHT JOIN url ON text.texturl = url.urlid) as td ON textfont.textid = td.textid WHERE textfont.fontpriority <= 0 AND textfont.textlen > 100 GROUP BY font.font HAVING documents >= 1000 AND domains >= 10 ORDER BY 2 DESC; ``` And this is the python code I use: ``` import MySQLdb as mdb print "%s\t\t\t%s\t\t%s" % ("font","documents","domains") res = cur.execute(query , (font_priority,text_len,min_texts,min_domains)) for res in cur.fetchall(): print "%s\t\t\t%d\t\t%d" % (res[0],res[1],res[2]) ``` But this code produces a messy output due to different widths.
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
You need to do two passes: 1. Calculate the column widths 2. Print the table So ``` table = cur.fetchall() widths = [0]*len(table[0]) # Assuming there is always one row for row in table: widths = [max(w,len(c)) for w,c in zip(widths,row)] ``` Now you can print the table trivially. Remember the `string.rjust` method when printing the numbers. **Update** A more functional way of calculating `widths` is: ``` sizetable = [map(len,row) for row in table] widths = map(max, zip(*sizetable)) ```
I modified [dotancohen's answer](https://stackoverflow.com/a/20383011/4795539) so only the resulting list of dict is needed as input. This is useful if you already have a library method returning results: ``` def format_table(self, results:list): if not len(results): return [] widths = [] max_widths = {} tavnit = '|' separator = '+' report = [] # add col headers length to widths for key in results[0].keys(): max_widths[key] = len(key) # add max content lengths to widths for row in results: for key in row.keys(): if len(str(row[key])) > max_widths[key]: max_widths[key] = len(str(row[key])) for key in results[0].keys(): widths.append(max_widths[key]) for w in widths: tavnit += " %-" + "%s.%ss |" % (w, w) separator += '-' * w + '--+' # build report report.append(separator) report.append(tavnit % tuple(results[0].keys())) report.append(separator) for row in results: report.append(tavnit % tuple(row.values())) report.append(separator) return report ```
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ | arial | 99854 | 5741 | | georgia | 52388 | 1955 | | verdana | 43219 | 2388 | | helvetica neue | 22179 | 1019 | | helvetica | 16753 | 1036 | | lucida grande | 15431 | 641 | | tahoma | 10038 | 594 | | trebuchet ms | 8868 | 417 | | palatino | 5794 | 177 | | lucida sans unicode | 3525 | 116 | | sans-serif | 2947 | 216 | | times new roman | 2554 | 161 | | proxima-nova | 2076 | 36 | | droid sans | 1773 | 78 | | calibri | 1735 | 64 | | open sans | 1479 | 60 | | segoe ui | 1273 | 57 | +---------------------+-----------+---------+ 17 rows in set (19.43 sec) ``` Notice: I don't know the max width for each column a priori, and yet I would like to be able to that without going over the table twice. Should I add to the query length() for each column? How does MySQL do it, in order to not impact severely the memory or processing time? *EDIT* I did not think it was relevant to the question but, this is the query I send: ``` SELECT font.font as font,count(textfont.textid) as documents, count(DISTINCT td.domain) as domains FROM textfont RIGHT JOIN font ON textfont.fontid = font.fontid RIGHT JOIN ( SELECT text.text as text,url.domain as domain, text.textid as textid FROM text RIGHT JOIN url ON text.texturl = url.urlid) as td ON textfont.textid = td.textid WHERE textfont.fontpriority <= 0 AND textfont.textlen > 100 GROUP BY font.font HAVING documents >= 1000 AND domains >= 10 ORDER BY 2 DESC; ``` And this is the python code I use: ``` import MySQLdb as mdb print "%s\t\t\t%s\t\t%s" % ("font","documents","domains") res = cur.execute(query , (font_priority,text_len,min_texts,min_domains)) for res in cur.fetchall(): print "%s\t\t\t%d\t\t%d" % (res[0],res[1],res[2]) ``` But this code produces a messy output due to different widths.
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
Use [`prettytable`](http://code.google.com/p/prettytable/) ``` x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"]) x.set_field_align("City name", "l") # Left align city names x.set_padding_width(1) # One space between column edges and contents (default) x.add_row(["Adelaide",1295, 1158259, 600.5]) x.add_row(["Brisbane",5905, 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) print x +-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ | Adelaide | 1295 | 1158259 | 600.5 | | Brisbane | 5905 | 1857594 | 1146.4 | | Darwin | 112 | 120900 | 1714.7 | | Hobart | 1357 | 205556 | 619.5 | | Sydney | 2058 | 4336374 | 1214.8 | | Melbourne | 1566 | 3806092 | 646.9 | | Perth | 5386 | 1554769 | 869.4 | +-----------+------+------------+-----------------+ ```
The data is in some list it seems, and are printing the header. Consider some formatting like this: ``` res = ['trebuchet ms', 8868, 417] res = ['lucida sans unicode', 3525, 116] ``` and ``` print(' {0[0]:20s} {0[1]:10d} {0[2]:10d}'.format(res)) ``` give you ``` trebuchet ms 8868 417 lucida sans unicode 3525 116 ``` Notice the indexing into the list is done inside the string, `format` only needs to supply the list or tuple. *Alternatively*, you could specify widths programatically: ``` wid1 = 20 wid2 = 10 wid3 = 10 print(' {:{}s} {:{}d} {:{}d}'.format(res[0], wid1, res[1], wid2, res[2], wid3)) ``` which gives identical output as above. You'd have to adjust the field widths as required and loop through the list for each line of data instead of made up sample lines. Numbers are automatically right justified, string automatically left. Advantage, to some, is of course that this doesn't rely on any external libraries, and is done with what Python already provides. Learn More About String Formatting [here](https://www.python.org/dev/peps/pep-3101/)
4,591,125
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always return the same `True`(or `False`) with the pre-allocated `True`(or `False`)? Is it safe to replace `==` with `is` to compare Boolean-values? --- It's not about Best-Practice. I just want to know the Truth.
2011/01/04
[ "https://Stackoverflow.com/questions/4591125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348785/" ]
It seems that all answers deal with `True` and `False` as defined after an interpreter startup. Before booleans became part of Python they were often defined as part of a program. Even now (Python 2.6.6) they are only names that can be pointed to different objects: ``` >>> True = 1 >>> (2 > 1) True >>> (2 > 1) == True True >>> (2 > 1) is True False ``` If you have to deal with older software, be aware of that.
`==` and `is` are both comparison operators, which would return a boolean value - `True` or `False`. True has a numeric value of 1 and False has a numeric value of 0. The operator `==` compare the values of two objects and objects compared are most often are the same types (int vs int, float vs float), If you compare objects of different types, then they are unequal. The operator `is` tests for object identity, 'x is y' is true if both x and y have the same id. That is, they are same objects. So, when you are comparing if you comparing the return values of same type, use == and if you are comparing if two objects are same (be it boolean or anything else), you can use `is`. `42 is 42` is True and is same as `42 == 42`.
4,591,125
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always return the same `True`(or `False`) with the pre-allocated `True`(or `False`)? Is it safe to replace `==` with `is` to compare Boolean-values? --- It's not about Best-Practice. I just want to know the Truth.
2011/01/04
[ "https://Stackoverflow.com/questions/4591125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348785/" ]
It seems that all answers deal with `True` and `False` as defined after an interpreter startup. Before booleans became part of Python they were often defined as part of a program. Even now (Python 2.6.6) they are only names that can be pointed to different objects: ``` >>> True = 1 >>> (2 > 1) True >>> (2 > 1) == True True >>> (2 > 1) is True False ``` If you have to deal with older software, be aware of that.
Another reason to [compare values using `==`](https://docs.python.org/3/reference/expressions.html#comparisons) is that both `None` and `False` are [“falsy”](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false) values. And sometimes it’s useful to use `None` to mark a value as “not defined” or “no value” while considering `True` and `False` values to work with: ```py def some_function(val = None): """This function does an awesome thing.""" if val is None: # Values was not defined. elif val == False: # User passed boolean value. elif val == True: # User passed boolean value. else: # Quack quack. ``` Somewhat related question: [Python != operation vs “is not”](https://stackoverflow.com/questions/2209755/python-operation-vs-is-not).
4,591,125
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always return the same `True`(or `False`) with the pre-allocated `True`(or `False`)? Is it safe to replace `==` with `is` to compare Boolean-values? --- It's not about Best-Practice. I just want to know the Truth.
2011/01/04
[ "https://Stackoverflow.com/questions/4591125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348785/" ]
You probably shouldn't ever need to compare booleans. If you are doing something like: ``` if some_bool == True: ... ``` ...just change it to: ``` if some_bool: ... ``` No `is` or `==` needed. As commenters have pointed out, there are valid reasons to compare booleans. If both booleans are unknown and you want to know if one is equal to the other, you should use `==` or `!=` rather than `is` or `is not` (the reason is explained below). Note that this is logically equivalent to `xnor` and `xor` respectively, which don't exist as logical operators in Python. Internally, there should only ever be [two boolean literal objects](http://docs.python.org/library/functions.html#bool) (see also the [C API](http://docs.python.org/c-api/bool.html)), and `bool(x) is True` should be `True` if `bool(x) == True` for any Python program. Two caveats: * This *does not mean* that `x is True` if `x == True`, however (eg. `x = 1`). * This is true for the usual implementation of Python (CPython) but might not be true in other implementations. Hence `==` is a more reliable comparison.
It seems that all answers deal with `True` and `False` as defined after an interpreter startup. Before booleans became part of Python they were often defined as part of a program. Even now (Python 2.6.6) they are only names that can be pointed to different objects: ``` >>> True = 1 >>> (2 > 1) True >>> (2 > 1) == True True >>> (2 > 1) is True False ``` If you have to deal with older software, be aware of that.