qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
33,511,259
**How to find the majority votes for a list that can contain -1s, 1s and 0s?** For example, given a list of: ``` x = [-1, -1, -1, -1, 0] ``` The majority is -1 , so the output should return `-1` Another example, given a list of: ``` x = [1, 1, 1, 0, 0, -1] ``` The majority vote would be `1` And when we have a...
2015/11/03
[ "https://Stackoverflow.com/questions/33511259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
I am assuming that votes for 0 count as votes. So `sum` is not a reasonable option. Try a Counter: ``` >>> from collections import Counter >>> x = Counter([-1,-1,-1, 1,1,1,1,0,0,0,0,0,0,0,0]) >>> x Counter({0: 8, 1: 4, -1: 3}) >>> x.most_common(1) [(0, 8)] >>> x.most_common(1)[0][0] 0 ``` So you could write code li...
You could use [statistics.mode](https://docs.python.org/3/library/statistics.html#statistics.mode) if you were using python >= 3.4 ,catching a `StatisticsError` for when you have no unique mode: ``` from statistics import mode, StatisticsError def majority(l): try: return mode(l) except StatisticsErro...
33,511,259
**How to find the majority votes for a list that can contain -1s, 1s and 0s?** For example, given a list of: ``` x = [-1, -1, -1, -1, 0] ``` The majority is -1 , so the output should return `-1` Another example, given a list of: ``` x = [1, 1, 1, 0, 0, -1] ``` The majority vote would be `1` And when we have a...
2015/11/03
[ "https://Stackoverflow.com/questions/33511259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
``` # These are your actual votes votes = [-1, -1, -1, -1, 0] # These are the options on the ballot ballot = (-1, 0, 1) # This is to initialize your counters counters = {x: 0 for x in ballot} # Count the number of votes for vote in votes: counters[vote] += 1 results = counters.values().sort() if len(set(values...
``` import numpy as np def fn(vote): n=vote[np.where(vote<0)].size p=vote[np.where(vote>0)].size ret=np.sign(p-n) z=vote.size-p-n if z>=max(p,n): ret=0 return ret # some test cases print fn(np.array([-1,-1, 1,1,1,1,0,0,0,0,0,0,0,0])) print fn(np.array([-1, -1, -1, 1,1,1,0,0])) print fn(np.arra...
33,511,259
**How to find the majority votes for a list that can contain -1s, 1s and 0s?** For example, given a list of: ``` x = [-1, -1, -1, -1, 0] ``` The majority is -1 , so the output should return `-1` Another example, given a list of: ``` x = [1, 1, 1, 0, 0, -1] ``` The majority vote would be `1` And when we have a...
2015/11/03
[ "https://Stackoverflow.com/questions/33511259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
I am assuming that votes for 0 count as votes. So `sum` is not a reasonable option. Try a Counter: ``` >>> from collections import Counter >>> x = Counter([-1,-1,-1, 1,1,1,1,0,0,0,0,0,0,0,0]) >>> x Counter({0: 8, 1: 4, -1: 3}) >>> x.most_common(1) [(0, 8)] >>> x.most_common(1)[0][0] 0 ``` So you could write code li...
``` # These are your actual votes votes = [-1, -1, -1, -1, 0] # These are the options on the ballot ballot = (-1, 0, 1) # This is to initialize your counters counters = {x: 0 for x in ballot} # Count the number of votes for vote in votes: counters[vote] += 1 results = counters.values().sort() if len(set(values...
33,511,259
**How to find the majority votes for a list that can contain -1s, 1s and 0s?** For example, given a list of: ``` x = [-1, -1, -1, -1, 0] ``` The majority is -1 , so the output should return `-1` Another example, given a list of: ``` x = [1, 1, 1, 0, 0, -1] ``` The majority vote would be `1` And when we have a...
2015/11/03
[ "https://Stackoverflow.com/questions/33511259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
You could use [statistics.mode](https://docs.python.org/3/library/statistics.html#statistics.mode) if you were using python >= 3.4 ,catching a `StatisticsError` for when you have no unique mode: ``` from statistics import mode, StatisticsError def majority(l): try: return mode(l) except StatisticsErro...
``` from collections import Counter result = Counter(votes).most_common(2) result = 0 if result[0][1] == result[1][1] else result[0][0] ``` Error handling for empty `votes` lists or `votes` lists with a set cardinality of 1 is trivial and left as an exercise for the reader.
7,692,121
I saw [this question](https://stackoverflow.com/questions/4978738/is-there-a-python-equivalent-of-the-c-null-coalescing-operator) but it uses the ?? operator as a null check, I want to use it as a bool true/false test. I have this code in Python: ``` if self.trait == self.spouse.trait: trait = self.trait else: ...
2011/10/07
[ "https://Stackoverflow.com/questions/7692121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116286/" ]
Yes, you can write: ``` trait = self.trait if self.trait == self.spouse.trait else defaultTrait ``` This is called a [Conditional Expression](http://docs.python.org/reference/expressions.html#conditional-expressions) in Python.
On the null-coalescing operator in C#, what you have in the question isn't a correct usage. That would fail at compile time. In C#, the correct way to write what you're attempting would be this: ``` trait = this.trait == this.spouse.trait ? self.trait : defaultTrait ``` Null coalesce in C# returns the first value t...
42,871,090
As the title says, is there a way to change the default pip to pip2.7 When I run `sudo which pip`, I get `/usr/local/bin/pip` When I run `sudo pip -V`, I get `pip 1.5.6 from /usr/lib/python3/dist-packages (python 3.4)` If there is no problem at all with this mixed version, please do tell. If there is a problem with ...
2017/03/18
[ "https://Stackoverflow.com/questions/42871090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2400585/" ]
* You can use `alias pip = 'pip2.7'`Put this in your `.bashrc` file(If you're using bash,if zsh it should be `.zshrc`). By the way,you should know that `sudo` command change current user,default `root`.So if you have to change user to `root`,maybe you should put it in `/root/.bashrc` * Or you can make a link ``` ln -...
A very intuitive and straightforward method is just modify the settings in `/usr/local/bin/pip`. You don't need alias and symbolic links. For mine: 1. Check the infor: =================== ``` lerner@lerner:~/$ pip -V ``` > > `pip 1.5.4 from /usr/lib/python3/dist-packages (python 3.4)` > > > ``` lerner@lerner:...
42,871,090
As the title says, is there a way to change the default pip to pip2.7 When I run `sudo which pip`, I get `/usr/local/bin/pip` When I run `sudo pip -V`, I get `pip 1.5.6 from /usr/lib/python3/dist-packages (python 3.4)` If there is no problem at all with this mixed version, please do tell. If there is a problem with ...
2017/03/18
[ "https://Stackoverflow.com/questions/42871090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2400585/" ]
**Concise Answer** 1.  Locate pip: ``` $ which pip /usr/local/bin/pip ``` 2.  List all pips in location learned above: ``` $ ls /usr/local/bin/pip* /usr/local/bin/pip /usr/local/bin/pip2.7 /usr/local/bin/pip3.5 /usr/local/bin/pip2 /usr/local/bin/pip3 ``` 3.  Select which one should be your default, i.e. `/us...
* You can use `alias pip = 'pip2.7'`Put this in your `.bashrc` file(If you're using bash,if zsh it should be `.zshrc`). By the way,you should know that `sudo` command change current user,default `root`.So if you have to change user to `root`,maybe you should put it in `/root/.bashrc` * Or you can make a link ``` ln -...
42,871,090
As the title says, is there a way to change the default pip to pip2.7 When I run `sudo which pip`, I get `/usr/local/bin/pip` When I run `sudo pip -V`, I get `pip 1.5.6 from /usr/lib/python3/dist-packages (python 3.4)` If there is no problem at all with this mixed version, please do tell. If there is a problem with ...
2017/03/18
[ "https://Stackoverflow.com/questions/42871090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2400585/" ]
**Concise Answer** 1.  Locate pip: ``` $ which pip /usr/local/bin/pip ``` 2.  List all pips in location learned above: ``` $ ls /usr/local/bin/pip* /usr/local/bin/pip /usr/local/bin/pip2.7 /usr/local/bin/pip3.5 /usr/local/bin/pip2 /usr/local/bin/pip3 ``` 3.  Select which one should be your default, i.e. `/us...
A very intuitive and straightforward method is just modify the settings in `/usr/local/bin/pip`. You don't need alias and symbolic links. For mine: 1. Check the infor: =================== ``` lerner@lerner:~/$ pip -V ``` > > `pip 1.5.4 from /usr/lib/python3/dist-packages (python 3.4)` > > > ``` lerner@lerner:...
67,948,945
I want to force the Huggingface transformer (BERT) to make use of CUDA. nvidia-smi showed that all my CPU cores were maxed out during the code execution, but my GPU was at 0% utilization. Unfortunately, I'm new to the Hugginface library as well as PyTorch and don't know where to place the CUDA attributes `device = cuda...
2021/06/12
[ "https://Stackoverflow.com/questions/67948945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15445597/" ]
You can make the entire class inherit `torch.nn.Module` like so: ``` class SentimentModel_t(torch.nn.Module): def __init___(...) super(SentimentModel_t, self).__init__() ... ``` Upon initializing your model you can then call `.to(device)` to cast it to the device of your choice, like so: ``` sentiment_m...
I am a bit late to the party. The python package that I wrote already uses your GPU. You can have a look at the [code to see how it was implemented](https://github.com/oliverguhr/german-sentiment-lib/blob/master/germansentiment/sentimentmodel.py) Just install the package: ``` pip install germansentiment ``` and run...
39,502,345
I have two columns in a pandas dataframe that are supposed to be identical. Each column has many NaN values. I would like to compare the columns, producing a 3rd column containing True / False values; *True* when the columns match, *False* when they do not. This is what I have tried: ``` df['new_column'] = (df['colum...
2016/09/15
[ "https://Stackoverflow.com/questions/39502345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1762492/" ]
Or you could just use the `equals` method: ``` df['new_column'] = df['column_one'].equals(df['column_two']) ``` It is a batteries included approach, and will work no matter the `dtype` or the content of the cells. You can also put it in a loop, if you want.
To my understanding, Pandas does not consider NaNs different in element-wise equality and inequality comparison methods. While it does when comparing entire Pandas objects (Series, DataFrame, Panel). > > NaN values are considered different (i.e. NaN != NaN). - [source](https://pandas.pydata.org/pandas-docs/stable/ref...
39,502,345
I have two columns in a pandas dataframe that are supposed to be identical. Each column has many NaN values. I would like to compare the columns, producing a 3rd column containing True / False values; *True* when the columns match, *False* when they do not. This is what I have tried: ``` df['new_column'] = (df['colum...
2016/09/15
[ "https://Stackoverflow.com/questions/39502345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1762492/" ]
Or you could just use the `equals` method: ``` df['new_column'] = df['column_one'].equals(df['column_two']) ``` It is a batteries included approach, and will work no matter the `dtype` or the content of the cells. You can also put it in a loop, if you want.
You can use a loop like below and it works irrespective of whether your dataframe contains NANs or not as long as both the columns are having same format ``` def Check(df): if df['column_one']== df['column_two']: return "True" else: return "False" df['result'] = df.apply(Check, axis=1) df ```
39,502,345
I have two columns in a pandas dataframe that are supposed to be identical. Each column has many NaN values. I would like to compare the columns, producing a 3rd column containing True / False values; *True* when the columns match, *False* when they do not. This is what I have tried: ``` df['new_column'] = (df['colum...
2016/09/15
[ "https://Stackoverflow.com/questions/39502345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1762492/" ]
Or you could just use the `equals` method: ``` df['new_column'] = df['column_one'].equals(df['column_two']) ``` It is a batteries included approach, and will work no matter the `dtype` or the content of the cells. You can also put it in a loop, if you want.
Working also for None values. ``` df['are_equal'] = df['a'].eq(df_f['b']) ``` result df:[![enter image description here](https://i.stack.imgur.com/FujYb.png)](https://i.stack.imgur.com/FujYb.png)
65,583,958
I've a Python program as follows: ``` class a: def __init__(self,n): self.n=n def __del__(self,n): print('dest',self.n,n) def b(): d=a('d') c=a('c') d.__del__(8) b() ``` Here, I have given a parameter `n` in `__del__()` just to clear my doubt. Its output : ``` $ python des.py d...
2021/01/05
[ "https://Stackoverflow.com/questions/65583958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
you cannot. pre-defined dunder methods (methods with leading and trailing double underscore) like `__del__` have a fixed signature. If you define them with another signature, then when python calls them using the non-dunder interface (`del`, `len`, ...), the number of arguments is wrong and it fails. To pass `n` to `...
Python objects become a candidate for garbage collection when there are no more references to them (object tagging), so you do not need to create such a destructor. If you want to add optional arguments to a method, it's common to set them to `None` or an empty tuple `()` ``` def other_del(self, x=None): ...
65,583,958
I've a Python program as follows: ``` class a: def __init__(self,n): self.n=n def __del__(self,n): print('dest',self.n,n) def b(): d=a('d') c=a('c') d.__del__(8) b() ``` Here, I have given a parameter `n` in `__del__()` just to clear my doubt. Its output : ``` $ python des.py d...
2021/01/05
[ "https://Stackoverflow.com/questions/65583958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can *define* the `__del__` method with an argument, as you've shown. And if you call the method yourself, you can pass in a value, just like you can with any other method. But when the interpreter calls `__del__` itself, it's not going to pass anything, and there will be an exception raised. However, because `__de...
you cannot. pre-defined dunder methods (methods with leading and trailing double underscore) like `__del__` have a fixed signature. If you define them with another signature, then when python calls them using the non-dunder interface (`del`, `len`, ...), the number of arguments is wrong and it fails. To pass `n` to `...
65,583,958
I've a Python program as follows: ``` class a: def __init__(self,n): self.n=n def __del__(self,n): print('dest',self.n,n) def b(): d=a('d') c=a('c') d.__del__(8) b() ``` Here, I have given a parameter `n` in `__del__()` just to clear my doubt. Its output : ``` $ python des.py d...
2021/01/05
[ "https://Stackoverflow.com/questions/65583958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can *define* the `__del__` method with an argument, as you've shown. And if you call the method yourself, you can pass in a value, just like you can with any other method. But when the interpreter calls `__del__` itself, it's not going to pass anything, and there will be an exception raised. However, because `__de...
Python objects become a candidate for garbage collection when there are no more references to them (object tagging), so you do not need to create such a destructor. If you want to add optional arguments to a method, it's common to set them to `None` or an empty tuple `()` ``` def other_del(self, x=None): ...
18,485,044
It's not under the supported libraries here: <https://developers.google.com/api-client-library/python/reference/supported_apis> Is it just not available with Python? If not, what language is it available for?
2013/08/28
[ "https://Stackoverflow.com/questions/18485044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2721465/" ]
Andre's answer points you at a correct place to reference the API. Since your question was python specific, allow me to show you a basic approach to building your submitted search URL in python. This example will get you all the way to search content in just a few minutes after you sign up for Google's free API key. `...
Somebody has written a wrapper for the API: <https://github.com/slimkrazy/python-google-places> Basically it's just HTTP with JSON responses. It's easier to access through JavaScript but it's just as easy to use `urllib` and the `json` library to connect to the API.
18,485,044
It's not under the supported libraries here: <https://developers.google.com/api-client-library/python/reference/supported_apis> Is it just not available with Python? If not, what language is it available for?
2013/08/28
[ "https://Stackoverflow.com/questions/18485044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2721465/" ]
Andre's answer points you at a correct place to reference the API. Since your question was python specific, allow me to show you a basic approach to building your submitted search URL in python. This example will get you all the way to search content in just a few minutes after you sign up for Google's free API key. `...
Ezekiel's answer worked great for me and all of the credit goes to him. I had to change his code in order for it to work with python3. Below is the code I used: ``` def build_URL(search_text='',types_text=''): base_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json' key_string = '?key=' + ACCESS...
18,485,044
It's not under the supported libraries here: <https://developers.google.com/api-client-library/python/reference/supported_apis> Is it just not available with Python? If not, what language is it available for?
2013/08/28
[ "https://Stackoverflow.com/questions/18485044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2721465/" ]
Somebody has written a wrapper for the API: <https://github.com/slimkrazy/python-google-places> Basically it's just HTTP with JSON responses. It's easier to access through JavaScript but it's just as easy to use `urllib` and the `json` library to connect to the API.
Ezekiel's answer worked great for me and all of the credit goes to him. I had to change his code in order for it to work with python3. Below is the code I used: ``` def build_URL(search_text='',types_text=''): base_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json' key_string = '?key=' + ACCESS...
37,659,072
I'm new with python and I have to sort by date a voluminous file text with lot of line like these: ``` CCC!LL!EEEE!EW050034!2016-04-01T04:39:54.000Z!7!1!1!1 CCC!LL!EEEE!GH676589!2016-04-01T04:39:54.000Z!7!1!1!1 CCC!LL!EEEE!IJ6758004!2016-04-01T04:39:54.000Z!7!1!1!1 ``` Can someone help me please ? Thank y...
2016/06/06
[ "https://Stackoverflow.com/questions/37659072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4989650/" ]
Have you considered using the \*nix [`sort`](http://linux.die.net/man/1/sort) program? in raw terms, it'll probably be faster than most Python scripts. Use `-t \!` to specify that columns are separated by a `!` char, `-k n` to specify the field, where `n` is the field number, and `-o outputfile` if you want to output...
I would like to convert the time to timestamp then sort. first convert the date to list. ``` rawData = '''CCC!LL!EEEE!EW050034!2016-04-01T04:39:54.000Z!7!1!1!1 CCC!LL!EEEE!GH676589!2016-04-01T04:39:54.000Z!7!1!1!1 CCC!LL!EEEE!IJ6758004!2016-04-01T04:39:54.000Z!7!1!1!1''' a = rawData.split('\n') >>> import dateu...
37,659,072
I'm new with python and I have to sort by date a voluminous file text with lot of line like these: ``` CCC!LL!EEEE!EW050034!2016-04-01T04:39:54.000Z!7!1!1!1 CCC!LL!EEEE!GH676589!2016-04-01T04:39:54.000Z!7!1!1!1 CCC!LL!EEEE!IJ6758004!2016-04-01T04:39:54.000Z!7!1!1!1 ``` Can someone help me please ? Thank y...
2016/06/06
[ "https://Stackoverflow.com/questions/37659072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4989650/" ]
Have you considered using the \*nix [`sort`](http://linux.die.net/man/1/sort) program? in raw terms, it'll probably be faster than most Python scripts. Use `-t \!` to specify that columns are separated by a `!` char, `-k n` to specify the field, where `n` is the field number, and `-o outputfile` if you want to output...
Take a look into regular expression module, I've used it a couple of times and it looks lretty simple to do what you want with this module <https://docs.python.org/2/library/re.html> Here is the docs but try googling for regular expression python examples to make it more clear, good luck.
42,620,323
I am trying to parse many files found in a directory, however using multiprocessing slows my program. ``` # Calling my parsing function from Client. L = getParsedFiles('/home/tony/Lab/slicedFiles') <--- 1000 .txt files found here. combined ~100MB ``` Following ...
2017/03/06
[ "https://Stackoverflow.com/questions/42620323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6530695/" ]
Looks like you're [I/O bound](https://en.wikipedia.org/wiki/I/O_bound): > > In computer science, I/O bound refers to a condition in which the time it takes to complete a computation is determined principally by the period spent waiting for input/output operations to be completed. This is the opposite of a task being ...
In general it is never a good idea to read from the same physical (spinning) hard disk from different threads simultaneously, because every switch causes an extra delay of around 10ms to position the read head of the hard disk (would be different on SSD). As @peter-wood already said, it is better to have one thread re...
42,620,323
I am trying to parse many files found in a directory, however using multiprocessing slows my program. ``` # Calling my parsing function from Client. L = getParsedFiles('/home/tony/Lab/slicedFiles') <--- 1000 .txt files found here. combined ~100MB ``` Following ...
2017/03/06
[ "https://Stackoverflow.com/questions/42620323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6530695/" ]
Looks like you're [I/O bound](https://en.wikipedia.org/wiki/I/O_bound): > > In computer science, I/O bound refers to a condition in which the time it takes to complete a computation is determined principally by the period spent waiting for input/output operations to be completed. This is the opposite of a task being ...
A copy-paste snippet, for people who come from Google and don't like reading Example is for json reading, just replace `__single_json_loader` with another file type to work with that. ``` from multiprocessing import Pool from typing import Callable, Any, Iterable import os import json def parallel_file_read(existing...
42,620,323
I am trying to parse many files found in a directory, however using multiprocessing slows my program. ``` # Calling my parsing function from Client. L = getParsedFiles('/home/tony/Lab/slicedFiles') <--- 1000 .txt files found here. combined ~100MB ``` Following ...
2017/03/06
[ "https://Stackoverflow.com/questions/42620323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6530695/" ]
In general it is never a good idea to read from the same physical (spinning) hard disk from different threads simultaneously, because every switch causes an extra delay of around 10ms to position the read head of the hard disk (would be different on SSD). As @peter-wood already said, it is better to have one thread re...
A copy-paste snippet, for people who come from Google and don't like reading Example is for json reading, just replace `__single_json_loader` with another file type to work with that. ``` from multiprocessing import Pool from typing import Callable, Any, Iterable import os import json def parallel_file_read(existing...
56,465,109
I am looking for an example of using python multiprocessing (i.e. a process-pool/threadpool, job queue etc.) with hylang.
2019/06/05
[ "https://Stackoverflow.com/questions/56465109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7740698/" ]
The first example from the [`multiprocessing`](https://docs.python.org/3/library/multiprocessing.html) documentation can be literally translated to Hy like so: ``` (import multiprocessing [Pool]) (defn f [x] (* x x)) (when (= __name__ "__main__") (with [p (Pool 5)] (print (.map p f [1 2 3])))) ```
Note that a straightforward translation runs into a problem on macOS (which is not officially supported, but mostly works anyway): Hy sets `sys.executable` to the Hy interpreter, and `multiprocessing` relies on that value to start up new processes. You can work around that particular problem by calling `(multiprocessin...
38,217,594
[Distinguishable objects into distinguishable boxes](https://math.stackexchange.com/questions/468824/distinguishable-objects-into-distinguishable-boxes?rq=1) It is very similar to this question posted. I'm trying to get python code for this question. Note although it is similar there is a key difference. i.e. A bucke...
2016/07/06
[ "https://Stackoverflow.com/questions/38217594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6055596/" ]
I think there is no way to combine more than one language in one editor. Please refer to this link. <https://www.tinymce.com/docs/configure/localization/#language> TinyMce is made for simplicity and easyness. If you want to have more than one language that points to one ID please play around with your Database Desi...
Actually now you can add languages in Tinymce by downloading different languages packages and integrating it with your editor. <https://www.tiny.cloud/docs/configure/localization/> here you will find the list of Available Language Packages and how to use them
50,311,713
Hello I'm trying to make a python script to loop text and toggle through it. I'm able to get python to toggle through the text once but what I cant get it to do is to keep toggling through the text. After it toggles through the text once I get a message that says Traceback (most recent call last): File "test.py", lin...
2018/05/13
[ "https://Stackoverflow.com/questions/50311713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9394080/" ]
> > Is this not redundant?? > > > Maybe it is redundant for instance methods and constructors. It isn't redundant for static methods or class initialization pseudo-methods. --- It is also possible that the (supposedly) redundant reference gets optimized away by the JIT compiler. (Or maybe it isn't optimized aw...
> > The stack frame will contain the "current class constant pool reference" and also it will have the reference to the object in heap which in turn will also point to the class data. Is this not redundant?? > > > You missed the precondition of that statement, or you misquoted it, or it was just plainly wrong wher...
50,311,713
Hello I'm trying to make a python script to loop text and toggle through it. I'm able to get python to toggle through the text once but what I cant get it to do is to keep toggling through the text. After it toggles through the text once I get a message that says Traceback (most recent call last): File "test.py", lin...
2018/05/13
[ "https://Stackoverflow.com/questions/50311713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9394080/" ]
> > Is this not redundant?? > > > Maybe it is redundant for instance methods and constructors. It isn't redundant for static methods or class initialization pseudo-methods. --- It is also possible that the (supposedly) redundant reference gets optimized away by the JIT compiler. (Or maybe it isn't optimized aw...
There are two points here. First, there are `static` methods which are invoked without a `this` reference. Second, the actual class of an object instance is not necessarily the declaring class of the method whose code we are actually executing. The purpose of the constant pool reference is to enable resolving of symbol...
50,311,713
Hello I'm trying to make a python script to loop text and toggle through it. I'm able to get python to toggle through the text once but what I cant get it to do is to keep toggling through the text. After it toggles through the text once I get a message that says Traceback (most recent call last): File "test.py", lin...
2018/05/13
[ "https://Stackoverflow.com/questions/50311713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9394080/" ]
> > The stack frame will contain the "current class constant pool reference" and also it will have the reference to the object in heap which in turn will also point to the class data. Is this not redundant?? > > > You missed the precondition of that statement, or you misquoted it, or it was just plainly wrong wher...
There are two points here. First, there are `static` methods which are invoked without a `this` reference. Second, the actual class of an object instance is not necessarily the declaring class of the method whose code we are actually executing. The purpose of the constant pool reference is to enable resolving of symbol...
69,416,562
I have this simple csv: ``` date,count 2020-07-09,144.0 2020-07-10,143.5 2020-07-12,145.5 2020-07-13,144.5 2020-07-14,146.0 2020-07-20,145.5 2020-07-21,146.0 2020-07-24,145.5 2020-07-28,143.0 2020-08-05,146.0 2020-08-10,147.0 2020-08-11,147.5 2020-08-14,146.5 2020-09-01,143.5 2020-09-02,143.0 2020-09-09,144.5 2020-09-...
2021/10/02
[ "https://Stackoverflow.com/questions/69416562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7503046/" ]
I made some research and found this: [how to close server on ctrl+c when in no-daemon](https://github.com/Unitech/pm2/issues/2833#issuecomment-298560152) ```sh pm2 kill && pm2 start ecosystem.json --only dev --no-daemon ``` It works if you run pm2 alone but you are running 2 programs together, so give it a try below...
I've created `dev.sh` script: ``` #!/bin/bash yarn pm2:del yarn pm2:dev yarn wp:dev yarn pm2:del ``` And run it using `yarn dev`: ``` "scripts": { "dev": "sh ./scripts/dev.sh", "pm2:dev": "pm2 start ecosystem.config.js --only dev", "pm2:del": "pm2 delete all || exit 0", "wp:dev": "webpack --mode=de...
61,819,993
I'm trying to run a Python script from a (windows/c#) background process. I'm successfully getting python.exe to run with the script file, but it's erroring out on the first line, "import pandas as pd". The exact error I'm getting from stderr is... Traceback (most recent call last): File "predictX.py", line 1, in i...
2020/05/15
[ "https://Stackoverflow.com/questions/61819993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13507069/" ]
You should install it in your desktop before using it. ``` $ pip install pandas ``` Then it should work fine. If not, try un-install and re-install it. [EDIT] Anaconda is a package for python which includes more module that wasn't included in the original python installer. So the script can run in Anaconda, but not...
Pilot error... Apparently there are at least two python.exe files on my computer. I changed the path to reflect the one under the Anaconda folder and everything came right up.
14,974,659
Please bear with me as I'm new to Python/Django/Unix in general. I'm learning how to use different `settings.py` files for local and production environments. The following is from the section on the `--settings` option in [the official Django docs page on `django-admin.py`](https://docs.djangoproject.com/en/1.5/ref/...
2013/02/20
[ "https://Stackoverflow.com/questions/14974659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/312462/" ]
the `--settings` flag takes a dotted Python path, not a relative path on your filesystem. Meaning `--settings=mysite/local` should actually be `--settings=mysite.local`. If your current working directory is your project root when you run `django-admin`, then you shouldn't have to touch your `PYTHONPATH`.
You have to replace `/` with `.` ``` $ django-admin.py runserver --settings=mysite.local ``` You can update PYTHONPATH in the `manage.py` too. Inside `if __name__ == "__main__":` add the following. ``` import sys sys.path.append(additional_path) ```
22,429,004
I have multiple forms in a html file, which all call the same python cgi script. For example: ``` <html> <body> <form method="POST" name="form1" action="script.cgi" enctype="multipart/data-form"> .... </form> ... <form method="POST" name="form2" action="script.cgi" enctype="multipart/data-form"> ... </form> ... </body...
2014/03/15
[ "https://Stackoverflow.com/questions/22429004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2415118/" ]
You cannot. The browser submits one form, or the other, but not both. If you need data from both forms, merge the forms into one `<form>` tag instead.
First, `FieldStorage()` consumes standard input, so it should only be instantiated once. Second, only the data in the submitted form is sent to the server. The other forms may as well not exist. So while you can use the same cgi script to process both forms, if you need process both forms at the same time, as Martij...
46,511,011
The question has racked my brains There are 26 underscores presenting English alphabet in-sequence. means that letter a,b and g should be substituted by the letter k, j and r respectively, while all the other letters are not substituted. how do I do like this? How can python detect each underscore = each English alp...
2017/10/01
[ "https://Stackoverflow.com/questions/46511011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could use `str.translate`: ``` In [8]: from string import ascii_lowercase In [9]: text.translate({ord(l): l if g == '_' else g for g, l in zip(guess, ascii_lowercase)}) Out[9]: 'i km jen .' ``` This maps elements of `string.ascii_lowercase` to elements of `guess` (by position). If an element of `guess` is the u...
If you had a list of the alphabet, then the list of underscores, enter a for loop and then just compare the two values, appending to a list if it does or doesn’t
46,511,011
The question has racked my brains There are 26 underscores presenting English alphabet in-sequence. means that letter a,b and g should be substituted by the letter k, j and r respectively, while all the other letters are not substituted. how do I do like this? How can python detect each underscore = each English alp...
2017/10/01
[ "https://Stackoverflow.com/questions/46511011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could use `str.translate`: ``` In [8]: from string import ascii_lowercase In [9]: text.translate({ord(l): l if g == '_' else g for g, l in zip(guess, ascii_lowercase)}) Out[9]: 'i km jen .' ``` This maps elements of `string.ascii_lowercase` to elements of `guess` (by position). If an element of `guess` is the u...
``` >>> text = "i am ben ." >>> guess = "kj____r___________________" >>> d = dict() >>> for i in xrange(len(guess)): ... if(guess[i] != "_"): ... d[chr(i+97)] = guess[i] ... >>> d {'a': 'k', 'b': 'j', 'g': 'r'} >>> text_list = list(text) >>> text_list ['i', ' ', 'a', 'm', ' ', 'b', 'e', 'n', ' ', '.']...
46,511,011
The question has racked my brains There are 26 underscores presenting English alphabet in-sequence. means that letter a,b and g should be substituted by the letter k, j and r respectively, while all the other letters are not substituted. how do I do like this? How can python detect each underscore = each English alp...
2017/10/01
[ "https://Stackoverflow.com/questions/46511011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could use `str.translate`: ``` In [8]: from string import ascii_lowercase In [9]: text.translate({ord(l): l if g == '_' else g for g, l in zip(guess, ascii_lowercase)}) Out[9]: 'i km jen .' ``` This maps elements of `string.ascii_lowercase` to elements of `guess` (by position). If an element of `guess` is the u...
Zip them: ``` import string zipped = zip(string.ascii_lowercase, "kj____r___________________") print(zipped) # [('a', 'k'), ('b', 'j'), ('c', '_'), ('d', '_'), ('e', '_'), ('f', '_'), ('g', 'r'), ('h', '_'), ('i', '_'), ('j', '_'), ('k', '_'), ('l', '_'), ('m', '_'), ('n', '_'), ('o', '_'), ('p', '_'), ('q', '_'), ('...
46,511,011
The question has racked my brains There are 26 underscores presenting English alphabet in-sequence. means that letter a,b and g should be substituted by the letter k, j and r respectively, while all the other letters are not substituted. how do I do like this? How can python detect each underscore = each English alp...
2017/10/01
[ "https://Stackoverflow.com/questions/46511011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could use `str.translate`: ``` In [8]: from string import ascii_lowercase In [9]: text.translate({ord(l): l if g == '_' else g for g, l in zip(guess, ascii_lowercase)}) Out[9]: 'i km jen .' ``` This maps elements of `string.ascii_lowercase` to elements of `guess` (by position). If an element of `guess` is the u...
Let's solve your issue step by step without making it too much complicated: > > First step : > > > So first step is data gathering which user providing or you already have : Suppose you have one list of a-z alphabets and other list have replaced "\_" underscore and letters : if you don't have let's gather data ...
73,646,972
I am using the following function to estimate the Gaussian window rolling average of my timeseries. Though it works great from small size averaging windows, it crushes (or gets extremely slow) for larger averaging windows. ``` def norm_factor_Gauss_window(s, dt): numer = np.arange(-3*s, 3*s+dt, dt) mu...
2022/09/08
[ "https://Stackoverflow.com/questions/73646972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15353940/" ]
Using [numba njit decorator](https://numba.pydata.org/numba-doc/latest/user/parallel.html?highlight=njit) on `norm_factor_Gauss_window` function on my pc I get a **10x** speed up (from 10µs to 1µs) on the execution time of this function. ``` import numba as nb @nb.njit(nogil=True) def norm_factor_Gauss_window(s, dt):...
I was able to drastically improve the speed of this code using the following: ``` from scipy import signal def norm_factor_Gauss_window(s, dt): numer = np.arange(-3*s, 3*s+dt, dt) multiplic_fac = np.exp(-(numer)**2/(2*s**2)) norm_factor = np.sum(multiplic_fac) window = len(multiplic_f...
8,765,568
I am trying to make a windows executable from a python script that uses matplotlib and it seems that I am getting a common error. > > File "run.py", line 29, in > import matplotlib.pyplot as plt File "matplotlib\pyplot.pyc", line 95, in File "matplotlib\backends\_\_init\_\_.pyc", line > 25, in pylab\_setup ImportE...
2012/01/06
[ "https://Stackoverflow.com/questions/8765568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/842785/" ]
First, the easy question, is that backend installed? On my Fedora system I had to install it separately from the base matplotlib. At a Python console can you: ``` >>> import matplotlib.backends.backend_tkagg ``` If that works, then force py2exe to include it. In your config: ``` opts = { 'py2exe': { "includes" ...
If you are using py2exe it doesn't handle .egg formatted Python modules. If you used easy\_install to install the trouble module then you might only have the .egg version. See the py2exe site for more info on how to fix it. <http://www.py2exe.org/index.cgi/ExeWithEggs>
8,765,568
I am trying to make a windows executable from a python script that uses matplotlib and it seems that I am getting a common error. > > File "run.py", line 29, in > import matplotlib.pyplot as plt File "matplotlib\pyplot.pyc", line 95, in File "matplotlib\backends\_\_init\_\_.pyc", line > 25, in pylab\_setup ImportE...
2012/01/06
[ "https://Stackoverflow.com/questions/8765568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/842785/" ]
First, the easy question, is that backend installed? On my Fedora system I had to install it separately from the base matplotlib. At a Python console can you: ``` >>> import matplotlib.backends.backend_tkagg ``` If that works, then force py2exe to include it. In your config: ``` opts = { 'py2exe': { "includes" ...
This works well from distutils.core import setup import py2exe, sys, os import matplotlib sys.setrecursionlimit(12000) sys.argv.append('py2exe') setup( options = { "py2exe" : { "bundle\_files":3, "compressed":True, "includes" : ["matplotlib.backends.backend\_tkagg"] } }, windows = [{"script": "script.py"}], ...
8,765,568
I am trying to make a windows executable from a python script that uses matplotlib and it seems that I am getting a common error. > > File "run.py", line 29, in > import matplotlib.pyplot as plt File "matplotlib\pyplot.pyc", line 95, in File "matplotlib\backends\_\_init\_\_.pyc", line > 25, in pylab\_setup ImportE...
2012/01/06
[ "https://Stackoverflow.com/questions/8765568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/842785/" ]
First, the easy question, is that backend installed? On my Fedora system I had to install it separately from the base matplotlib. At a Python console can you: ``` >>> import matplotlib.backends.backend_tkagg ``` If that works, then force py2exe to include it. In your config: ``` opts = { 'py2exe': { "includes" ...
Run the following command to install the backend\_tkagg For centos -- **sudo yum install python-matplotlib-tk** This should work.
8,765,568
I am trying to make a windows executable from a python script that uses matplotlib and it seems that I am getting a common error. > > File "run.py", line 29, in > import matplotlib.pyplot as plt File "matplotlib\pyplot.pyc", line 95, in File "matplotlib\backends\_\_init\_\_.pyc", line > 25, in pylab\_setup ImportE...
2012/01/06
[ "https://Stackoverflow.com/questions/8765568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/842785/" ]
If you are using py2exe it doesn't handle .egg formatted Python modules. If you used easy\_install to install the trouble module then you might only have the .egg version. See the py2exe site for more info on how to fix it. <http://www.py2exe.org/index.cgi/ExeWithEggs>
This works well from distutils.core import setup import py2exe, sys, os import matplotlib sys.setrecursionlimit(12000) sys.argv.append('py2exe') setup( options = { "py2exe" : { "bundle\_files":3, "compressed":True, "includes" : ["matplotlib.backends.backend\_tkagg"] } }, windows = [{"script": "script.py"}], ...
8,765,568
I am trying to make a windows executable from a python script that uses matplotlib and it seems that I am getting a common error. > > File "run.py", line 29, in > import matplotlib.pyplot as plt File "matplotlib\pyplot.pyc", line 95, in File "matplotlib\backends\_\_init\_\_.pyc", line > 25, in pylab\_setup ImportE...
2012/01/06
[ "https://Stackoverflow.com/questions/8765568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/842785/" ]
If you are using py2exe it doesn't handle .egg formatted Python modules. If you used easy\_install to install the trouble module then you might only have the .egg version. See the py2exe site for more info on how to fix it. <http://www.py2exe.org/index.cgi/ExeWithEggs>
Run the following command to install the backend\_tkagg For centos -- **sudo yum install python-matplotlib-tk** This should work.
46,006,513
I'm trying to evaluate the accuracy of an algorithm that segments regions in 3D MRI Volumes (Brain). I've been using Dice, Jaccard, FPR, TNR, Precision... etc but I've only done this pixelwise (I.E. FNs= number of false neg pixels). Is there a python package (or pseudo code) out there to do this at the lesion level? Fo...
2017/09/01
[ "https://Stackoverflow.com/questions/46006513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7914014/" ]
You could use scipy's [`label`](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.measurements.label.html) to find connected components in an image: ``` from scipy.ndimage.measurements import label label_pred, numobj_pred = label(my_predictions) label_true, numobj_true = label(my_groundtruth) ...
Here is the code I ended up writing to do this task. Please let me know if anyone sees any errors. ``` def distance(p1, p2,dim): if dim==2: return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2) elif dim==3: return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2+ (p2[2] - p1[2])**2) else: print 'error...
67,959,301
I want to print the code exactly after one min ``` import time from datetime import datetime while True: time.sleep(1) now = datetime.now() current_datetime = now.strftime("%d-%m-%Y %H:%M:%S") if current_datetime==today.strftime("%d-%m-%Y") + "09:15:00": sec = 60 time.sleep(sec) ...
2021/06/13
[ "https://Stackoverflow.com/questions/67959301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
No. They are different things. Auto-incremented columns in MySQL are not guaranteed to be gapless. Gaps can occur for multiple reasons. The most common are: * Concurrent transactions. * Deletion. It sounds like you have a unique identifier in Java which is either redundant or an item of data. If the latter, then add ...
It isn't compulsory to create and unique id field in the database . You can instead change the table like--> ``` CREATE TABLE companies ( 'COMPANYID' int NOT NULL, `NAME` varchar(200) DEFAULT NULL, `EMAIL` varchar(200) DEFAULT NULL, `PASSWORD` varchar(200) DEFAULT NULL, PRIMARY KEY (`ID`) ``` since you are...
39,852,963
I have the following list of tuples already sorted, with "sorted" in python: ``` L = [("1","blaabal"), ("1.2","bbalab"), ("10","ejej"), ("11.1","aaua"), ("12.1","ehjej"), ("12.2 (c)", "ekeke"), ("12.2 (d)", "qwerty"), ("2.1","baala"), ("3","yuio"), ("4","poku"), ("5....
2016/10/04
[ "https://Stackoverflow.com/questions/39852963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6726377/" ]
Since the first element in each tuple is a string, Python is performing lexographic sorting in which all strings that start with `'1'` come before strings that start with a `'2'`. To get the sorting you desire, you'll want to treat the first entry *as a `float`* instead of a string. We can use `sorted` along with a c...
The first value of your tuples are strings, and are being sorted in lexicographic order. If you want them to remain strings, sort with ``` sorted(l, key = lambda x: float(x[0])) ```
39,852,963
I have the following list of tuples already sorted, with "sorted" in python: ``` L = [("1","blaabal"), ("1.2","bbalab"), ("10","ejej"), ("11.1","aaua"), ("12.1","ehjej"), ("12.2 (c)", "ekeke"), ("12.2 (d)", "qwerty"), ("2.1","baala"), ("3","yuio"), ("4","poku"), ("5....
2016/10/04
[ "https://Stackoverflow.com/questions/39852963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6726377/" ]
There's a package made specifically for your case called [`natsort`](https://pypi.python.org/pypi/natsort): ``` >>> from natsort import natsorted >>> L = [('1', 'blaabal'), ('4', 'poku'), ('12.2 (c)', 'ekeke'), ('12.1', 'ehjej')] >>> natsorted(L) [('1', 'blaabal'), ('4', 'poku'), ('12.1', 'ehjej'), ('12.2 (c)', 'ekeke...
The first value of your tuples are strings, and are being sorted in lexicographic order. If you want them to remain strings, sort with ``` sorted(l, key = lambda x: float(x[0])) ```
21,699,251
I got a function to call an exec in **node.js** server. I'm really lost about getting the stdout back. This is function: ``` function callPythonFile(args) { out = null var exec = require('child_process').exec, child; child = exec("../Prácticas/python/Taylor.py 'sin(w)' -10 10 0 10", function (er...
2014/02/11
[ "https://Stackoverflow.com/questions/21699251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742560/" ]
Because you return from the function before the exec is finished and the callback is executed. Exec in this case is asynchronous and unfortunately there is no synchronous exec in node.js in the last version (0.10.x). There are two ways to do what you are trying to do. Wait until the exec is done -------------------...
Have a look here about the `exec`: [nodejs doc](http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback). The callback function does not really return anything. So if you want to "return" the output, why don't you just read the stream and return the resulting string ([nodejs ...
3,289,330
I have 5 python cgi pages. I can navigate from one page to another. All pages get their data from the same database table just that they use different queries. The problem is that the application as a whole is slow. Though they connect to the same database, each page creates a new handle every time I visit it and hand...
2010/07/20
[ "https://Stackoverflow.com/questions/3289330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343409/" ]
cgi requires a new interpreter to start up for each request, and then all the resources such as db connections to be acquired and released. [fastcgi](http://en.wikipedia.org/wiki/FastCGI) or [wsgi](http://en.wikipedia.org/wiki/Wsgi) improve performance by allowing you to keep running the same process between requests
Django and Pylons are both frameworks that solve this problem quite nicely, namely by abstracting the DB-frontend integration. They are worth considering.
24,863,576
I have a python script that have \_\_main\_\_ statement and took all values parametric. I want to import and use it in my own script. Actually I can import but don't know how to use it. As you see below, \_\_main\_\_ is a bit complicated and rewriting it will take time because I even don't know what does most of code...
2014/07/21
[ "https://Stackoverflow.com/questions/24863576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2681662/" ]
No, there is no clean way to do so. When the module is being imported, it's code is executed and all global variables are set as attributes to the module object. So if part of the code is not executed at all (is guarded by `__main__` condition) there is no clean way to get access to that code. You can however run code ...
by what your saying you want to call a function in the script that is importing the module so try: ``` import __main__ __main__.myfunc() ```
24,863,576
I have a python script that have \_\_main\_\_ statement and took all values parametric. I want to import and use it in my own script. Actually I can import but don't know how to use it. As you see below, \_\_main\_\_ is a bit complicated and rewriting it will take time because I even don't know what does most of code...
2014/07/21
[ "https://Stackoverflow.com/questions/24863576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2681662/" ]
No, there is no clean way to do so. When the module is being imported, it's code is executed and all global variables are set as attributes to the module object. So if part of the code is not executed at all (is guarded by `__main__` condition) there is no clean way to get access to that code. You can however run code ...
Use the ***runpy*** module in the [Python 3 Standard Library](https://docs.python.org/3/library/runpy.html) See that data can be passed to and from the called script ```py # top.py import runpy import sys sys.argv += ["another parameter"] module_globals_dict = runpy.run_path("other_script.py", init_globals = glo...
24,863,576
I have a python script that have \_\_main\_\_ statement and took all values parametric. I want to import and use it in my own script. Actually I can import but don't know how to use it. As you see below, \_\_main\_\_ is a bit complicated and rewriting it will take time because I even don't know what does most of code...
2014/07/21
[ "https://Stackoverflow.com/questions/24863576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2681662/" ]
Use the ***runpy*** module in the [Python 3 Standard Library](https://docs.python.org/3/library/runpy.html) See that data can be passed to and from the called script ```py # top.py import runpy import sys sys.argv += ["another parameter"] module_globals_dict = runpy.run_path("other_script.py", init_globals = glo...
by what your saying you want to call a function in the script that is importing the module so try: ``` import __main__ __main__.myfunc() ```
43,754,065
I want to get the shade value of each circles from an image. 1. I try to detect circles using `HoughCircle`. 2. I get the center of each circle. 3. I put the text (the circle numbers) in a circle. 4. I set the pixel subset to obtain the shading values and calculate the averaged shading values. 5. I want to get the re...
2017/05/03
[ "https://Stackoverflow.com/questions/43754065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7955795/" ]
I can't answer completely, because it depends entirely on what's in `$HashVariable`. The easiest way to tell what's in there is: ``` use Data::Dumper; print Dumper $HashVariable; ``` Assuming this is a hash *reference* - which it would be, if `print $HashVariable` gives `HASH(0xdeadbeef)` as an output. So this *...
There's an obvious problem here, but it wouldn't cause the behaviour that you are seeing. You think that you have a hash reference in `$HashVariable` and that sounds correct given the `HASH(0xd1007d0)` output that you see when you print it. But setting up a hash reference and running your code, gives slightly strange...
37,096,806
I have landed into quite a unique problem. I created the model **1.**'message', used it for a while, then i changed it to **2.** 'messages' and after that again changed it back to **3.** 'message' but this time with many changes in the model fields. As i got to know afterwards, django migrations gets into some problem...
2016/05/08
[ "https://Stackoverflow.com/questions/37096806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4510252/" ]
Normally, You should not edit them manually. Once you start editing them, you will land into cyclic dependencies problems and if you do not remember what changes you made, your entire migrations will be messed up. What you can do is revert back migrations if you do not have any data to lose. If you are deleting migra...
No, I don't think so, you are better off deleting the migration files after the last successful migrations and running it again.
37,096,806
I have landed into quite a unique problem. I created the model **1.**'message', used it for a while, then i changed it to **2.** 'messages' and after that again changed it back to **3.** 'message' but this time with many changes in the model fields. As i got to know afterwards, django migrations gets into some problem...
2016/05/08
[ "https://Stackoverflow.com/questions/37096806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4510252/" ]
Normally, You should not edit them manually. Once you start editing them, you will land into cyclic dependencies problems and if you do not remember what changes you made, your entire migrations will be messed up. What you can do is revert back migrations if you do not have any data to lose. If you are deleting migra...
Having gone through the migration management process in different companies, I think it's fine to edit migrations if you know what you are doing. Actually, in many cases you will have to edit existing migrations file or even create new file just to implement a particular change. Few points to be taken care here: 1. Un...
57,060,964
I am using `sklearn` modules to find the best fitting models and model parameters. However, I have an unexpected Index error down below: ``` > IndexError Traceback (most recent call > last) <ipython-input-38-ea3f99e30226> in <module> > 22 s = mean_squared_error(y[ts], be...
2019/07/16
[ "https://Stackoverflow.com/questions/57060964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7302169/" ]
The root cause of your issue is that, while you ask for the evaluation of 6 models in `GridSearchCV`, you provide parameters only for the first 2 ones: ``` models = [SVR(), RandomForestRegressor(), LinearRegression(), Ridge(), Lasso(), XGBRegressor()] params = [{'C': [0.01, 1]}, {'n_estimators': [10, 20]}] ``` The r...
When you define ``` cv = [[] for _ in range(len(models))] ``` it has an empty list for each model. In the loop, however, you go over `enumerate(zip(models, params))` which has only **two** elements, since your `params` list has two elements (because `list(zip(x,y))` [has length](https://docs.python.org/3.3/library...
31,387,660
How I can use the Kivy framework in Qpython3 (Python 3.2 for android) app? I know that Qpython (Python 2.7 for android) app support this framework. pip\_console don't install kivy. I have an error, when I try to install it. Please help me.
2015/07/13
[ "https://Stackoverflow.com/questions/31387660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5111676/" ]
``` Session["email"] = email; ``` This will store the value between response and postback. Let me know if this is what you were looking for.
**TempData** can work for you. Another option is to store it in hidden field and receive it back on POST but you should be aware that "bad users" can modify that (via browser developer tools for example).
31,387,660
How I can use the Kivy framework in Qpython3 (Python 3.2 for android) app? I know that Qpython (Python 2.7 for android) app support this framework. pip\_console don't install kivy. I have an error, when I try to install it. Please help me.
2015/07/13
[ "https://Stackoverflow.com/questions/31387660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5111676/" ]
``` Session["email"] = email; ``` This will store the value between response and postback. Let me know if this is what you were looking for.
**If you need values that were rendered with the view to arrive in the POST** You should add that value to the Model (`Profile` in your case). **If you need values that were saved with POST to load in the next view** If you are using the same action (`return View()`), just preload the model. ``` DoStuff(); return V...
7,391,689
Here is what I can read in the python subprocess module documentation: ``` Replacing shell pipeline output=`dmesg | grep hda` ==> p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output ...
2011/09/12
[ "https://Stackoverflow.com/questions/7391689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
From [Wikipedia](http://en.wikipedia.org/wiki/SIGPIPE), **SIGPIPE** is the signal sent to a process when it attempts to write to a pipe without a process connected to the other end. When you first create `p1` using `stdout=PIPE`, there is one process connected to the pipe, which is your Python process, and you can rea...
OK I see. p1.stdout is closed from my python script but remains open in p2, and then p1 and p2 communicate together. Except if p2 is already closed, then p1 receives a SIGPIPE. Am I correct?
46,517,814
sudo python yantest.py 255,255,0 ``` who = sys.argv[1] print sys.argv[1] print who print 'Number of arguments:', len(sys.argv), 'arguments.' print 'Argument List:', str(sys.argv) yanon(strip, Color(who)) ``` output from above is ``` 255,255,0 255,255,0 Number of arguments: 2 arguments. Argument List: ['yantes...
2017/10/01
[ "https://Stackoverflow.com/questions/46517814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7509061/" ]
The problem with your implementation is that it does not distinguish original numbers from the squares that you have previously added. First, since you are doing this recursively, you don't need a `for` loop. Each invocation needs to take care of the initial value of the list alone. Next, `add(n)` adds the number at ...
There are two ways to safely add (or remove) elements to a list while iterating it: 1. Iterate backwards over the list, so that the indexes of the upcoming elements don't shift. 2. Use an [`Iterator`](https://docs.oracle.com/javase/9/docs/api/java/util/Iterator.html) or [`ListIterator`](https://docs.oracle.com/javase/...
45,765,946
I'm using some objects in python with dynamic properties, all with numbers and strings. Also I created a simple method to make a copy of an object. One of the property is a list, but I don't need it to be deep copied. This method seems to work fine, but I found an odd problem. This piece of code shows it: ``` #!/usr/b...
2017/08/18
[ "https://Stackoverflow.com/questions/45765946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1502508/" ]
Your `copy()` method copied the `copy` method (*not* the function from the class) from `test1`, which means that `self` in `test2.copy()` is still `test1`.
If you take a look at `dir(test1)`, you'll see that one of the elements is `'copy'`. In other words, you're not just copying the `type` attribute. **You're copying the `copy` method.** `test2` gets `test2.copy` set to `test1.copy`, a bound method that will copy `test1`. Don't use `dir` for this. Look at the instance...
4,834,538
``` import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = "trade.settings" from trade.turkey.models import * d = DemoRecs.objects.all() d.delete() ``` When I run this, it imports fine if I leave out the `d.delete()` line. It's erroring on that line. Why? If I comment that out, everything is cool. I can insert...
2011/01/29
[ "https://Stackoverflow.com/questions/4834538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179736/" ]
The directory for the `trade` project is missing from `sys.path`.
Try adding "trade" to the pythonpath... ``` import os.path _pypath = os.path.realpath(os.path.dirname(__file__) + '/trade') sys.path.append(_pypath) ```
50,809,052
So in python, if I want to make an if statement I need to do something like this (where a,b,c are conditions): ``` if(a) x=1 elsif(b) x=1 elseif(c) x=1 ``` is there a way to simply do something like: ``` if(a or b or c) x=1 ``` this would save a huge amount of time, but it doesn't evaluate.
2018/06/12
[ "https://Stackoverflow.com/questions/50809052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9928114/" ]
Turns out, whatever the issue was internally, it was actually triggered by this library in my `build.gradle` file: ``` implementation "com.github.bigfishcat.android:svg-android:2.0.8" ``` How a library cause this, I do not know. Everything builds fine now though.
apply plugin: 'com.android.application' **apply plugin: 'kotlin-android'** **apply plugin: 'kotlin-android-extensions'** android { ``` compileSdkVersion 26 defaultConfig { applicationId "com.example.admin.myapplication" minSdkVersion 15 targetSdkVersion 26 versionCode 1 versionName "1.0" te...
12,173,856
I'm trying to reimplement python [slice notation](https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is, given a list and a triple `(start, stop, step)` or a part th...
2012/08/29
[ "https://Stackoverflow.com/questions/12173856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989121/" ]
I've written a PHP port based on the C code, optimized for step sizes -1 and 1: ``` function get_indices($length, $step, &$start, &$end, &$size) { if (is_null($start)) { $start = $step < 0 ? $length - 1 : 0; } else { if ($start < 0) { $start += $l...
I can't say there's no bug in the codes, but it had past your test program :) ``` def mySlice(L, start=None, stop=None, step=None): ret = [] le = len(L) if step is None: step = 1 if step > 0: #this situation might be easier if start is None: start = 0 else: if ...
12,173,856
I'm trying to reimplement python [slice notation](https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is, given a list and a triple `(start, stop, step)` or a part th...
2012/08/29
[ "https://Stackoverflow.com/questions/12173856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989121/" ]
Here's a straight port of the C code: ``` def adjust_endpoint(length, endpoint, step): if endpoint < 0: endpoint += length if endpoint < 0: endpoint = -1 if step < 0 else 0 elif endpoint >= length: endpoint = length - 1 if step < 0 else length return endpoint def...
This is what I came up with (python) ``` def mySlice(L, start=None, stop=None, step=None): answer = [] if not start: start = 0 if start < 0: start += len(L) if not stop: stop = len(L) if stop < 0: stop += len(L) if not step: step = 1 if stop == sta...
12,173,856
I'm trying to reimplement python [slice notation](https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is, given a list and a triple `(start, stop, step)` or a part th...
2012/08/29
[ "https://Stackoverflow.com/questions/12173856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989121/" ]
This is based on @ecatmur's Python code ported again to PHP. ``` <?php function adjust_endpoint($length, $endpoint, $step) { if ($endpoint < 0) { $endpoint += $length; if ($endpoint < 0) { $endpoint = $step < 0 ? -1 : 0; } } elseif ($endpoint >= $length) { $endpo...
I can't say there's no bug in the codes, but it had past your test program :) ``` def mySlice(L, start=None, stop=None, step=None): ret = [] le = len(L) if step is None: step = 1 if step > 0: #this situation might be easier if start is None: start = 0 else: if ...
12,173,856
I'm trying to reimplement python [slice notation](https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is, given a list and a triple `(start, stop, step)` or a part th...
2012/08/29
[ "https://Stackoverflow.com/questions/12173856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989121/" ]
This is what I came up with (python) ``` def mySlice(L, start=None, stop=None, step=None): answer = [] if not start: start = 0 if start < 0: start += len(L) if not stop: stop = len(L) if stop < 0: stop += len(L) if not step: step = 1 if stop == sta...
I've written a PHP port based on the C code, optimized for step sizes -1 and 1: ``` function get_indices($length, $step, &$start, &$end, &$size) { if (is_null($start)) { $start = $step < 0 ? $length - 1 : 0; } else { if ($start < 0) { $start += $l...
12,173,856
I'm trying to reimplement python [slice notation](https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is, given a list and a triple `(start, stop, step)` or a part th...
2012/08/29
[ "https://Stackoverflow.com/questions/12173856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989121/" ]
Here's a straight port of the C code: ``` def adjust_endpoint(length, endpoint, step): if endpoint < 0: endpoint += length if endpoint < 0: endpoint = -1 if step < 0 else 0 elif endpoint >= length: endpoint = length - 1 if step < 0 else length return endpoint def...
This is based on @ecatmur's Python code ported again to PHP. ``` <?php function adjust_endpoint($length, $endpoint, $step) { if ($endpoint < 0) { $endpoint += $length; if ($endpoint < 0) { $endpoint = $step < 0 ? -1 : 0; } } elseif ($endpoint >= $length) { $endpo...
12,173,856
I'm trying to reimplement python [slice notation](https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is, given a list and a triple `(start, stop, step)` or a part th...
2012/08/29
[ "https://Stackoverflow.com/questions/12173856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989121/" ]
This is a solution I came up with in C# .NET, maybe not the prettiest, but it works. ``` private object[] Slice(object[] list, int start = 0, int stop = 0, int step = 0) { List<object> result = new List<object>(); if (step == 0) step = 1; if (start < 0) { for (int i = list.Length + start; i < ...
I can't say there's no bug in the codes, but it had past your test program :) ``` def mySlice(L, start=None, stop=None, step=None): ret = [] le = len(L) if step is None: step = 1 if step > 0: #this situation might be easier if start is None: start = 0 else: if ...
12,173,856
I'm trying to reimplement python [slice notation](https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is, given a list and a triple `(start, stop, step)` or a part th...
2012/08/29
[ "https://Stackoverflow.com/questions/12173856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989121/" ]
This is what I came up with (python) ``` def mySlice(L, start=None, stop=None, step=None): answer = [] if not start: start = 0 if start < 0: start += len(L) if not stop: stop = len(L) if stop < 0: stop += len(L) if not step: step = 1 if stop == sta...
I can't say there's no bug in the codes, but it had past your test program :) ``` def mySlice(L, start=None, stop=None, step=None): ret = [] le = len(L) if step is None: step = 1 if step > 0: #this situation might be easier if start is None: start = 0 else: if ...
12,173,856
I'm trying to reimplement python [slice notation](https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is, given a list and a triple `(start, stop, step)` or a part th...
2012/08/29
[ "https://Stackoverflow.com/questions/12173856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989121/" ]
This is what I came up with (python) ``` def mySlice(L, start=None, stop=None, step=None): answer = [] if not start: start = 0 if start < 0: start += len(L) if not stop: stop = len(L) if stop < 0: stop += len(L) if not step: step = 1 if stop == sta...
This is based on @ecatmur's Python code ported again to PHP. ``` <?php function adjust_endpoint($length, $endpoint, $step) { if ($endpoint < 0) { $endpoint += $length; if ($endpoint < 0) { $endpoint = $step < 0 ? -1 : 0; } } elseif ($endpoint >= $length) { $endpo...
12,173,856
I'm trying to reimplement python [slice notation](https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is, given a list and a triple `(start, stop, step)` or a part th...
2012/08/29
[ "https://Stackoverflow.com/questions/12173856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989121/" ]
Here's a straight port of the C code: ``` def adjust_endpoint(length, endpoint, step): if endpoint < 0: endpoint += length if endpoint < 0: endpoint = -1 if step < 0 else 0 elif endpoint >= length: endpoint = length - 1 if step < 0 else length return endpoint def...
I can't say there's no bug in the codes, but it had past your test program :) ``` def mySlice(L, start=None, stop=None, step=None): ret = [] le = len(L) if step is None: step = 1 if step > 0: #this situation might be easier if start is None: start = 0 else: if ...
12,173,856
I'm trying to reimplement python [slice notation](https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is, given a list and a triple `(start, stop, step)` or a part th...
2012/08/29
[ "https://Stackoverflow.com/questions/12173856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989121/" ]
Here's a straight port of the C code: ``` def adjust_endpoint(length, endpoint, step): if endpoint < 0: endpoint += length if endpoint < 0: endpoint = -1 if step < 0 else 0 elif endpoint >= length: endpoint = length - 1 if step < 0 else length return endpoint def...
This is a solution I came up with in C# .NET, maybe not the prettiest, but it works. ``` private object[] Slice(object[] list, int start = 0, int stop = 0, int step = 0) { List<object> result = new List<object>(); if (step == 0) step = 1; if (start < 0) { for (int i = list.Length + start; i < ...
1,376,016
I was playing around with Python's subprocess module, trying a few examples but I can't seem to get heredoc statements to work. Here is the trivial example I was playing with: ``` import subprocess a = "A String of Text" p = subprocess.Popen(["cat", "<<DATA\n" + a + "\nDATA"]) ``` I get the following error when I r...
2009/09/03
[ "https://Stackoverflow.com/questions/1376016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/124861/" ]
The shell "heredoc" support is a shell feature. `subprocess.Popen` does not run your command through the shell by default, so this syntax certainly won't work. However, since you're using pipes anyway, there isn't any need to use the heredoc support of the shell. Just write your string `a` to the stdin pipe of the pro...
You're passing shell syntax as an arguments to `cat` program. You can try to do it like that: ``` p = subprocess.Popen(["sh", "-c", "cat <<DATA\n" + a + "\nDATA"]) ``` But the concept itself is wrong. You should use Python features instead of calling shell scripts inside your python scripts. And in this particular ...
1,376,016
I was playing around with Python's subprocess module, trying a few examples but I can't seem to get heredoc statements to work. Here is the trivial example I was playing with: ``` import subprocess a = "A String of Text" p = subprocess.Popen(["cat", "<<DATA\n" + a + "\nDATA"]) ``` I get the following error when I r...
2009/09/03
[ "https://Stackoverflow.com/questions/1376016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/124861/" ]
The shell "heredoc" support is a shell feature. `subprocess.Popen` does not run your command through the shell by default, so this syntax certainly won't work. However, since you're using pipes anyway, there isn't any need to use the heredoc support of the shell. Just write your string `a` to the stdin pipe of the pro...
As others have pointed out, you need to run it in a shell. Popen makes this easy with a shell=True argument. I get the following output: ``` >>> import subprocess >>> a = "A String of Text" >>> p = subprocess.Popen("cat <<DATA\n" + a + "\nDATA", shell=True) >>> A String of Text >>> p.wait() 0 ```
1,376,016
I was playing around with Python's subprocess module, trying a few examples but I can't seem to get heredoc statements to work. Here is the trivial example I was playing with: ``` import subprocess a = "A String of Text" p = subprocess.Popen(["cat", "<<DATA\n" + a + "\nDATA"]) ``` I get the following error when I r...
2009/09/03
[ "https://Stackoverflow.com/questions/1376016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/124861/" ]
The shell "heredoc" support is a shell feature. `subprocess.Popen` does not run your command through the shell by default, so this syntax certainly won't work. However, since you're using pipes anyway, there isn't any need to use the heredoc support of the shell. Just write your string `a` to the stdin pipe of the pro...
As of Python 3.5 you can use [subrocess.run](https://docs.python.org/3.5/library/subprocess.html#subprocess.run) as in: ``` subprocess.run(['cat'], input=b"A String of Text") ```
1,376,016
I was playing around with Python's subprocess module, trying a few examples but I can't seem to get heredoc statements to work. Here is the trivial example I was playing with: ``` import subprocess a = "A String of Text" p = subprocess.Popen(["cat", "<<DATA\n" + a + "\nDATA"]) ``` I get the following error when I r...
2009/09/03
[ "https://Stackoverflow.com/questions/1376016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/124861/" ]
You're passing shell syntax as an arguments to `cat` program. You can try to do it like that: ``` p = subprocess.Popen(["sh", "-c", "cat <<DATA\n" + a + "\nDATA"]) ``` But the concept itself is wrong. You should use Python features instead of calling shell scripts inside your python scripts. And in this particular ...
As of Python 3.5 you can use [subrocess.run](https://docs.python.org/3.5/library/subprocess.html#subprocess.run) as in: ``` subprocess.run(['cat'], input=b"A String of Text") ```
1,376,016
I was playing around with Python's subprocess module, trying a few examples but I can't seem to get heredoc statements to work. Here is the trivial example I was playing with: ``` import subprocess a = "A String of Text" p = subprocess.Popen(["cat", "<<DATA\n" + a + "\nDATA"]) ``` I get the following error when I r...
2009/09/03
[ "https://Stackoverflow.com/questions/1376016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/124861/" ]
As others have pointed out, you need to run it in a shell. Popen makes this easy with a shell=True argument. I get the following output: ``` >>> import subprocess >>> a = "A String of Text" >>> p = subprocess.Popen("cat <<DATA\n" + a + "\nDATA", shell=True) >>> A String of Text >>> p.wait() 0 ```
As of Python 3.5 you can use [subrocess.run](https://docs.python.org/3.5/library/subprocess.html#subprocess.run) as in: ``` subprocess.run(['cat'], input=b"A String of Text") ```
30,438,227
I am building an application in python that uses a wrap to a library that performs hardware communication I would like to create some test units and I am pretty new to unit tests, so I would like to mock the communications but I really don't know how to do it quick example: this is the application code using the co...
2015/05/25
[ "https://Stackoverflow.com/questions/30438227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180699/" ]
You can use [`mock`](https://docs.python.org/3/library/unittest.mock.html#module-unittest.mock) framework to this kind of jobs. First of all you use `comm = Comm()` in `MyClass` and that means you have something like `from comm_module import Comm` in `MyClass`'s module. In these cases you need to patch `Comm` referenc...
The trick is not to use global objects like `comm`. If you can, make it so that `comm` gets injected to your class or method by the caller. Then what you do is pass a mocked `comm` when testing and then real one when in production. So either you make a `comm` reference a field in your class (and inject it via a const...
247,301
Besides the syntactic sugar and expressiveness power what are the differences in runtime efficiency. I mean, plpgsql can be faster than, lets say plpythonu or pljava? Or are they all approximately equals? We are using stored procedures for the task of detecting nearly-duplicates records of people in a moderately sized...
2008/10/29
[ "https://Stackoverflow.com/questions/247301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18300/" ]
plpgsql provides greater type safety I believe, you have to perform explicit casts if you want to perform operations using two different columns of similar type, like varchar and text or int4 and int8. This is important because if you need to have your stored proc use indexes, postgres requires that the types match exa...
Without doing actual testing, I would expect plpgsql to be somewhat more efficient than other languages, because it's small. Having said that, remember that SQL functions are likely to be even faster than plpgsql, if a function is simple enough that you can write it in just SQL.
247,301
Besides the syntactic sugar and expressiveness power what are the differences in runtime efficiency. I mean, plpgsql can be faster than, lets say plpythonu or pljava? Or are they all approximately equals? We are using stored procedures for the task of detecting nearly-duplicates records of people in a moderately sized...
2008/10/29
[ "https://Stackoverflow.com/questions/247301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18300/" ]
plpgsql provides greater type safety I believe, you have to perform explicit casts if you want to perform operations using two different columns of similar type, like varchar and text or int4 and int8. This is important because if you need to have your stored proc use indexes, postgres requires that the types match exa...
plpgsql is very well integrated with SQL - the source code should be very clean and readable. For SQL languages like PLJava or PLPython, SQL statements have to be isolated - SQL isn't part of language. So you have to write little bit more code. If your procedure has lot of SQL statements, then plpgsql procedure should ...
247,301
Besides the syntactic sugar and expressiveness power what are the differences in runtime efficiency. I mean, plpgsql can be faster than, lets say plpythonu or pljava? Or are they all approximately equals? We are using stored procedures for the task of detecting nearly-duplicates records of people in a moderately sized...
2008/10/29
[ "https://Stackoverflow.com/questions/247301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18300/" ]
plpgsql is very well integrated with SQL - the source code should be very clean and readable. For SQL languages like PLJava or PLPython, SQL statements have to be isolated - SQL isn't part of language. So you have to write little bit more code. If your procedure has lot of SQL statements, then plpgsql procedure should ...
Without doing actual testing, I would expect plpgsql to be somewhat more efficient than other languages, because it's small. Having said that, remember that SQL functions are likely to be even faster than plpgsql, if a function is simple enough that you can write it in just SQL.
14,053,552
I am writing a webapp and I would like to start charging my users. What are the recommended billing platforms for a python/Django webapp? I would like something that keeps track of my users' purchase history, can elegantly handle subscription purchases, a la carte items, coupon codes, and refunds, makes it straightfo...
2012/12/27
[ "https://Stackoverflow.com/questions/14053552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234270/" ]
The **[koalixcrm](https://github.com/scaphilo/koalixcrm)** is perhaps something you could start with. It offers some of your required functionality. Still it is in a prealpha stage but it already provides PDF export for Invoices and Quotes, there is already one included plugin for subscriptions. also try the **[demo]...
It's not really clear why Django Community hasn't come up a with complete billing system or at least a generic one to start working on. There's many packages that can be used for getting an idea how to implement such platform: <https://www.djangopackages.com/grids/g/payment-processing/>
67,996,181
So in python to call a parent classes function in a child class we use the `super()` method but why do we use the `super()` when we can just call the Parent class function suppose i have a `Class Employee:` and i have another class which inherites from the Employee class `class Programmer(Employee):` to call any functi...
2021/06/16
[ "https://Stackoverflow.com/questions/67996181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15895348/" ]
With `super()` you don't need to define `takeBreath()` in each class inherited from the `Person()` class.
`super()` is a far more general method. Suppose you decide to change your superclass. Maybe you name it `Tom` instead of `Employee`. Now you have to go about and change every mention of your `Employee` call. You can think of `super()` as a "proxy" to get the superclass regardless of what it is. It enables you to write...
67,996,181
So in python to call a parent classes function in a child class we use the `super()` method but why do we use the `super()` when we can just call the Parent class function suppose i have a `Class Employee:` and i have another class which inherites from the Employee class `class Programmer(Employee):` to call any functi...
2021/06/16
[ "https://Stackoverflow.com/questions/67996181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15895348/" ]
You already got a few answers as to why your code doesn't work (you're creating a new `Employee` rather than calling `Employee`'s method with your own `self`) and why delegation via `super` is convenient (don't have to update all the code if you update the parent class). An other reason is that Python supports *multip...
`super()` is a far more general method. Suppose you decide to change your superclass. Maybe you name it `Tom` instead of `Employee`. Now you have to go about and change every mention of your `Employee` call. You can think of `super()` as a "proxy" to get the superclass regardless of what it is. It enables you to write...
59,475,157
I'm a beginner in python. I'm not able to understand what the problem is? ``` the runtime process for the instance running on port 43421 has unexpectedly quit ERROR 2019-12-24 17:29:10,258 base.py:209] Internal Server Error: /input/ Traceback (most recent call last): File "/var/www/html/sym_math/google_appengine...
2019/12/25
[ "https://Stackoverflow.com/questions/59475157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12277769/" ]
Since the column in the first table is an identity field, you should use [`scope_idenity()`](https://learn.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql?view=sql-server-ver15) immediately after the first INSERT statement to get the result. Then use that result in the subsequent INSERT statements. ...
You can use MAX: ``` DECLARE @id int = (select max(BusinessEntityId) From Person.BusinessEntity) ```
59,475,157
I'm a beginner in python. I'm not able to understand what the problem is? ``` the runtime process for the instance running on port 43421 has unexpectedly quit ERROR 2019-12-24 17:29:10,258 base.py:209] Internal Server Error: /input/ Traceback (most recent call last): File "/var/www/html/sym_math/google_appengine...
2019/12/25
[ "https://Stackoverflow.com/questions/59475157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12277769/" ]
I encourage you to use the [`OUTPUT`](https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-ver15) clause. This just works, regardless of triggers on tables, other transactions, sessions, and so on. ``` CREATE PROCEDURE spCustomerDetails ( @FirstName NVARCHAR(30), @Last...
You can use MAX: ``` DECLARE @id int = (select max(BusinessEntityId) From Person.BusinessEntity) ```
59,475,157
I'm a beginner in python. I'm not able to understand what the problem is? ``` the runtime process for the instance running on port 43421 has unexpectedly quit ERROR 2019-12-24 17:29:10,258 base.py:209] Internal Server Error: /input/ Traceback (most recent call last): File "/var/www/html/sym_math/google_appengine...
2019/12/25
[ "https://Stackoverflow.com/questions/59475157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12277769/" ]
Since the column in the first table is an identity field, you should use [`scope_idenity()`](https://learn.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql?view=sql-server-ver15) immediately after the first INSERT statement to get the result. Then use that result in the subsequent INSERT statements. ...
I encourage you to use the [`OUTPUT`](https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-ver15) clause. This just works, regardless of triggers on tables, other transactions, sessions, and so on. ``` CREATE PROCEDURE spCustomerDetails ( @FirstName NVARCHAR(30), @Last...
23,382,499
I'm running a python script that makes modifications in a specific database. I want to run a second script once there is a modification in my database (local server). Is there anyway to do that? Any help would be very appreciated. Thanks!
2014/04/30
[ "https://Stackoverflow.com/questions/23382499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2343621/" ]
Thanks for your answers, i found a solution here: <http://crazytechthoughts.blogspot.fr/2011/12/call-external-program-from-mysql.html> A Trigger must be defined to call an external function once the DB Table is modified: ``` DELIMITER $ CREATE TRIGGER Test_Trigger AFTER INSERT ON SFCRoutingTable FOR EACH ROW BEGIN D...
You can use 'Stored Procedures' in your database a lot of RDBMS engines support one or multiple programming languages to do so. AFAIK postgresql support signals to call external process to. Google something like 'Stored Procedures in Python for PostgreSQL' or 'postgresql trigger call external program'
23,382,499
I'm running a python script that makes modifications in a specific database. I want to run a second script once there is a modification in my database (local server). Is there anyway to do that? Any help would be very appreciated. Thanks!
2014/04/30
[ "https://Stackoverflow.com/questions/23382499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2343621/" ]
You can use 'Stored Procedures' in your database a lot of RDBMS engines support one or multiple programming languages to do so. AFAIK postgresql support signals to call external process to. Google something like 'Stored Procedures in Python for PostgreSQL' or 'postgresql trigger call external program'
And if what you need is to keep the python script running and listen to changes in a certain table. 1. You can create a listener table ex. 'trigger\_table' in your database with only one value. 2. Create a trigger that will change the value in the 'trigger\_table' table every time a change occurs in some table. 3. And...
23,382,499
I'm running a python script that makes modifications in a specific database. I want to run a second script once there is a modification in my database (local server). Is there anyway to do that? Any help would be very appreciated. Thanks!
2014/04/30
[ "https://Stackoverflow.com/questions/23382499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2343621/" ]
Thanks for your answers, i found a solution here: <http://crazytechthoughts.blogspot.fr/2011/12/call-external-program-from-mysql.html> A Trigger must be defined to call an external function once the DB Table is modified: ``` DELIMITER $ CREATE TRIGGER Test_Trigger AFTER INSERT ON SFCRoutingTable FOR EACH ROW BEGIN D...
And if what you need is to keep the python script running and listen to changes in a certain table. 1. You can create a listener table ex. 'trigger\_table' in your database with only one value. 2. Create a trigger that will change the value in the 'trigger\_table' table every time a change occurs in some table. 3. And...
37,355,375
There is a dict (say `d`). `dict.get(key, None)` returns `None` if `key` doesn't exist in `d`. **How do I get the first value (i.e., `d[key]` is not `None`) from a list of keys (some of them might not exist in `d`)?** This post, [Pythonic way to avoid “if x: return x” statements](https://stackoverflow.com/questions/...
2016/05/20
[ "https://Stackoverflow.com/questions/37355375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3067748/" ]
There's no convenient builtin, but you could implement it easily enough: ``` def getfirst(d, keys): for key in keys: if key in d: return d[key] return None ```
I would use `next` with a comprehension: ``` # build list of keys levels = [ 'level' + str(i) for i in range(3) ] for d in list_dicts: level_key = next(k for k in levels if d.get(k)) level = d[level_key] ```
37,355,375
There is a dict (say `d`). `dict.get(key, None)` returns `None` if `key` doesn't exist in `d`. **How do I get the first value (i.e., `d[key]` is not `None`) from a list of keys (some of them might not exist in `d`)?** This post, [Pythonic way to avoid “if x: return x” statements](https://stackoverflow.com/questions/...
2016/05/20
[ "https://Stackoverflow.com/questions/37355375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3067748/" ]
This line: ``` x, y = d.get('level0', None) or d.get('level1', None) or d.get('level2', None) ``` Is basically mapping a `list` of `['level0', 'level1', 'level2']` to `d.get` (`None` is already the default value; there's no need to explicitly state it in this case). Next, you want to choose the one that doesn't map ...
There's no convenient builtin, but you could implement it easily enough: ``` def getfirst(d, keys): for key in keys: if key in d: return d[key] return None ```
37,355,375
There is a dict (say `d`). `dict.get(key, None)` returns `None` if `key` doesn't exist in `d`. **How do I get the first value (i.e., `d[key]` is not `None`) from a list of keys (some of them might not exist in `d`)?** This post, [Pythonic way to avoid “if x: return x” statements](https://stackoverflow.com/questions/...
2016/05/20
[ "https://Stackoverflow.com/questions/37355375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3067748/" ]
There's no convenient builtin, but you could implement it easily enough: ``` def getfirst(d, keys): for key in keys: if key in d: return d[key] return None ```
Should work on all Pythons: ``` # a list of dicts list_dicts = [{'level0': (1, 2), 'col': '#ff310021'}, {'level1': (3, 4), 'col': '#ff310011'}, {'level2': (5, 6), 'col': '#ff312221'}] # Prioritized (ordered) list of keys [level0, level99] KEYS = ['level{}'.format(i) for i in range(100)] #...
37,355,375
There is a dict (say `d`). `dict.get(key, None)` returns `None` if `key` doesn't exist in `d`. **How do I get the first value (i.e., `d[key]` is not `None`) from a list of keys (some of them might not exist in `d`)?** This post, [Pythonic way to avoid “if x: return x” statements](https://stackoverflow.com/questions/...
2016/05/20
[ "https://Stackoverflow.com/questions/37355375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3067748/" ]
There's no convenient builtin, but you could implement it easily enough: ``` def getfirst(d, keys): for key in keys: if key in d: return d[key] return None ```
Just as a novelty item, here is a version that first computes a getter using functional composition. ``` if 'reduce' not in globals(): from functools import reduce list_dicts = [ {'level0' : (1, 2), 'col': '#ff310021'}, {'level1' : (3, 4), 'col': '#ff310011'}, {'level2' : (5, 6), ...
37,355,375
There is a dict (say `d`). `dict.get(key, None)` returns `None` if `key` doesn't exist in `d`. **How do I get the first value (i.e., `d[key]` is not `None`) from a list of keys (some of them might not exist in `d`)?** This post, [Pythonic way to avoid “if x: return x” statements](https://stackoverflow.com/questions/...
2016/05/20
[ "https://Stackoverflow.com/questions/37355375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3067748/" ]
This line: ``` x, y = d.get('level0', None) or d.get('level1', None) or d.get('level2', None) ``` Is basically mapping a `list` of `['level0', 'level1', 'level2']` to `d.get` (`None` is already the default value; there's no need to explicitly state it in this case). Next, you want to choose the one that doesn't map ...
I would use `next` with a comprehension: ``` # build list of keys levels = [ 'level' + str(i) for i in range(3) ] for d in list_dicts: level_key = next(k for k in levels if d.get(k)) level = d[level_key] ```
37,355,375
There is a dict (say `d`). `dict.get(key, None)` returns `None` if `key` doesn't exist in `d`. **How do I get the first value (i.e., `d[key]` is not `None`) from a list of keys (some of them might not exist in `d`)?** This post, [Pythonic way to avoid “if x: return x” statements](https://stackoverflow.com/questions/...
2016/05/20
[ "https://Stackoverflow.com/questions/37355375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3067748/" ]
This line: ``` x, y = d.get('level0', None) or d.get('level1', None) or d.get('level2', None) ``` Is basically mapping a `list` of `['level0', 'level1', 'level2']` to `d.get` (`None` is already the default value; there's no need to explicitly state it in this case). Next, you want to choose the one that doesn't map ...
Should work on all Pythons: ``` # a list of dicts list_dicts = [{'level0': (1, 2), 'col': '#ff310021'}, {'level1': (3, 4), 'col': '#ff310011'}, {'level2': (5, 6), 'col': '#ff312221'}] # Prioritized (ordered) list of keys [level0, level99] KEYS = ['level{}'.format(i) for i in range(100)] #...
37,355,375
There is a dict (say `d`). `dict.get(key, None)` returns `None` if `key` doesn't exist in `d`. **How do I get the first value (i.e., `d[key]` is not `None`) from a list of keys (some of them might not exist in `d`)?** This post, [Pythonic way to avoid “if x: return x” statements](https://stackoverflow.com/questions/...
2016/05/20
[ "https://Stackoverflow.com/questions/37355375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3067748/" ]
This line: ``` x, y = d.get('level0', None) or d.get('level1', None) or d.get('level2', None) ``` Is basically mapping a `list` of `['level0', 'level1', 'level2']` to `d.get` (`None` is already the default value; there's no need to explicitly state it in this case). Next, you want to choose the one that doesn't map ...
Just as a novelty item, here is a version that first computes a getter using functional composition. ``` if 'reduce' not in globals(): from functools import reduce list_dicts = [ {'level0' : (1, 2), 'col': '#ff310021'}, {'level1' : (3, 4), 'col': '#ff310011'}, {'level2' : (5, 6), ...
828,139
I'm trying to get the values from a pointer to a float array, but it returns as c\_void\_p in python The C code ``` double v; const void *data; pa_stream_peek(s, &data, &length); v = ((const float*) data)[length / sizeof(float) -1]; ``` Python so far ``` import ctypes null_ptr = ctypes.c_void_p() pa_stream_pee...
2009/05/06
[ "https://Stackoverflow.com/questions/828139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/102018/" ]
My ctypes is rusty, but I believe you want POINTER(c\_float) instead of c\_void\_p. So try this: ``` null_ptr = POINTER(c_float)() pa_stream_peek(stream, null_ptr, ctypes.c_ulong(length)) null_ptr[0] null_ptr[5] # etc ```
You'll also probably want to be passing the null\_ptr using byref, e.g. ``` pa_stream_peek(stream, ctypes.byref(null_ptr), ctypes.c_ulong(length)) ```
828,139
I'm trying to get the values from a pointer to a float array, but it returns as c\_void\_p in python The C code ``` double v; const void *data; pa_stream_peek(s, &data, &length); v = ((const float*) data)[length / sizeof(float) -1]; ``` Python so far ``` import ctypes null_ptr = ctypes.c_void_p() pa_stream_pee...
2009/05/06
[ "https://Stackoverflow.com/questions/828139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/102018/" ]
My ctypes is rusty, but I believe you want POINTER(c\_float) instead of c\_void\_p. So try this: ``` null_ptr = POINTER(c_float)() pa_stream_peek(stream, null_ptr, ctypes.c_ulong(length)) null_ptr[0] null_ptr[5] # etc ```
To use ctypes in a way that mimics your C code, I would suggest (and I'm out-of-practice and this is untested): ``` vdata = ctypes.c_void_p() length = ctypes.c_ulong(0) pa_stream_peek(stream, ctypes.byref(vdata), ctypes.byref(length)) fdata = ctypes.cast(vdata, POINTER(float)) ```
828,139
I'm trying to get the values from a pointer to a float array, but it returns as c\_void\_p in python The C code ``` double v; const void *data; pa_stream_peek(s, &data, &length); v = ((const float*) data)[length / sizeof(float) -1]; ``` Python so far ``` import ctypes null_ptr = ctypes.c_void_p() pa_stream_pee...
2009/05/06
[ "https://Stackoverflow.com/questions/828139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/102018/" ]
My ctypes is rusty, but I believe you want POINTER(c\_float) instead of c\_void\_p. So try this: ``` null_ptr = POINTER(c_float)() pa_stream_peek(stream, null_ptr, ctypes.c_ulong(length)) null_ptr[0] null_ptr[5] # etc ```
When you pass pointer arguments without using ctypes.pointer or ctypes.byref, their contents simply get set to the integer value of the memory address (i.e., the pointer bits). These arguments should be passed with `byref` (or `pointer`, but `byref` has less overhead): ``` data = ctypes.pointer(ctypes.c_float()) nbyte...