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
71,637,890
I use python and pandas to analyze big data set. I have a several arrays with different length. I need to insert values to specific column. If some values ​​are not present for column it should be 'not defined'. Input data looks like row in dataframe with different positions. Expected output: ![Expected output](https:/...
2022/03/27
[ "https://Stackoverflow.com/questions/71637890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18598283/" ]
Me too was facing same issue. But using `window` worked for me, ``` const lineHeight= window .getComputedStyle(descriptionRef.current, null) .getPropertyValue("line-height"); ```
you need to set the `line-height` via `style` prop to get by script. But bear in mind, `15` and `15px` are different things for `line-height` attribute. If we remove the style attribute, even we specify the `line-height` in CSS class, we cannot get its value as `12px` and it will be empty as same as your case. ```c...
35,092,571
I am trying to create a dashboard where I can analyse my model's data (Article) using the library [plotly](https://plot.ly/python/). The Plotly bar chart is not showing on my template, I am wondering if I am doing something wrong since there's no error with the code below : **models.py** ``` from django.db import mo...
2016/01/29
[ "https://Stackoverflow.com/questions/35092571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4859971/" ]
The result of ``` py.plot(data, filename='basic-bar') ``` is to generate a offline HTML file and return a local URL of this file e.g. file:///your\_project\_pwd/temp-plot.html If you want to render it in Django framework, you need to * use `<iframe>` and restructure of your folder in Django settings OR * use pl...
The above answer was very useful, I am in fact watching for parent resize, I am working in angular and I used the below code to achieve the resize, I am having a similar problem and this line of code was useful ``` <div class="col-lg-12" ng-if="showME" style="padding:0px"> <div id="graphPlot" ng-bind-html="myHTML">...
1,718,251
I am using the macports version of python on a Snow Leopard computer, and using cmake to build a cross-platform extension to it. I search for the python interpreter and libraries on the system using the following commands in CMakeLists.txt ``` include(FindPythonInterp) include(FindPythonLibs ) ``` However, while cm...
2009/11/11
[ "https://Stackoverflow.com/questions/1718251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/134397/" ]
Adding the following in `~/.bash_profile` ``` export DYLD_FRAMEWORK_PATH=/opt/local/Library/Frameworks ``` fixes the problem at least temporarily. Apparently, this inconsistency between the python interpreter and the python framework used by cmake is a bug that should be hopefully fixed in the new version.
I am not intimately familiar with CMake, but with the Apple version of gcc/ld, you can pass the `-F` flag to specify a new framework search path. For example, `-F/opt/local/Library/Frameworks` will search in MacPorts' frameworks directory. If you can specify such a flag using CMake, it may solve your problem.
69,102,892
I have a class object which has the task of running a file. When I was developing, my class object was in the same file as the code I used to run the file. Now I am refactoring and making this a real package so I moved the code to a file called `class_objects.py`. I have installed this package locally, but now when I...
2021/09/08
[ "https://Stackoverflow.com/questions/69102892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2444023/" ]
Just use boolean logic: ``` WHERE (:IP_TYPE = 'HIGH' AND (TYPE = 'HIGH' OR TYPE = '' OR TYPE IS NULL) ) OR (:IP_TYPE = 'LOW' AND TYPE = 'LOW') ``` Or more succinctly: ``` WHERE :IP_TYPE = TYPE OR (:IP_TYPE = 'HIGH' AND (TYPE = '' OR TYPE IS NULL)) ```
In Oracle, an empty string `''` is the same as `NULL`; so your filter can simply be: ```sql SELECT * FROM PAYRECORDS WHERE :ip_type = type OR (:ip_type = 'HIGH' AND type IS NULL); ```
69,102,892
I have a class object which has the task of running a file. When I was developing, my class object was in the same file as the code I used to run the file. Now I am refactoring and making this a real package so I moved the code to a file called `class_objects.py`. I have installed this package locally, but now when I...
2021/09/08
[ "https://Stackoverflow.com/questions/69102892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2444023/" ]
Just use boolean logic: ``` WHERE (:IP_TYPE = 'HIGH' AND (TYPE = 'HIGH' OR TYPE = '' OR TYPE IS NULL) ) OR (:IP_TYPE = 'LOW' AND TYPE = 'LOW') ``` Or more succinctly: ``` WHERE :IP_TYPE = TYPE OR (:IP_TYPE = 'HIGH' AND (TYPE = '' OR TYPE IS NULL)) ```
You can also use the `NVL()` to consider that when column `type` isn't populated then it should be considered as `HIGH`: ``` SELECT * FROM PAYRECORDS WHERE NVL(type, 'HIGH') = :ip_type; ```
69,102,892
I have a class object which has the task of running a file. When I was developing, my class object was in the same file as the code I used to run the file. Now I am refactoring and making this a real package so I moved the code to a file called `class_objects.py`. I have installed this package locally, but now when I...
2021/09/08
[ "https://Stackoverflow.com/questions/69102892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2444023/" ]
In Oracle, an empty string `''` is the same as `NULL`; so your filter can simply be: ```sql SELECT * FROM PAYRECORDS WHERE :ip_type = type OR (:ip_type = 'HIGH' AND type IS NULL); ```
You can also use the `NVL()` to consider that when column `type` isn't populated then it should be considered as `HIGH`: ``` SELECT * FROM PAYRECORDS WHERE NVL(type, 'HIGH') = :ip_type; ```
21,529,118
I'm trying to use flask-migrate to version my database locally and then reflect the changes in production (Heroku). So far I managed to successfully version the local database and upgrade it, so now I wanted to reflect this on Heroku. To do this I pushed the latest code state to Heroku together with the newly created *...
2014/02/03
[ "https://Stackoverflow.com/questions/21529118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/703809/" ]
I was struggling with this for some time and even posted on the Heroku python forums, but no replies so far. To solve the issue I decided not to run the migration remotely on Heroku, but to run the migration on my development machine and pass the production database address instead. So I do this: 1. Sync the developme...
I haven't tried this with Heroku, but ran into the same error and symptoms. The issue for me was that when running locally, my current working directory was set to the project root directory, and when running remotely, it was set to the user's home directory. Try either cd'ing to the right starting directory first, or...
21,529,118
I'm trying to use flask-migrate to version my database locally and then reflect the changes in production (Heroku). So far I managed to successfully version the local database and upgrade it, so now I wanted to reflect this on Heroku. To do this I pushed the latest code state to Heroku together with the newly created *...
2014/02/03
[ "https://Stackoverflow.com/questions/21529118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/703809/" ]
I was struggling with this for some time and even posted on the Heroku python forums, but no replies so far. To solve the issue I decided not to run the migration remotely on Heroku, but to run the migration on my development machine and pass the production database address instead. So I do this: 1. Sync the developme...
Had the same issue as you. I then tried to commit `migrations/alembic.ini` and then things started to work. Just make sure there's no sensitive information inside that file before committing it. Hope this solves your issue too.
21,529,118
I'm trying to use flask-migrate to version my database locally and then reflect the changes in production (Heroku). So far I managed to successfully version the local database and upgrade it, so now I wanted to reflect this on Heroku. To do this I pushed the latest code state to Heroku together with the newly created *...
2014/02/03
[ "https://Stackoverflow.com/questions/21529118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/703809/" ]
I was struggling with this for some time and even posted on the Heroku python forums, but no replies so far. To solve the issue I decided not to run the migration remotely on Heroku, but to run the migration on my development machine and pass the production database address instead. So I do this: 1. Sync the developme...
To elaborate on lawicko's answer, when using Flask-Migrate and Heroku, a good way to conduct database migrations for a production database is to download the production database, generate the migration script locally, and run the migration script on Heroku. The alternative is to use a local development database to gene...
21,529,118
I'm trying to use flask-migrate to version my database locally and then reflect the changes in production (Heroku). So far I managed to successfully version the local database and upgrade it, so now I wanted to reflect this on Heroku. To do this I pushed the latest code state to Heroku together with the newly created *...
2014/02/03
[ "https://Stackoverflow.com/questions/21529118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/703809/" ]
I haven't tried this with Heroku, but ran into the same error and symptoms. The issue for me was that when running locally, my current working directory was set to the project root directory, and when running remotely, it was set to the user's home directory. Try either cd'ing to the right starting directory first, or...
Had the same issue as you. I then tried to commit `migrations/alembic.ini` and then things started to work. Just make sure there's no sensitive information inside that file before committing it. Hope this solves your issue too.
21,529,118
I'm trying to use flask-migrate to version my database locally and then reflect the changes in production (Heroku). So far I managed to successfully version the local database and upgrade it, so now I wanted to reflect this on Heroku. To do this I pushed the latest code state to Heroku together with the newly created *...
2014/02/03
[ "https://Stackoverflow.com/questions/21529118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/703809/" ]
To elaborate on lawicko's answer, when using Flask-Migrate and Heroku, a good way to conduct database migrations for a production database is to download the production database, generate the migration script locally, and run the migration script on Heroku. The alternative is to use a local development database to gene...
Had the same issue as you. I then tried to commit `migrations/alembic.ini` and then things started to work. Just make sure there's no sensitive information inside that file before committing it. Hope this solves your issue too.
10,524,842
I have a multithreaded mergesorting program in C, and a program for benchmark testing it with 0, 1, 2, or 4 threads. I also wrote a program in Python to do multiple tests and aggregate the results. The weird thing is that when I run the Python, the tests always run in about half the time compared to when I run them di...
2012/05/09
[ "https://Stackoverflow.com/questions/10524842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1325447/" ]
Turns out I was passing sys.maxint to the subprocess as the modulus for generating random numbers. C was truncating the 64-bit integer and interpreting it as signed, i.e., -1 in two's complement, so every random number was being mod'd by that and becoming 0. So, sorting all the same values seems to take about half as m...
wrapping this in a shell script will probably have the same effect. if so its the console operations
20,694,338
I am trying to play around with some more of function programming parts of python and for a test I thought I would print out the sum of the first n integers for all numbers between 1 and 100. ``` for i in map(lambda n: (n*(n+1))/2, range(1,101)): print "sum of the first %d integers: %d" % (i,i) ``` The last lin...
2013/12/20
[ "https://Stackoverflow.com/questions/20694338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1761521/" ]
You can return tuple with (index, value) from your lambda, like that: ``` for i,s in map(lambda n: (n,(n*(n+1))/2), range(1,101)): print "sum of the first %d integers: %d" % (i,s) ```
Your code doesn't define a variable that holds an index. In the outermost scope, there is just the variable (sometimes called a "name" when talking about Python) "i". If you'd like an index, you can use the built-in function enumerate() ``` for i,x in enumerate([5,10,15]): print i, x ```
20,694,338
I am trying to play around with some more of function programming parts of python and for a test I thought I would print out the sum of the first n integers for all numbers between 1 and 100. ``` for i in map(lambda n: (n*(n+1))/2, range(1,101)): print "sum of the first %d integers: %d" % (i,i) ``` The last lin...
2013/12/20
[ "https://Stackoverflow.com/questions/20694338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1761521/" ]
Your code doesn't define a variable that holds an index. In the outermost scope, there is just the variable (sometimes called a "name" when talking about Python) "i". If you'd like an index, you can use the built-in function enumerate() ``` for i,x in enumerate([5,10,15]): print i, x ```
Or you could try this: ``` for ind, val in enumerate(map(lambda n: (n*(n+1))/2, range(1,101)), 1): print "sum of the first %d integers: %d" % (ind, val) ```
20,694,338
I am trying to play around with some more of function programming parts of python and for a test I thought I would print out the sum of the first n integers for all numbers between 1 and 100. ``` for i in map(lambda n: (n*(n+1))/2, range(1,101)): print "sum of the first %d integers: %d" % (i,i) ``` The last lin...
2013/12/20
[ "https://Stackoverflow.com/questions/20694338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1761521/" ]
Your code doesn't define a variable that holds an index. In the outermost scope, there is just the variable (sometimes called a "name" when talking about Python) "i". If you'd like an index, you can use the built-in function enumerate() ``` for i,x in enumerate([5,10,15]): print i, x ```
Mayby I don't understand what you are going for but couldn't you just use print ``` print "sum of the first %d integers: %d" %(100,sum(xrange(1,101))) ``` if you wanted user input... ``` i = input("Enter the upper range to sum: ") print "sum of the first %d integers: %d" %(i,sum(xrange(1,i+1))) ``` I'm also using...
20,694,338
I am trying to play around with some more of function programming parts of python and for a test I thought I would print out the sum of the first n integers for all numbers between 1 and 100. ``` for i in map(lambda n: (n*(n+1))/2, range(1,101)): print "sum of the first %d integers: %d" % (i,i) ``` The last lin...
2013/12/20
[ "https://Stackoverflow.com/questions/20694338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1761521/" ]
You can return tuple with (index, value) from your lambda, like that: ``` for i,s in map(lambda n: (n,(n*(n+1))/2), range(1,101)): print "sum of the first %d integers: %d" % (i,s) ```
Or you could try this: ``` for ind, val in enumerate(map(lambda n: (n*(n+1))/2, range(1,101)), 1): print "sum of the first %d integers: %d" % (ind, val) ```
20,694,338
I am trying to play around with some more of function programming parts of python and for a test I thought I would print out the sum of the first n integers for all numbers between 1 and 100. ``` for i in map(lambda n: (n*(n+1))/2, range(1,101)): print "sum of the first %d integers: %d" % (i,i) ``` The last lin...
2013/12/20
[ "https://Stackoverflow.com/questions/20694338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1761521/" ]
You can return tuple with (index, value) from your lambda, like that: ``` for i,s in map(lambda n: (n,(n*(n+1))/2), range(1,101)): print "sum of the first %d integers: %d" % (i,s) ```
Mayby I don't understand what you are going for but couldn't you just use print ``` print "sum of the first %d integers: %d" %(100,sum(xrange(1,101))) ``` if you wanted user input... ``` i = input("Enter the upper range to sum: ") print "sum of the first %d integers: %d" %(i,sum(xrange(1,i+1))) ``` I'm also using...
20,694,338
I am trying to play around with some more of function programming parts of python and for a test I thought I would print out the sum of the first n integers for all numbers between 1 and 100. ``` for i in map(lambda n: (n*(n+1))/2, range(1,101)): print "sum of the first %d integers: %d" % (i,i) ``` The last lin...
2013/12/20
[ "https://Stackoverflow.com/questions/20694338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1761521/" ]
Or you could try this: ``` for ind, val in enumerate(map(lambda n: (n*(n+1))/2, range(1,101)), 1): print "sum of the first %d integers: %d" % (ind, val) ```
Mayby I don't understand what you are going for but couldn't you just use print ``` print "sum of the first %d integers: %d" %(100,sum(xrange(1,101))) ``` if you wanted user input... ``` i = input("Enter the upper range to sum: ") print "sum of the first %d integers: %d" %(i,sum(xrange(1,i+1))) ``` I'm also using...
62,670,991
I'm trying to read multiple CSV files from blob storage using python. The code that I'm using is: ``` blob_service_client = BlobServiceClient.from_connection_string(connection_str) container_client = blob_service_client.get_container_client(container) blobs_list = container_client.list_blobs(folder_root) for blob in ...
2020/07/01
[ "https://Stackoverflow.com/questions/62670991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6153466/" ]
You could download the file from blob storage, then read the data into a pandas DataFrame from the downloaded file. ``` from azure.storage.blob import BlockBlobService import pandas as pd import tables STORAGEACCOUNTNAME= <storage_account_name> STORAGEACCOUNTKEY= <storage_account_key> LOCALFILENAME= <local_file_name>...
``` import pandas as pd data = pd.read_csv('blob_sas_url') ``` The Blob SAS Url can be found by right clicking on the azure portal's blob file that you want to import and selecting Generate SAS. Then, click Generate SAS token and URL button and copy the SAS url to above code in place of blob\_sas\_url.
62,670,991
I'm trying to read multiple CSV files from blob storage using python. The code that I'm using is: ``` blob_service_client = BlobServiceClient.from_connection_string(connection_str) container_client = blob_service_client.get_container_client(container) blobs_list = container_client.list_blobs(folder_root) for blob in ...
2020/07/01
[ "https://Stackoverflow.com/questions/62670991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6153466/" ]
You could download the file from blob storage, then read the data into a pandas DataFrame from the downloaded file. ``` from azure.storage.blob import BlockBlobService import pandas as pd import tables STORAGEACCOUNTNAME= <storage_account_name> STORAGEACCOUNTKEY= <storage_account_key> LOCALFILENAME= <local_file_name>...
You can now directly read from BlobStorage into a Pandas DataFrame: ``` mydata = pd.read_csv( f"abfs://{blob_path}", storage_options={ "connection_string": os.environ["STORAGE_CONNECTION"] }) ``` where `blob_path` is the path to your file, given as `{container-name}/{blob-preifx.csv}`
62,670,991
I'm trying to read multiple CSV files from blob storage using python. The code that I'm using is: ``` blob_service_client = BlobServiceClient.from_connection_string(connection_str) container_client = blob_service_client.get_container_client(container) blobs_list = container_client.list_blobs(folder_root) for blob in ...
2020/07/01
[ "https://Stackoverflow.com/questions/62670991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6153466/" ]
You could download the file from blob storage, then read the data into a pandas DataFrame from the downloaded file. ``` from azure.storage.blob import BlockBlobService import pandas as pd import tables STORAGEACCOUNTNAME= <storage_account_name> STORAGEACCOUNTKEY= <storage_account_key> LOCALFILENAME= <local_file_name>...
The BlockBlobService as part of azure-storage is deprecated. Use below instead: ``` !pip install azure-storage-blob from azure.storage.blob import BlobServiceClient import pandas as pd STORAGEACCOUNTURL= <storage_account_url> STORAGEACCOUNTKEY= <storage_account_key> LOCALFILENAME= <local_file_name> CONTAINERNAME= <co...
62,670,991
I'm trying to read multiple CSV files from blob storage using python. The code that I'm using is: ``` blob_service_client = BlobServiceClient.from_connection_string(connection_str) container_client = blob_service_client.get_container_client(container) blobs_list = container_client.list_blobs(folder_root) for blob in ...
2020/07/01
[ "https://Stackoverflow.com/questions/62670991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6153466/" ]
You could download the file from blob storage, then read the data into a pandas DataFrame from the downloaded file. ``` from azure.storage.blob import BlockBlobService import pandas as pd import tables STORAGEACCOUNTNAME= <storage_account_name> STORAGEACCOUNTKEY= <storage_account_key> LOCALFILENAME= <local_file_name>...
BlockBlobService is indeed deprecated. However, @Deepak's answer doesn't work for me. Below works: ``` import pandas as pd from io import BytesIO from azure.storage.blob import BlobServiceClient CONNECTION_STRING= <connection_string> CONTAINERNAME= <container_name> BLOBNAME= <blob_name> blob_service_client = BlobSer...
62,670,991
I'm trying to read multiple CSV files from blob storage using python. The code that I'm using is: ``` blob_service_client = BlobServiceClient.from_connection_string(connection_str) container_client = blob_service_client.get_container_client(container) blobs_list = container_client.list_blobs(folder_root) for blob in ...
2020/07/01
[ "https://Stackoverflow.com/questions/62670991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6153466/" ]
``` import pandas as pd data = pd.read_csv('blob_sas_url') ``` The Blob SAS Url can be found by right clicking on the azure portal's blob file that you want to import and selecting Generate SAS. Then, click Generate SAS token and URL button and copy the SAS url to above code in place of blob\_sas\_url.
You can now directly read from BlobStorage into a Pandas DataFrame: ``` mydata = pd.read_csv( f"abfs://{blob_path}", storage_options={ "connection_string": os.environ["STORAGE_CONNECTION"] }) ``` where `blob_path` is the path to your file, given as `{container-name}/{blob-preifx.csv}`
62,670,991
I'm trying to read multiple CSV files from blob storage using python. The code that I'm using is: ``` blob_service_client = BlobServiceClient.from_connection_string(connection_str) container_client = blob_service_client.get_container_client(container) blobs_list = container_client.list_blobs(folder_root) for blob in ...
2020/07/01
[ "https://Stackoverflow.com/questions/62670991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6153466/" ]
``` import pandas as pd data = pd.read_csv('blob_sas_url') ``` The Blob SAS Url can be found by right clicking on the azure portal's blob file that you want to import and selecting Generate SAS. Then, click Generate SAS token and URL button and copy the SAS url to above code in place of blob\_sas\_url.
The BlockBlobService as part of azure-storage is deprecated. Use below instead: ``` !pip install azure-storage-blob from azure.storage.blob import BlobServiceClient import pandas as pd STORAGEACCOUNTURL= <storage_account_url> STORAGEACCOUNTKEY= <storage_account_key> LOCALFILENAME= <local_file_name> CONTAINERNAME= <co...
62,670,991
I'm trying to read multiple CSV files from blob storage using python. The code that I'm using is: ``` blob_service_client = BlobServiceClient.from_connection_string(connection_str) container_client = blob_service_client.get_container_client(container) blobs_list = container_client.list_blobs(folder_root) for blob in ...
2020/07/01
[ "https://Stackoverflow.com/questions/62670991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6153466/" ]
``` import pandas as pd data = pd.read_csv('blob_sas_url') ``` The Blob SAS Url can be found by right clicking on the azure portal's blob file that you want to import and selecting Generate SAS. Then, click Generate SAS token and URL button and copy the SAS url to above code in place of blob\_sas\_url.
BlockBlobService is indeed deprecated. However, @Deepak's answer doesn't work for me. Below works: ``` import pandas as pd from io import BytesIO from azure.storage.blob import BlobServiceClient CONNECTION_STRING= <connection_string> CONTAINERNAME= <container_name> BLOBNAME= <blob_name> blob_service_client = BlobSer...
936,933
If you raise a KeyboardInterrupt while trying to acquire a semaphore, the threads that also try to release the same semaphore object hang indefinitely. Code: ``` import threading import time def worker(i, sema): time.sleep(2) print i, "finished" sema.release() sema = threading.BoundedSemaphore(value=5) ...
2009/06/01
[ "https://Stackoverflow.com/questions/936933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41613/" ]
You can use the signal module to set a flag that tells the main thread to stop processing: ``` import threading import time import signal import sys sigint = False def sighandler(num, frame): global sigint sigint = True def worker(i, sema): time.sleep(2) print i, "finished" sema.release() signal.signal(s...
In this case, it looks like you might just want to use a thread pool to control the starting and stopping of your threads. You could use [Chris Arndt's threadpool library](http://www.chrisarndt.de/projects/threadpool/) in a manner something like this: ``` pool = ThreadPool(5) try: # enqueue 100 worker threads ...
936,933
If you raise a KeyboardInterrupt while trying to acquire a semaphore, the threads that also try to release the same semaphore object hang indefinitely. Code: ``` import threading import time def worker(i, sema): time.sleep(2) print i, "finished" sema.release() sema = threading.BoundedSemaphore(value=5) ...
2009/06/01
[ "https://Stackoverflow.com/questions/936933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41613/" ]
You can use the signal module to set a flag that tells the main thread to stop processing: ``` import threading import time import signal import sys sigint = False def sighandler(num, frame): global sigint sigint = True def worker(i, sema): time.sleep(2) print i, "finished" sema.release() signal.signal(s...
In your original code you could also make the threads daemon threads. When you interrupt the script, the daemon threads all die as you expected. ``` t = ... t.setDaemon(True) t.start() ```
936,933
If you raise a KeyboardInterrupt while trying to acquire a semaphore, the threads that also try to release the same semaphore object hang indefinitely. Code: ``` import threading import time def worker(i, sema): time.sleep(2) print i, "finished" sema.release() sema = threading.BoundedSemaphore(value=5) ...
2009/06/01
[ "https://Stackoverflow.com/questions/936933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41613/" ]
You can use the signal module to set a flag that tells the main thread to stop processing: ``` import threading import time import signal import sys sigint = False def sighandler(num, frame): global sigint sigint = True def worker(i, sema): time.sleep(2) print i, "finished" sema.release() signal.signal(s...
This is bug [#11714](http://bugs.python.org/issue11714), and has been [patched](http://hg.python.org/cpython/rev/2253b8a18bbf) in newer versions of python. If you are using an older python, you could copy the the version of `Semaphore` found in that patch into your project and use it instead of relying on the buggy ve...
936,933
If you raise a KeyboardInterrupt while trying to acquire a semaphore, the threads that also try to release the same semaphore object hang indefinitely. Code: ``` import threading import time def worker(i, sema): time.sleep(2) print i, "finished" sema.release() sema = threading.BoundedSemaphore(value=5) ...
2009/06/01
[ "https://Stackoverflow.com/questions/936933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41613/" ]
You can use the signal module to set a flag that tells the main thread to stop processing: ``` import threading import time import signal import sys sigint = False def sighandler(num, frame): global sigint sigint = True def worker(i, sema): time.sleep(2) print i, "finished" sema.release() signal.signal(s...
``` # importing modules import threading import time # defining our worker and pass a counter and the semaphore to it def worker(i, sema): time.sleep(2) print i, "finished" # releasing the thread increments the sema value sema.release() # creating the semaphore object sema = threading.BoundedSemaphore(...
936,933
If you raise a KeyboardInterrupt while trying to acquire a semaphore, the threads that also try to release the same semaphore object hang indefinitely. Code: ``` import threading import time def worker(i, sema): time.sleep(2) print i, "finished" sema.release() sema = threading.BoundedSemaphore(value=5) ...
2009/06/01
[ "https://Stackoverflow.com/questions/936933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41613/" ]
In your original code you could also make the threads daemon threads. When you interrupt the script, the daemon threads all die as you expected. ``` t = ... t.setDaemon(True) t.start() ```
In this case, it looks like you might just want to use a thread pool to control the starting and stopping of your threads. You could use [Chris Arndt's threadpool library](http://www.chrisarndt.de/projects/threadpool/) in a manner something like this: ``` pool = ThreadPool(5) try: # enqueue 100 worker threads ...
936,933
If you raise a KeyboardInterrupt while trying to acquire a semaphore, the threads that also try to release the same semaphore object hang indefinitely. Code: ``` import threading import time def worker(i, sema): time.sleep(2) print i, "finished" sema.release() sema = threading.BoundedSemaphore(value=5) ...
2009/06/01
[ "https://Stackoverflow.com/questions/936933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41613/" ]
In your original code you could also make the threads daemon threads. When you interrupt the script, the daemon threads all die as you expected. ``` t = ... t.setDaemon(True) t.start() ```
This is bug [#11714](http://bugs.python.org/issue11714), and has been [patched](http://hg.python.org/cpython/rev/2253b8a18bbf) in newer versions of python. If you are using an older python, you could copy the the version of `Semaphore` found in that patch into your project and use it instead of relying on the buggy ve...
936,933
If you raise a KeyboardInterrupt while trying to acquire a semaphore, the threads that also try to release the same semaphore object hang indefinitely. Code: ``` import threading import time def worker(i, sema): time.sleep(2) print i, "finished" sema.release() sema = threading.BoundedSemaphore(value=5) ...
2009/06/01
[ "https://Stackoverflow.com/questions/936933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41613/" ]
In your original code you could also make the threads daemon threads. When you interrupt the script, the daemon threads all die as you expected. ``` t = ... t.setDaemon(True) t.start() ```
``` # importing modules import threading import time # defining our worker and pass a counter and the semaphore to it def worker(i, sema): time.sleep(2) print i, "finished" # releasing the thread increments the sema value sema.release() # creating the semaphore object sema = threading.BoundedSemaphore(...
48,561,126
I installed opencv on my Ubuntu 14.04 system system with ``` pip install python-opencv ``` my Python version is 2.7.14 ``` import cv2 cv2.__version__ ``` tells me that I have the OpenCV version 3.4.0. After that I wanted to follow the tutorial on the OpenCV website ``` import numpy as np import cv2 as cv img =...
2018/02/01
[ "https://Stackoverflow.com/questions/48561126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3977420/" ]
Apparently ``` pip install python-opencv ``` is not working at all and should not be used. After I installed Opencv from their website it worked
Try checking if the image you are reading is loading ``` image = cv2.imread(filepath,0) #0 for gray scale if image is None: print "Cant Load Image" else: cv2.imshow("Image", image) cv2.waitKey(0) ```
48,561,126
I installed opencv on my Ubuntu 14.04 system system with ``` pip install python-opencv ``` my Python version is 2.7.14 ``` import cv2 cv2.__version__ ``` tells me that I have the OpenCV version 3.4.0. After that I wanted to follow the tutorial on the OpenCV website ``` import numpy as np import cv2 as cv img =...
2018/02/01
[ "https://Stackoverflow.com/questions/48561126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3977420/" ]
Try checking if the image you are reading is loading ``` image = cv2.imread(filepath,0) #0 for gray scale if image is None: print "Cant Load Image" else: cv2.imshow("Image", image) cv2.waitKey(0) ```
seems hard to install opencv on ubuntu, I finally get it with a docker image <https://hub.docker.com/r/jjanzic/docker-python3-opencv/> or you can download sources and make install as described on <https://milq.github.io/install-opencv-ubuntu-debian/> using bash script
48,561,126
I installed opencv on my Ubuntu 14.04 system system with ``` pip install python-opencv ``` my Python version is 2.7.14 ``` import cv2 cv2.__version__ ``` tells me that I have the OpenCV version 3.4.0. After that I wanted to follow the tutorial on the OpenCV website ``` import numpy as np import cv2 as cv img =...
2018/02/01
[ "https://Stackoverflow.com/questions/48561126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3977420/" ]
Apparently ``` pip install python-opencv ``` is not working at all and should not be used. After I installed Opencv from their website it worked
seems hard to install opencv on ubuntu, I finally get it with a docker image <https://hub.docker.com/r/jjanzic/docker-python3-opencv/> or you can download sources and make install as described on <https://milq.github.io/install-opencv-ubuntu-debian/> using bash script
30,324,474
**Using the "re" i compile the datas of a handshake like this:** ``` piece_request_handshake = re.compile('13426974546f7272656e742070726f746f636f6c(?P<reserved>\w{16})(?P<info_hash>\w{40})(?P<peer_id>\w{40})') handshake = piece_request_handshake.findall(hex_data) ``` *Then i print it* **I'm unable to add image b...
2015/05/19
[ "https://Stackoverflow.com/questions/30324474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872475/" ]
`re.findall()` returns a list of tuples, each containing the matching strings that correspond to the named groups in the re pattern. This example (using a simplified pattern) demonstrates that you can access the required item with indexing: ``` import re prefix = 'prefix' pattern = re.compile('%s(?P<reserved>\w{4})(?...
`re.findall` will return a list of tuples. The `group()` call works on `Match` objects, returned by some other functions in `re`: ``` for match in re.finditer(needle, haystack): print match.group('info_hash') ``` Also, you might not need `findall` if you're just matching a single handshake.
30,542,336
I am new to python and trying to learn the recursion. I'm trying to display all possible outcomes by changing 'a' to either number 7 or 8 For example, ``` user_type = 40aa ``` so it will display: ``` 4077 4078 4087 4088 ``` thank you it doesn't have to be 40aa, it can be a4a0, aaa0, etc this code is only r...
2015/05/30
[ "https://Stackoverflow.com/questions/30542336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4955371/" ]
``` pattern = "40aa" options = [7, 8] def replace(left, right): if len(right) > 0: if right[0] == "a": results = [] for i in options: results.extend(replace(left + str(i), right[1:])) return results else: return replace(left + right[0], right[1:]) else...
I don't know Python very well, but I can help with the recursion. The basic idea is that you will loop through each character in the string, and each time you hit an 'a', you will replace it with a 7 and an 8, and pass both of those values to your recursive method. Here is an example: Suppose you have the string "Bast...
30,542,336
I am new to python and trying to learn the recursion. I'm trying to display all possible outcomes by changing 'a' to either number 7 or 8 For example, ``` user_type = 40aa ``` so it will display: ``` 4077 4078 4087 4088 ``` thank you it doesn't have to be 40aa, it can be a4a0, aaa0, etc this code is only r...
2015/05/30
[ "https://Stackoverflow.com/questions/30542336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4955371/" ]
``` pattern = "40aa" options = [7, 8] def replace(left, right): if len(right) > 0: if right[0] == "a": results = [] for i in options: results.extend(replace(left + str(i), right[1:])) return results else: return replace(left + right[0], right[1:]) else...
So, we can do this in a fairly straightforward way. We need to create two lists: ``` user_type.split('a') == ['40', '', ''] itertools.product('78', repeat=user_type.count('a')) == [('7', '7'), ('7', '8'), ('8', '7'), ('8', '8')] ``` Now, for each of our pairs, we need to interleave them. The `itertools` documentatio...
22,770,352
I am trying to predict weekly sales using ARMA ARIMA models. I could not find a function for tuning the order(p,d,q) in `statsmodels`. Currently R has a function `forecast::auto.arima()` which will tune the (p,d,q) parameters. How do I go about choosing the right order for my model? Are there any libraries availabl...
2014/03/31
[ "https://Stackoverflow.com/questions/22770352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483927/" ]
``` def evaluate_arima_model(X, arima_order): # prepare training dataset train_size = int(len(X) * 0.90) train, test = X[0:train_size], X[train_size:] history = [x for x in train] # make predictions predictions = list() for t in range(len(test)): model = ARIMA(history, order=arima_or...
I wrote these utility functions to directly calculate pdq values *get\_PDQ\_parallel* require three inputs data which is series with timestamp(datetime) as index. n\_jobs will provide number of parallel processor. output will be dataframe with aic and bic value with order=(P,D,Q) in index p and q range is [0,12] while...
22,770,352
I am trying to predict weekly sales using ARMA ARIMA models. I could not find a function for tuning the order(p,d,q) in `statsmodels`. Currently R has a function `forecast::auto.arima()` which will tune the (p,d,q) parameters. How do I go about choosing the right order for my model? Are there any libraries availabl...
2014/03/31
[ "https://Stackoverflow.com/questions/22770352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483927/" ]
As of now, we can directly use [pyramid-arima](https://pypi.org/project/pyramid-arima/) package from PyPI.
In conda, use `conda install -c saravji pmdarima` to install. The user `saravji` has put it in anaconda cloud. then to use, ``` from pmdarima.arima import auto_arima ``` (Note that the name `pyramid-arima` is changed to `pmdarima`).
22,770,352
I am trying to predict weekly sales using ARMA ARIMA models. I could not find a function for tuning the order(p,d,q) in `statsmodels`. Currently R has a function `forecast::auto.arima()` which will tune the (p,d,q) parameters. How do I go about choosing the right order for my model? Are there any libraries availabl...
2014/03/31
[ "https://Stackoverflow.com/questions/22770352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483927/" ]
You can implement a number of approaches: 1. [`ARIMAResults`](http://statsmodels.sourceforge.net/stable/generated/statsmodels.tsa.arima_model.ARIMAResults.html#statsmodels.tsa.arima_model.ARIMAResults) include `aic` and `bic`. By their definition, (see [here](http://en.wikipedia.org/wiki/Akaike_information_criterion) ...
possible solution ``` df=pd.read_csv("http://vincentarelbundock.github.io/Rdatasets/csv/datasets/AirPassengers.csv") # Define the p, d and q parameters to take any value between 0 and 2 p = d = q = range(0, 2) print(p) import itertools import warnings # Generate all different combinations of p, q and q triplets pdq...
22,770,352
I am trying to predict weekly sales using ARMA ARIMA models. I could not find a function for tuning the order(p,d,q) in `statsmodels`. Currently R has a function `forecast::auto.arima()` which will tune the (p,d,q) parameters. How do I go about choosing the right order for my model? Are there any libraries availabl...
2014/03/31
[ "https://Stackoverflow.com/questions/22770352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483927/" ]
I wrote these utility functions to directly calculate pdq values *get\_PDQ\_parallel* require three inputs data which is series with timestamp(datetime) as index. n\_jobs will provide number of parallel processor. output will be dataframe with aic and bic value with order=(P,D,Q) in index p and q range is [0,12] while...
In conda, use `conda install -c saravji pmdarima` to install. The user `saravji` has put it in anaconda cloud. then to use, ``` from pmdarima.arima import auto_arima ``` (Note that the name `pyramid-arima` is changed to `pmdarima`).
22,770,352
I am trying to predict weekly sales using ARMA ARIMA models. I could not find a function for tuning the order(p,d,q) in `statsmodels`. Currently R has a function `forecast::auto.arima()` which will tune the (p,d,q) parameters. How do I go about choosing the right order for my model? Are there any libraries availabl...
2014/03/31
[ "https://Stackoverflow.com/questions/22770352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483927/" ]
possible solution ``` df=pd.read_csv("http://vincentarelbundock.github.io/Rdatasets/csv/datasets/AirPassengers.csv") # Define the p, d and q parameters to take any value between 0 and 2 p = d = q = range(0, 2) print(p) import itertools import warnings # Generate all different combinations of p, q and q triplets pdq...
actually ``` def objfunc(order,*params ): from statsmodels.tsa.arima_model import ARIMA p,d,q = order fit = ARIMA(endog, order, exog).fit() return fit.aic() from scipy.optimize import brute grid = (slice(1, 3, 1), slice(1, 3, 1), slice(1, 3, 1)) brute(objfunc, grid, args=params, finish=...
22,770,352
I am trying to predict weekly sales using ARMA ARIMA models. I could not find a function for tuning the order(p,d,q) in `statsmodels`. Currently R has a function `forecast::auto.arima()` which will tune the (p,d,q) parameters. How do I go about choosing the right order for my model? Are there any libraries availabl...
2014/03/31
[ "https://Stackoverflow.com/questions/22770352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483927/" ]
You can implement a number of approaches: 1. [`ARIMAResults`](http://statsmodels.sourceforge.net/stable/generated/statsmodels.tsa.arima_model.ARIMAResults.html#statsmodels.tsa.arima_model.ARIMAResults) include `aic` and `bic`. By their definition, (see [here](http://en.wikipedia.org/wiki/Akaike_information_criterion) ...
There is now a proper python package to do auto-arima. <https://github.com/tgsmith61591/pmdarima> Docs: <http://alkaline-ml.com/pmdarima> Example usage: <https://github.com/tgsmith61591/pmdarima/blob/master/examples/quick_start_example.ipynb>
22,770,352
I am trying to predict weekly sales using ARMA ARIMA models. I could not find a function for tuning the order(p,d,q) in `statsmodels`. Currently R has a function `forecast::auto.arima()` which will tune the (p,d,q) parameters. How do I go about choosing the right order for my model? Are there any libraries availabl...
2014/03/31
[ "https://Stackoverflow.com/questions/22770352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483927/" ]
``` def evaluate_arima_model(X, arima_order): # prepare training dataset train_size = int(len(X) * 0.90) train, test = X[0:train_size], X[train_size:] history = [x for x in train] # make predictions predictions = list() for t in range(len(test)): model = ARIMA(history, order=arima_or...
actually ``` def objfunc(order,*params ): from statsmodels.tsa.arima_model import ARIMA p,d,q = order fit = ARIMA(endog, order, exog).fit() return fit.aic() from scipy.optimize import brute grid = (slice(1, 3, 1), slice(1, 3, 1), slice(1, 3, 1)) brute(objfunc, grid, args=params, finish=...
22,770,352
I am trying to predict weekly sales using ARMA ARIMA models. I could not find a function for tuning the order(p,d,q) in `statsmodels`. Currently R has a function `forecast::auto.arima()` which will tune the (p,d,q) parameters. How do I go about choosing the right order for my model? Are there any libraries availabl...
2014/03/31
[ "https://Stackoverflow.com/questions/22770352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483927/" ]
As of now, we can directly use [pyramid-arima](https://pypi.org/project/pyramid-arima/) package from PyPI.
actually ``` def objfunc(order,*params ): from statsmodels.tsa.arima_model import ARIMA p,d,q = order fit = ARIMA(endog, order, exog).fit() return fit.aic() from scipy.optimize import brute grid = (slice(1, 3, 1), slice(1, 3, 1), slice(1, 3, 1)) brute(objfunc, grid, args=params, finish=...
22,770,352
I am trying to predict weekly sales using ARMA ARIMA models. I could not find a function for tuning the order(p,d,q) in `statsmodels`. Currently R has a function `forecast::auto.arima()` which will tune the (p,d,q) parameters. How do I go about choosing the right order for my model? Are there any libraries availabl...
2014/03/31
[ "https://Stackoverflow.com/questions/22770352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483927/" ]
There is now a proper python package to do auto-arima. <https://github.com/tgsmith61591/pmdarima> Docs: <http://alkaline-ml.com/pmdarima> Example usage: <https://github.com/tgsmith61591/pmdarima/blob/master/examples/quick_start_example.ipynb>
I wrote these utility functions to directly calculate pdq values *get\_PDQ\_parallel* require three inputs data which is series with timestamp(datetime) as index. n\_jobs will provide number of parallel processor. output will be dataframe with aic and bic value with order=(P,D,Q) in index p and q range is [0,12] while...
22,770,352
I am trying to predict weekly sales using ARMA ARIMA models. I could not find a function for tuning the order(p,d,q) in `statsmodels`. Currently R has a function `forecast::auto.arima()` which will tune the (p,d,q) parameters. How do I go about choosing the right order for my model? Are there any libraries availabl...
2014/03/31
[ "https://Stackoverflow.com/questions/22770352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483927/" ]
There is now a proper python package to do auto-arima. <https://github.com/tgsmith61591/pmdarima> Docs: <http://alkaline-ml.com/pmdarima> Example usage: <https://github.com/tgsmith61591/pmdarima/blob/master/examples/quick_start_example.ipynb>
actually ``` def objfunc(order,*params ): from statsmodels.tsa.arima_model import ARIMA p,d,q = order fit = ARIMA(endog, order, exog).fit() return fit.aic() from scipy.optimize import brute grid = (slice(1, 3, 1), slice(1, 3, 1), slice(1, 3, 1)) brute(objfunc, grid, args=params, finish=...
68,562,020
This is my code ``` import pandas as pd keys = ['phone match', 'account match'] d = {k: [] for k in keys} df = pd.DataFrame(data=[[1,2,3],[4,5,6]],columns=['A','B','C']) df['D'] = [d for _ in range(df.shape[0])] df.at[0, 'D']['phone match'].append(4) ``` But instead of appending only on the dictionary at index 0 i...
2021/07/28
[ "https://Stackoverflow.com/questions/68562020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16546771/" ]
You need to create multiple `dict` in order to make each of them have different object ID ``` keys = ['phone match', 'account match'] df = pd.DataFrame(data=[[1,2,3],[4,5,6]],columns=['A','B','C']) df['D'] = [{k: [] for k in keys} for _ in range(df.shape[0])] # Change here df.at[0, 'D']['phone match'].append(4) df Ou...
`dict` objects are passed by reference in python. In order to achieve what you want, you can use the following line which creates a copy of d for every line: ``` df['D'] = [d.copy() for _ in range(df.shape[0])] ```
31,518,864
I am currently generating 8 random values each time I run a program on Python. These 8 values are different each time I run the program, and I would like to be able to now save these 8 values each time I run the program to a text file in 8 separate columns. When saving these values for future runs, though, I would like...
2015/07/20
[ "https://Stackoverflow.com/questions/31518864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5135338/" ]
``` import csv from tempfile import NamedTemporaryFile from shutil import move from itertools import chain with open("in.csv") as f, NamedTemporaryFile(dir=".", delete=False) as temp: r = csv.reader(f) new = [9, 10, 11, 12, 13, 14, 15, 16] wr = csv.writer(temp) wr.writerows(zip(chain.from_iterable(r), n...
what about ``` a = [1, 2, 3, 4, 5, 6, 7, 8] f = open('myFile.txt', 'a') for n in a: f.write('%d\t'%n) f.write('\n') f.close() ``` and you get as file content after running it 4 times 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 ======= EDIT ========= Try this, its ugly but works...
66,602,674
I have two e2e automation framework , one is python based other is protractor based. I need to write a docker-compose file to run these two projects in different containers and fetch reports and their console to my local system. below are the contents of my docker-compose.yml file ``` version: '3' services: e2e-Tes...
2021/03/12
[ "https://Stackoverflow.com/questions/66602674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7074479/" ]
Try to rename: `Dockerfile` instead of `DockerFile`. **Edit:** When the docker file name is not provided explicitly, it will look for the file `Dockerfile` with a small `f`. My issue was as simple that.
My issue was related to registry access issues. It works fine now.
53,402,349
i build regex expression that matches 2 letters or 2 letters folowed by '/' and next 2 letters for example: ``` rt bl/ws se gn/wd wk bl/rt /^(((\s+)?[a-zA-Z]{2}(\/[a-zA-Z]{2})?)(\s+|$))+$/i ``` and that works without problems. Next problem what I have is match all "word" not containing '/' character. and replace a...
2018/11/20
[ "https://Stackoverflow.com/questions/53402349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1743688/" ]
A list comprehension should do the trick: ``` >>> NUM_ITEMS = 5 >>> my_array = [[0, 1] for _ in range(NUM_ITEMS)] >>> my_array [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] ```
Since you tagged arrays, here's an alternative `numpy` solution using [`numpy.tile`](https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.tile.html). ``` >>> import numpy as np >>> NUM_ITEMS = 10 >>> np.tile([0, 1], (NUM_ITEMS, 1)) array([[0, 1], [0, 1], [0, 1], [0, 1], [0, 1],...
49,695,050
I'm trying to write a csv file into an S3 bucket using AWS Lambda, and for this I used the following code: ``` data=[[1,2,3],[23,56,98]] with open("s3://my_bucket/my_file.csv", "w") as f: f.write(data) ``` And this raises the following error: ``` [Errno 2] No such file or directory: u's3://my_bucket/my_file.csv'...
2018/04/06
[ "https://Stackoverflow.com/questions/49695050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6598781/" ]
Better to answer later than never. There are four steps to get your data in S3: * Call the S3 bucket * Load the data into Lambda using the requests library (if you don't have it installed, you are gonna have to load it as a layer) * Write the data into the Lambda '/tmp' file * Upload the file into s3 Something like t...
``` with open("s3://my_bucket/my_file.csv", "w+") as f: ``` instead of ``` with open("s3://my_bucket/my_file.csv", "w") as f: ``` notice the "w" has changed to "w+" this means that it will write to the file, and if it does not exist it will create it.
49,695,050
I'm trying to write a csv file into an S3 bucket using AWS Lambda, and for this I used the following code: ``` data=[[1,2,3],[23,56,98]] with open("s3://my_bucket/my_file.csv", "w") as f: f.write(data) ``` And this raises the following error: ``` [Errno 2] No such file or directory: u's3://my_bucket/my_file.csv'...
2018/04/06
[ "https://Stackoverflow.com/questions/49695050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6598781/" ]
Better to answer later than never. There are four steps to get your data in S3: * Call the S3 bucket * Load the data into Lambda using the requests library (if you don't have it installed, you are gonna have to load it as a layer) * Write the data into the Lambda '/tmp' file * Upload the file into s3 Something like t...
I am not aware of using AWS Lambda, but I have been using Boto3 to do the same. It is a simple few line code. ``` #Your file path will be something like this: #s3://<your_s3_bucket_name>/<Directory_name>/<File_name>.csv import boto3 BUCKET_NAME = '<your_s3_bucket_name>' PREFIX = '<Directory_name>/' s3 = boto3.resour...
51,400,332
I want the insertion query do nothing if it's nothing new in csv file , In Case it is , i want to insert only this one and not again all the csv, any suggestion would be great! PS: it's not duplicate with other questions because here we have "%s" no stable values and in python it's different the syntax! ``` curs...
2018/07/18
[ "https://Stackoverflow.com/questions/51400332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9855183/" ]
You should do something like this: ``` class eventCell: UICollectionViewCell { @IBOutlet private weak var eventTitle: UILabel! @IBOutlet private weak var descriptionLabel:UILabel! @IBOutlet private weak var eventImage: UIImageView! typealias Event = (title:String, location:String, lat:CLLocationDegree...
Why not creating some `Struct`? Simple like this: ``` struct Event { var title: String var location: String var lat: CLLocationDegrees var long: CLLocationDegrees } ``` Then just do that: ``` var eventArray = [Event]() ``` And call it like that: ``` for event in eventArray{ event.title = eventTitle...
68,714,450
I have 2 dataframes: **users** ``` user_id position 0 201 Senior Engineer 1 207 Senior System Architect 2 223 Senior account manage 3 212 Junior Manager 4 112 junior Engineer 5 311 junior python developer ``` ``` df1 = pd.DataFrame({'user_id': ['201', '207', '223', '212', '112', '311'], ...
2021/08/09
[ "https://Stackoverflow.com/questions/68714450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16580145/" ]
You can use `str.extract()`+`merge()`: ``` pat='('+'|'.join(df2['role_position'].str.strip('%').unique())+')' df1['role_position']='%'+df1['position'].str.lower().str.extract(pat,expand=False)+'%' df1=df1.merge(df2,on='role_position',how='left') ``` output of `df1`: ``` user_id position role_id role...
Possibilities: * [fuzzy words](https://www.google.com/search?q=fuzzy%20in%20pandas&rlz=1C5CHFA_enPL889PL889&oq=fuzzy%20in%20pandas&aqs=chrome..69i57j0i10i22i30j0i22i30.2529j0j7&sourceid=chrome&ie=UTF-8) * [Sequence Matcher](https://towardsdatascience.com/sequencematcher-in-python-6b1e6f3915fc) * [.extract](https://www...
68,714,450
I have 2 dataframes: **users** ``` user_id position 0 201 Senior Engineer 1 207 Senior System Architect 2 223 Senior account manage 3 212 Junior Manager 4 112 junior Engineer 5 311 junior python developer ``` ``` df1 = pd.DataFrame({'user_id': ['201', '207', '223', '212', '112', '311'], ...
2021/08/09
[ "https://Stackoverflow.com/questions/68714450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16580145/" ]
You can use `str.extract()`+`merge()`: ``` pat='('+'|'.join(df2['role_position'].str.strip('%').unique())+')' df1['role_position']='%'+df1['position'].str.lower().str.extract(pat,expand=False)+'%' df1=df1.merge(df2,on='role_position',how='left') ``` output of `df1`: ``` user_id position role_id role...
You can generate a dict of mappings and then map the values: ``` df2['role_position'] = df2['role_position'].str.strip('%') mappings = df2.set_index('role_position').to_dict('dict')['role_id'] >> mappings {'senior': '10', 'junior': '20'} ``` Using a regular expression we can extract the roles for each position: ``...
68,714,450
I have 2 dataframes: **users** ``` user_id position 0 201 Senior Engineer 1 207 Senior System Architect 2 223 Senior account manage 3 212 Junior Manager 4 112 junior Engineer 5 311 junior python developer ``` ``` df1 = pd.DataFrame({'user_id': ['201', '207', '223', '212', '112', '311'], ...
2021/08/09
[ "https://Stackoverflow.com/questions/68714450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16580145/" ]
You can save some trouble by doing a `merge` directly if the seniority level always start at front: ``` print (pd.merge(df, df2, left_on=df["position"].str.split().str[0].str.lower(), right_on=df2["role_position"].str.strip("%")).drop("key_0", axis=1)) ``` Else you can do a `pd.Series...
Possibilities: * [fuzzy words](https://www.google.com/search?q=fuzzy%20in%20pandas&rlz=1C5CHFA_enPL889PL889&oq=fuzzy%20in%20pandas&aqs=chrome..69i57j0i10i22i30j0i22i30.2529j0j7&sourceid=chrome&ie=UTF-8) * [Sequence Matcher](https://towardsdatascience.com/sequencematcher-in-python-6b1e6f3915fc) * [.extract](https://www...
68,714,450
I have 2 dataframes: **users** ``` user_id position 0 201 Senior Engineer 1 207 Senior System Architect 2 223 Senior account manage 3 212 Junior Manager 4 112 junior Engineer 5 311 junior python developer ``` ``` df1 = pd.DataFrame({'user_id': ['201', '207', '223', '212', '112', '311'], ...
2021/08/09
[ "https://Stackoverflow.com/questions/68714450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16580145/" ]
You can save some trouble by doing a `merge` directly if the seniority level always start at front: ``` print (pd.merge(df, df2, left_on=df["position"].str.split().str[0].str.lower(), right_on=df2["role_position"].str.strip("%")).drop("key_0", axis=1)) ``` Else you can do a `pd.Series...
You can generate a dict of mappings and then map the values: ``` df2['role_position'] = df2['role_position'].str.strip('%') mappings = df2.set_index('role_position').to_dict('dict')['role_id'] >> mappings {'senior': '10', 'junior': '20'} ``` Using a regular expression we can extract the roles for each position: ``...
61,253,507
I am parsing json file that has the following data subset. ``` "title": "Revert \"testcase for check\"" ``` In my python script I do the following: ``` with open('%s/staging_area/pr_info.json' % cwd) as data_file: pr_info = json.load(data_file) pr_title=pr_info["title"]...
2020/04/16
[ "https://Stackoverflow.com/questions/61253507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9828901/" ]
If you really need it, you should escape it again with json and remove first and last quote: ```py pr_title = json.dumps(pr_title)[1:-1] ``` but escape characters is for escaping, raw value of string is still `Revert "testcase for check"`. So escaping function will depend on where you data is applied (DB, HTML, XML,...
If your goal is to print pr\_title, then you can probably use json.dumps() to print the original text. ``` >>> import json >>> j = '{"name": "\"Bob\""}' >>> print(j) {"name": ""Bob""} >>> json.dumps(j) '"{\\"name\\": \\"\\"Bob\\"\\"}"' ```
61,253,507
I am parsing json file that has the following data subset. ``` "title": "Revert \"testcase for check\"" ``` In my python script I do the following: ``` with open('%s/staging_area/pr_info.json' % cwd) as data_file: pr_info = json.load(data_file) pr_title=pr_info["title"]...
2020/04/16
[ "https://Stackoverflow.com/questions/61253507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9828901/" ]
In case you really need to maintain the escape characters, you will have to escape the *escape characters* right after reading the file and before parsing the JSON. ``` with open('%s/staging_area/pr_info.json' % cwd) as data_file: raw_data_file = data_file.read().replace("\\", "\\\\\\") pr_info = json....
If your goal is to print pr\_title, then you can probably use json.dumps() to print the original text. ``` >>> import json >>> j = '{"name": "\"Bob\""}' >>> print(j) {"name": ""Bob""} >>> json.dumps(j) '"{\\"name\\": \\"\\"Bob\\"\\"}"' ```
62,618,261
I have 4 figures (y1,y2,y3,y4) that i want to plot on a common x axis (yr1,yr2,yr3,m1,m2,m3,m4,m5). In this code however i have kept axaxis as separate since i am trying to get the basics right first. ``` import matplotlib.pyplot as plt import numpy as np plt.figure(1) xaxis = ['y1','y2','y3','m1','m2','m3', 'm4', 'm...
2020/06/28
[ "https://Stackoverflow.com/questions/62618261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5866905/" ]
Small mistake. You have put `plt.subplot` instead of `plt.plot`. This should work now: ``` import matplotlib.pyplot as plt import numpy as np plt.figure(1) xaxis = ['y1','y2','y3','m1','m2','m3', 'm4', 'm5'] y1 = np.array([.73,.74,.71,.75,.72,.75,.74,.74]) y2 = np.array([.82,.80,.77,.81,.72,.81,.77,.77]) y3 = np.arra...
Try this: ``` fig, ax = plt.subplots(4, 1,sharex=True,gridspec_kw= {'height_ratios':[3,1,1,1]}) ax[0].plot(xais,y1) ax[1].plot(xais,y1) ax[2].plot(xais,y1) ax[3].plot(xais,y1) ``` for 4 figures stacked on top of each other with shared x-axis. for 2x2: ``` fig, ax = plt.subplots(2,2) ax[0,0].plot(xaxis,y1) ax[0,1]....
62,618,261
I have 4 figures (y1,y2,y3,y4) that i want to plot on a common x axis (yr1,yr2,yr3,m1,m2,m3,m4,m5). In this code however i have kept axaxis as separate since i am trying to get the basics right first. ``` import matplotlib.pyplot as plt import numpy as np plt.figure(1) xaxis = ['y1','y2','y3','m1','m2','m3', 'm4', 'm...
2020/06/28
[ "https://Stackoverflow.com/questions/62618261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5866905/" ]
Reusing Sahith Kurapati's code just to provide a cleaner solution. This way you can share axes and only configure line and chart styles once if they're all supposed to have the same style. ```py import matplotlib.pyplot as plt import numpy as np plt.figure(1) xaxis = ['y1','y2','y3','m1','m2','m3', 'm4', 'm5'] yy = n...
Try this: ``` fig, ax = plt.subplots(4, 1,sharex=True,gridspec_kw= {'height_ratios':[3,1,1,1]}) ax[0].plot(xais,y1) ax[1].plot(xais,y1) ax[2].plot(xais,y1) ax[3].plot(xais,y1) ``` for 4 figures stacked on top of each other with shared x-axis. for 2x2: ``` fig, ax = plt.subplots(2,2) ax[0,0].plot(xaxis,y1) ax[0,1]....
45,063,974
I have a sqlite table with 3 columns named ID (integer), N (integer) and V (real). The pair (ID, N) is unique. Using the python module sqlite3, I would like to perform a recursive selection with the form ``` select ID from TABLE where N = 0 and V between ? and ? and ID in (select ID from TABLE where N = 7 and V...
2017/07/12
[ "https://Stackoverflow.com/questions/45063974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2660966/" ]
Unwrap the recursion, do it in reverse order and do it in Python. For this I created a table consisting of 100 records, each with an Id between 0 and 99, N=3 and V=5. Arbitrarily I selected the entire collection of records as the innermost. You need to imagine having a list of values for N and V indexed so that the v...
Indexing the triplet (ID, N, V) instead of only the (N, V) doublet made the join approach fast enough for being considered ``` create index I on TABLE(ID, N, V) ``` and then ``` select ID from (select ID from TABLE where N = 0 and V between ? and ?) join (select ID from TABLE where N = 7 and V betw...
45,063,974
I have a sqlite table with 3 columns named ID (integer), N (integer) and V (real). The pair (ID, N) is unique. Using the python module sqlite3, I would like to perform a recursive selection with the form ``` select ID from TABLE where N = 0 and V between ? and ? and ID in (select ID from TABLE where N = 7 and V...
2017/07/12
[ "https://Stackoverflow.com/questions/45063974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2660966/" ]
Unwrap the recursion, do it in reverse order and do it in Python. For this I created a table consisting of 100 records, each with an Id between 0 and 99, N=3 and V=5. Arbitrarily I selected the entire collection of records as the innermost. You need to imagine having a list of values for N and V indexed so that the v...
This query requires only the (N, V) index for the subqueries. A separate index on ID might help for the outer query: ``` select ID from t where ID in (select ID from TABLE where N = 0 and V between ? and ?) and ID in (select ID from TABLE where N = 7 and V between ? and ?) and ID in (select ID from TABLE where N =...
45,063,974
I have a sqlite table with 3 columns named ID (integer), N (integer) and V (real). The pair (ID, N) is unique. Using the python module sqlite3, I would like to perform a recursive selection with the form ``` select ID from TABLE where N = 0 and V between ? and ? and ID in (select ID from TABLE where N = 7 and V...
2017/07/12
[ "https://Stackoverflow.com/questions/45063974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2660966/" ]
This query requires only the (N, V) index for the subqueries. A separate index on ID might help for the outer query: ``` select ID from t where ID in (select ID from TABLE where N = 0 and V between ? and ?) and ID in (select ID from TABLE where N = 7 and V between ? and ?) and ID in (select ID from TABLE where N =...
Indexing the triplet (ID, N, V) instead of only the (N, V) doublet made the join approach fast enough for being considered ``` create index I on TABLE(ID, N, V) ``` and then ``` select ID from (select ID from TABLE where N = 0 and V between ? and ?) join (select ID from TABLE where N = 7 and V betw...
28,506,726
I am new to the `subprocess` module in python. The documentation provided this example: ``` >>> subprocess.check_output(["echo", "Hello World!"]) b'Hello World!\n' ``` What I tried is: ``` >>> import subprocess >>> subprocess.check_output(["cd", "../tests", "ls"]) /usr/bin/cd: line 4: cd: ../tests: No such file o...
2015/02/13
[ "https://Stackoverflow.com/questions/28506726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1815710/" ]
The relative path to the `tests` directory depends on where the script is being run from. I would suggest calling `subprocess.check_output(["pwd"])` to check where you are. Also you can't combine two commands in the same call like in your attempt with `["cd", "../tests", "python", "printy.py"]`. You'll need to make tw...
You are missing a argument here I think. Here a snippet from the only python script I ever wrote: ``` #!/usr/local/bin/python from subprocess import call ... call( "rm " + backupFolder + "*.bz2", shell=True ) ``` Please note the `shell=True` in the end of that call.
28,506,726
I am new to the `subprocess` module in python. The documentation provided this example: ``` >>> subprocess.check_output(["echo", "Hello World!"]) b'Hello World!\n' ``` What I tried is: ``` >>> import subprocess >>> subprocess.check_output(["cd", "../tests", "ls"]) /usr/bin/cd: line 4: cd: ../tests: No such file o...
2015/02/13
[ "https://Stackoverflow.com/questions/28506726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1815710/" ]
**Try to avoid `shell=True` if possible.** In this case, you can certainly avoid. The problem you are facing is: `cd` is a shell builtin. Its not a command/program/utility that can be called from outside. You need to be within a shell for `cd` to work. What you can instead do is change your current directory. Execute ...
The relative path to the `tests` directory depends on where the script is being run from. I would suggest calling `subprocess.check_output(["pwd"])` to check where you are. Also you can't combine two commands in the same call like in your attempt with `["cd", "../tests", "python", "printy.py"]`. You'll need to make tw...
28,506,726
I am new to the `subprocess` module in python. The documentation provided this example: ``` >>> subprocess.check_output(["echo", "Hello World!"]) b'Hello World!\n' ``` What I tried is: ``` >>> import subprocess >>> subprocess.check_output(["cd", "../tests", "ls"]) /usr/bin/cd: line 4: cd: ../tests: No such file o...
2015/02/13
[ "https://Stackoverflow.com/questions/28506726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1815710/" ]
**Try to avoid `shell=True` if possible.** In this case, you can certainly avoid. The problem you are facing is: `cd` is a shell builtin. Its not a command/program/utility that can be called from outside. You need to be within a shell for `cd` to work. What you can instead do is change your current directory. Execute ...
You are missing a argument here I think. Here a snippet from the only python script I ever wrote: ``` #!/usr/local/bin/python from subprocess import call ... call( "rm " + backupFolder + "*.bz2", shell=True ) ``` Please note the `shell=True` in the end of that call.
28,506,726
I am new to the `subprocess` module in python. The documentation provided this example: ``` >>> subprocess.check_output(["echo", "Hello World!"]) b'Hello World!\n' ``` What I tried is: ``` >>> import subprocess >>> subprocess.check_output(["cd", "../tests", "ls"]) /usr/bin/cd: line 4: cd: ../tests: No such file o...
2015/02/13
[ "https://Stackoverflow.com/questions/28506726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1815710/" ]
The error message is clear: > > /usr/bin/cd: line 4: cd: ../tests: No such file or directory > > > that is you have successfully started `/usr/bin/cd` program that failed and printed the error message. If you wanted to run `ls` command from `../tests` directory instead: ``` import os import subprocess cwd = os...
You are missing a argument here I think. Here a snippet from the only python script I ever wrote: ``` #!/usr/local/bin/python from subprocess import call ... call( "rm " + backupFolder + "*.bz2", shell=True ) ``` Please note the `shell=True` in the end of that call.
28,506,726
I am new to the `subprocess` module in python. The documentation provided this example: ``` >>> subprocess.check_output(["echo", "Hello World!"]) b'Hello World!\n' ``` What I tried is: ``` >>> import subprocess >>> subprocess.check_output(["cd", "../tests", "ls"]) /usr/bin/cd: line 4: cd: ../tests: No such file o...
2015/02/13
[ "https://Stackoverflow.com/questions/28506726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1815710/" ]
**Try to avoid `shell=True` if possible.** In this case, you can certainly avoid. The problem you are facing is: `cd` is a shell builtin. Its not a command/program/utility that can be called from outside. You need to be within a shell for `cd` to work. What you can instead do is change your current directory. Execute ...
The error message is clear: > > /usr/bin/cd: line 4: cd: ../tests: No such file or directory > > > that is you have successfully started `/usr/bin/cd` program that failed and printed the error message. If you wanted to run `ls` command from `../tests` directory instead: ``` import os import subprocess cwd = os...
63,030,306
I have the below python snippet ```py @click.argument('file',type=click.Path(exists=True)) ``` The above command read from a file in the below format ```sh python3 code.py file.txt ``` The same file is processed using a function ```py def get_domains(domain_names_file): with open(domain_names_file) as f: ...
2020/07/22
[ "https://Stackoverflow.com/questions/63030306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8474328/" ]
`click.argument` by default creates arguments that are read from the command line: ``` @click.argument('file') ``` This should create an argument that is read from the command line and made available in the `file` argument. See the docs & examples [here](https://pocoo-click.readthedocs.io/en/latest/arguments/)
You may use `argparse`: ``` import argparse # set up the different arguments parser = argparse.ArgumentParser(description='Some nasty description here.') parser.add_argument("--domain", help="Domain: www.some-domain.com", required=True) args = parser.parse_args() print(args.domain) ``` And you invoke it via ```...
63,030,306
I have the below python snippet ```py @click.argument('file',type=click.Path(exists=True)) ``` The above command read from a file in the below format ```sh python3 code.py file.txt ``` The same file is processed using a function ```py def get_domains(domain_names_file): with open(domain_names_file) as f: ...
2020/07/22
[ "https://Stackoverflow.com/questions/63030306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8474328/" ]
I realised you're using the [click](https://click.palletsprojects.com/en/7.x/arguments) library. Since you want to pass the 'domain'/website as an argument, you can just input it as a string. If you remove the 'type' parameter from your decorator, it would make the type STRING by default. > > The most basic option is...
You may use `argparse`: ``` import argparse # set up the different arguments parser = argparse.ArgumentParser(description='Some nasty description here.') parser.add_argument("--domain", help="Domain: www.some-domain.com", required=True) args = parser.parse_args() print(args.domain) ``` And you invoke it via ```...
60,527,883
I have a dataset of 284 features I am trying to impute using scikit-learn, however I get an error where the number of features changes to 283: ``` imputer = SimpleImputer(missing_values = np.nan, strategy = "mean") imputer = imputer.fit(data.iloc[:,0:284]) df[:,0:284] = imputer.transform(df[:,0:284]) X = MinMaxScaler(...
2020/03/04
[ "https://Stackoverflow.com/questions/60527883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8831033/" ]
This could happen if you have a feature without any values, from <https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html>: 'Columns which only contained missing values at fit are discarded upon transform if strategy is not β€œconstant”'. You can tell if this is indeed the problem by using a h...
I was dealing with the same situation and i got my solution by adding this transformation before the SimpleImputer mean strategy ``` imputer = SimpleImputer(strategy = 'constant', fill_value = 0) df_prepared_to_mean_or_anything_else = imputer.fit_transform(previous_df) ``` What does it do? Fills everything missing w...
69,011,571
Which function was used for the following plot in R? At least it looks like a predefined function to me. Edit: Okay it seems to be Stata according Claudio. New question: Is there anything comparable in python/R to get this output? How to calculate Coef.? What kind of coefficient is this? [![enter image description h...
2021/09/01
[ "https://Stackoverflow.com/questions/69011571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15870842/" ]
You can simply switch over `status` inside the body of your view and assign the correct `String` and `foregroundColor` to your `Text` inside each `case. ``` struct StatusView: View { let status: Status var body: some View { switch status { case .accepted: Text("accepted") ...
Here is an updated and refactored answer based on **David** answer, with this way you do not need that `ststusColor` function anymore and you can access the **colorValue** every where in your project instead of last answer that was accessible only inside `StatusView`. ``` struct StatusView: View { let status: Sta...
5,373,474
I'm trying to use argparse to parse the command line arguments for a program I'm working on. Essentially, I need to support multiple positional arguments spread within the optional arguments, but cannot get argparse to work in this situation. In the actual program, I'm using a custom action (I need to store a snapshot ...
2011/03/21
[ "https://Stackoverflow.com/questions/5373474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/668807/" ]
You can't interleave the switches (i.e. `-a` and `-b`) with the positional arguments (i.e. fileone, filetwo and filethree) in this way. The switches must appear before or after the positional arguments, not in-between. Also, in order to have multiple positional arguments, you need to specify the `nargs` parameter to `...
The 'append' action makes more sense with an optional: ``` parser.add_argument('-i', '--input',action='append') parser.parse_args(['-i','fileone', '-a', '-i','filetwo', '-b', '-i','filethree']) ``` You can interleave optionals with separate positionals ('input1 -a input2 -b input3'), but you cannot interleave option...
5,373,474
I'm trying to use argparse to parse the command line arguments for a program I'm working on. Essentially, I need to support multiple positional arguments spread within the optional arguments, but cannot get argparse to work in this situation. In the actual program, I'm using a custom action (I need to store a snapshot ...
2011/03/21
[ "https://Stackoverflow.com/questions/5373474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/668807/" ]
You can't interleave the switches (i.e. `-a` and `-b`) with the positional arguments (i.e. fileone, filetwo and filethree) in this way. The switches must appear before or after the positional arguments, not in-between. Also, in order to have multiple positional arguments, you need to specify the `nargs` parameter to `...
It seems to me that hpaulj is on the right track but making things a bit more complicated than necessary. I suspect that Blair is looking for something akin to the behavior of the old optparse module and doesn't really need the list of input arguments in the inputs field of the args object. He just wants ``` import ar...
5,373,474
I'm trying to use argparse to parse the command line arguments for a program I'm working on. Essentially, I need to support multiple positional arguments spread within the optional arguments, but cannot get argparse to work in this situation. In the actual program, I'm using a custom action (I need to store a snapshot ...
2011/03/21
[ "https://Stackoverflow.com/questions/5373474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/668807/" ]
srgerg was right about the definition of positional arguments. In order to get the result you want, You have to accept them as optional arguments, and modify the resulted namespace according to your need. You can use a custom action: ``` class MyAction(argparse.Action): def __call__(self, parser, namespace, valu...
The 'append' action makes more sense with an optional: ``` parser.add_argument('-i', '--input',action='append') parser.parse_args(['-i','fileone', '-a', '-i','filetwo', '-b', '-i','filethree']) ``` You can interleave optionals with separate positionals ('input1 -a input2 -b input3'), but you cannot interleave option...
5,373,474
I'm trying to use argparse to parse the command line arguments for a program I'm working on. Essentially, I need to support multiple positional arguments spread within the optional arguments, but cannot get argparse to work in this situation. In the actual program, I'm using a custom action (I need to store a snapshot ...
2011/03/21
[ "https://Stackoverflow.com/questions/5373474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/668807/" ]
srgerg was right about the definition of positional arguments. In order to get the result you want, You have to accept them as optional arguments, and modify the resulted namespace according to your need. You can use a custom action: ``` class MyAction(argparse.Action): def __call__(self, parser, namespace, valu...
It seems to me that hpaulj is on the right track but making things a bit more complicated than necessary. I suspect that Blair is looking for something akin to the behavior of the old optparse module and doesn't really need the list of input arguments in the inputs field of the args object. He just wants ``` import ar...
5,373,474
I'm trying to use argparse to parse the command line arguments for a program I'm working on. Essentially, I need to support multiple positional arguments spread within the optional arguments, but cannot get argparse to work in this situation. In the actual program, I'm using a custom action (I need to store a snapshot ...
2011/03/21
[ "https://Stackoverflow.com/questions/5373474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/668807/" ]
The 'append' action makes more sense with an optional: ``` parser.add_argument('-i', '--input',action='append') parser.parse_args(['-i','fileone', '-a', '-i','filetwo', '-b', '-i','filethree']) ``` You can interleave optionals with separate positionals ('input1 -a input2 -b input3'), but you cannot interleave option...
It seems to me that hpaulj is on the right track but making things a bit more complicated than necessary. I suspect that Blair is looking for something akin to the behavior of the old optparse module and doesn't really need the list of input arguments in the inputs field of the args object. He just wants ``` import ar...
2,604,917
I'm trying to make a program so that I can run it through the command line with the following format: ``` ./myProgram ``` I made it executable and put `#!/usr/bin/env python` in the header, but it's giving me the following error. ``` env: python\r: No such file or directory ``` However, when I run "python myProg...
2010/04/09
[ "https://Stackoverflow.com/questions/2604917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305105/" ]
Your line endings are wrong. Use `dos2unix` to fix them.
`dos2unix filename.py` or inside vim issue the command `:set fileformat=unix` and save.
2,604,917
I'm trying to make a program so that I can run it through the command line with the following format: ``` ./myProgram ``` I made it executable and put `#!/usr/bin/env python` in the header, but it's giving me the following error. ``` env: python\r: No such file or directory ``` However, when I run "python myProg...
2010/04/09
[ "https://Stackoverflow.com/questions/2604917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305105/" ]
Your line endings are wrong. Use `dos2unix` to fix them.
+1 on ignacio's suggestion. however, to answer the 1st part of your question more directly, each OS/system uses a different line termination character: POSIX (any Unix-flavor like Linux, \*BSD, Mac OS X, etc.) uses **`\n`** (NEWLINE) while DOS/Win uses the combo **`\r\n`** (CR/carriage return + NEWLINE) and old Mac O...
2,604,917
I'm trying to make a program so that I can run it through the command line with the following format: ``` ./myProgram ``` I made it executable and put `#!/usr/bin/env python` in the header, but it's giving me the following error. ``` env: python\r: No such file or directory ``` However, when I run "python myProg...
2010/04/09
[ "https://Stackoverflow.com/questions/2604917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305105/" ]
+1 on ignacio's suggestion. however, to answer the 1st part of your question more directly, each OS/system uses a different line termination character: POSIX (any Unix-flavor like Linux, \*BSD, Mac OS X, etc.) uses **`\n`** (NEWLINE) while DOS/Win uses the combo **`\r\n`** (CR/carriage return + NEWLINE) and old Mac O...
`dos2unix filename.py` or inside vim issue the command `:set fileformat=unix` and save.
16,903,416
I've used: ``` data = DataReader("yhoo", "yahoo", datetime.datetime(2000, 1, 1), datetime.datetime.today()) ``` in pandas (python) to get history data of yahoo, but it cannot show today's price (the market has not yet closed) how can I resolve such problem, thanks in advance.
2013/06/03
[ "https://Stackoverflow.com/questions/16903416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857130/" ]
``` import pandas import pandas.io.data import datetime import urllib2 import csv YAHOO_TODAY="http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sd1ohgl1vl1" def get_quote_today(symbol): response = urllib2.urlopen(YAHOO_TODAY % symbol) reader = csv.reader(response, delimiter=",", quotechar='"') for ro...
The simplest way to extract Indian stock price data into Python is to use the nsepy library. In case you do not have the nsepy library do the following: ``` pip install nsepy ``` The following code allows you to extract HDFC stock price for 10 years. ``` from nsepy import get_history from datetime import date dfc=...
16,903,416
I've used: ``` data = DataReader("yhoo", "yahoo", datetime.datetime(2000, 1, 1), datetime.datetime.today()) ``` in pandas (python) to get history data of yahoo, but it cannot show today's price (the market has not yet closed) how can I resolve such problem, thanks in advance.
2013/06/03
[ "https://Stackoverflow.com/questions/16903416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857130/" ]
Find a way to work around, just use urllib to fetch the data with: ``` http://download.finance.yahoo.com/d/quotes.csv?s=yhoo&f=sd1ohgl1l1v ``` then add it to dataframe
The simplest way to extract Indian stock price data into Python is to use the nsepy library. In case you do not have the nsepy library do the following: ``` pip install nsepy ``` The following code allows you to extract HDFC stock price for 10 years. ``` from nsepy import get_history from datetime import date dfc=...
16,903,416
I've used: ``` data = DataReader("yhoo", "yahoo", datetime.datetime(2000, 1, 1), datetime.datetime.today()) ``` in pandas (python) to get history data of yahoo, but it cannot show today's price (the market has not yet closed) how can I resolve such problem, thanks in advance.
2013/06/03
[ "https://Stackoverflow.com/questions/16903416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857130/" ]
So from trying this out and looking at the dataframe, it doesn't look too possible. You tell it to go from a specific day until today, yet the dataframe stops at may 31st 2013. This tells me that yahoo probably has not made it available for you to use in the past couple days or somehow pandas is just not picking it up....
The module from pandas doesn't work anymore, because the google and yahoo doens't provide support anymore. So you can create a function to take the data direct from the Google Finance using the url. Here is a part of a code to do this ``` import csv import datetime import re import codecs import requests import pandas...
16,903,416
I've used: ``` data = DataReader("yhoo", "yahoo", datetime.datetime(2000, 1, 1), datetime.datetime.today()) ``` in pandas (python) to get history data of yahoo, but it cannot show today's price (the market has not yet closed) how can I resolve such problem, thanks in advance.
2013/06/03
[ "https://Stackoverflow.com/questions/16903416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857130/" ]
``` import pandas import pandas.io.data import datetime import urllib2 import csv YAHOO_TODAY="http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sd1ohgl1vl1" def get_quote_today(symbol): response = urllib2.urlopen(YAHOO_TODAY % symbol) reader = csv.reader(response, delimiter=",", quotechar='"') for ro...
Find a way to work around, just use urllib to fetch the data with: ``` http://download.finance.yahoo.com/d/quotes.csv?s=yhoo&f=sd1ohgl1l1v ``` then add it to dataframe
16,903,416
I've used: ``` data = DataReader("yhoo", "yahoo", datetime.datetime(2000, 1, 1), datetime.datetime.today()) ``` in pandas (python) to get history data of yahoo, but it cannot show today's price (the market has not yet closed) how can I resolve such problem, thanks in advance.
2013/06/03
[ "https://Stackoverflow.com/questions/16903416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857130/" ]
Find a way to work around, just use urllib to fetch the data with: ``` http://download.finance.yahoo.com/d/quotes.csv?s=yhoo&f=sd1ohgl1l1v ``` then add it to dataframe
So from trying this out and looking at the dataframe, it doesn't look too possible. You tell it to go from a specific day until today, yet the dataframe stops at may 31st 2013. This tells me that yahoo probably has not made it available for you to use in the past couple days or somehow pandas is just not picking it up....
16,903,416
I've used: ``` data = DataReader("yhoo", "yahoo", datetime.datetime(2000, 1, 1), datetime.datetime.today()) ``` in pandas (python) to get history data of yahoo, but it cannot show today's price (the market has not yet closed) how can I resolve such problem, thanks in advance.
2013/06/03
[ "https://Stackoverflow.com/questions/16903416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857130/" ]
This code uses the pandas read\_csv method to get the new quote from yahoo, and it checks if the new quote is an update from the current date or a new date in order to update the last record in history or append a new record. If you add a while(true) loop and a sleep around the new\_quote section, you can have the cod...
The module from pandas doesn't work anymore, because the google and yahoo doens't provide support anymore. So you can create a function to take the data direct from the Google Finance using the url. Here is a part of a code to do this ``` import csv import datetime import re import codecs import requests import pandas...
16,903,416
I've used: ``` data = DataReader("yhoo", "yahoo", datetime.datetime(2000, 1, 1), datetime.datetime.today()) ``` in pandas (python) to get history data of yahoo, but it cannot show today's price (the market has not yet closed) how can I resolve such problem, thanks in advance.
2013/06/03
[ "https://Stackoverflow.com/questions/16903416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857130/" ]
This code uses the pandas read\_csv method to get the new quote from yahoo, and it checks if the new quote is an update from the current date or a new date in order to update the last record in history or append a new record. If you add a while(true) loop and a sleep around the new\_quote section, you can have the cod...
So from trying this out and looking at the dataframe, it doesn't look too possible. You tell it to go from a specific day until today, yet the dataframe stops at may 31st 2013. This tells me that yahoo probably has not made it available for you to use in the past couple days or somehow pandas is just not picking it up....
16,903,416
I've used: ``` data = DataReader("yhoo", "yahoo", datetime.datetime(2000, 1, 1), datetime.datetime.today()) ``` in pandas (python) to get history data of yahoo, but it cannot show today's price (the market has not yet closed) how can I resolve such problem, thanks in advance.
2013/06/03
[ "https://Stackoverflow.com/questions/16903416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857130/" ]
``` import pandas import pandas.io.data import datetime import urllib2 import csv YAHOO_TODAY="http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sd1ohgl1vl1" def get_quote_today(symbol): response = urllib2.urlopen(YAHOO_TODAY % symbol) reader = csv.reader(response, delimiter=",", quotechar='"') for ro...
The module from pandas doesn't work anymore, because the google and yahoo doens't provide support anymore. So you can create a function to take the data direct from the Google Finance using the url. Here is a part of a code to do this ``` import csv import datetime import re import codecs import requests import pandas...
16,903,416
I've used: ``` data = DataReader("yhoo", "yahoo", datetime.datetime(2000, 1, 1), datetime.datetime.today()) ``` in pandas (python) to get history data of yahoo, but it cannot show today's price (the market has not yet closed) how can I resolve such problem, thanks in advance.
2013/06/03
[ "https://Stackoverflow.com/questions/16903416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857130/" ]
``` import pandas import pandas.io.data import datetime import urllib2 import csv YAHOO_TODAY="http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sd1ohgl1vl1" def get_quote_today(symbol): response = urllib2.urlopen(YAHOO_TODAY % symbol) reader = csv.reader(response, delimiter=",", quotechar='"') for ro...
So from trying this out and looking at the dataframe, it doesn't look too possible. You tell it to go from a specific day until today, yet the dataframe stops at may 31st 2013. This tells me that yahoo probably has not made it available for you to use in the past couple days or somehow pandas is just not picking it up....
16,903,416
I've used: ``` data = DataReader("yhoo", "yahoo", datetime.datetime(2000, 1, 1), datetime.datetime.today()) ``` in pandas (python) to get history data of yahoo, but it cannot show today's price (the market has not yet closed) how can I resolve such problem, thanks in advance.
2013/06/03
[ "https://Stackoverflow.com/questions/16903416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857130/" ]
So from trying this out and looking at the dataframe, it doesn't look too possible. You tell it to go from a specific day until today, yet the dataframe stops at may 31st 2013. This tells me that yahoo probably has not made it available for you to use in the past couple days or somehow pandas is just not picking it up....
The simplest way to extract Indian stock price data into Python is to use the nsepy library. In case you do not have the nsepy library do the following: ``` pip install nsepy ``` The following code allows you to extract HDFC stock price for 10 years. ``` from nsepy import get_history from datetime import date dfc=...
2,040,616
When I run my python script I get the following warning ``` DeprecationWarning: the sets module is deprecated ``` How do I fix this?
2010/01/11
[ "https://Stackoverflow.com/questions/2040616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247873/" ]
Stop using the `sets` module, or switch to an older version of python where it's not deprecated. According to [pep-004](http://www.python.org/dev/peps/pep-0004/), `sets` is deprecated as of v2.6, replaced by the built-in [`set` and `frozenset` types](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset...
You don't need to import the `sets` module to use them, they're in the builtin namespace.
2,040,616
When I run my python script I get the following warning ``` DeprecationWarning: the sets module is deprecated ``` How do I fix this?
2010/01/11
[ "https://Stackoverflow.com/questions/2040616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247873/" ]
History: Before Python 2.3: no set functionality Python 2.3: `sets` module arrived Python 2.4: `set` and `frozenset` built-ins introduced Python 2.6: `sets` module deprecated You should change your code to use `set` instead of `sets.Set`. If you still wish to be able to support using Python 2.3, you can do...
You don't need to import the `sets` module to use them, they're in the builtin namespace.
2,040,616
When I run my python script I get the following warning ``` DeprecationWarning: the sets module is deprecated ``` How do I fix this?
2010/01/11
[ "https://Stackoverflow.com/questions/2040616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247873/" ]
If you want to fix it James definitely has the right answer, but in case you want to just turn off deprecation warnings, you can run python like so: ``` $ python -Wignore::DeprecationWarning Python 2.6.2 (r262:71600, Sep 20 2009, 20:47:22) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "cred...
You don't need to import the `sets` module to use them, they're in the builtin namespace.
2,040,616
When I run my python script I get the following warning ``` DeprecationWarning: the sets module is deprecated ``` How do I fix this?
2010/01/11
[ "https://Stackoverflow.com/questions/2040616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247873/" ]
Stop using the `sets` module, or switch to an older version of python where it's not deprecated. According to [pep-004](http://www.python.org/dev/peps/pep-0004/), `sets` is deprecated as of v2.6, replaced by the built-in [`set` and `frozenset` types](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset...
Use the built-in `set` instead of importing and using `sets` module. From [documentation](http://docs.python.org/whatsnew/2.6.html): > > The sets module has been deprecated; > it’s better to use the built-in set > and frozenset types. > > >
2,040,616
When I run my python script I get the following warning ``` DeprecationWarning: the sets module is deprecated ``` How do I fix this?
2010/01/11
[ "https://Stackoverflow.com/questions/2040616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247873/" ]
Stop using the `sets` module, or switch to an older version of python where it's not deprecated. According to [pep-004](http://www.python.org/dev/peps/pep-0004/), `sets` is deprecated as of v2.6, replaced by the built-in [`set` and `frozenset` types](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset...
History: Before Python 2.3: no set functionality Python 2.3: `sets` module arrived Python 2.4: `set` and `frozenset` built-ins introduced Python 2.6: `sets` module deprecated You should change your code to use `set` instead of `sets.Set`. If you still wish to be able to support using Python 2.3, you can do...
2,040,616
When I run my python script I get the following warning ``` DeprecationWarning: the sets module is deprecated ``` How do I fix this?
2010/01/11
[ "https://Stackoverflow.com/questions/2040616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247873/" ]
Stop using the `sets` module, or switch to an older version of python where it's not deprecated. According to [pep-004](http://www.python.org/dev/peps/pep-0004/), `sets` is deprecated as of v2.6, replaced by the built-in [`set` and `frozenset` types](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset...
If you want to fix it James definitely has the right answer, but in case you want to just turn off deprecation warnings, you can run python like so: ``` $ python -Wignore::DeprecationWarning Python 2.6.2 (r262:71600, Sep 20 2009, 20:47:22) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "cred...
2,040,616
When I run my python script I get the following warning ``` DeprecationWarning: the sets module is deprecated ``` How do I fix this?
2010/01/11
[ "https://Stackoverflow.com/questions/2040616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247873/" ]
History: Before Python 2.3: no set functionality Python 2.3: `sets` module arrived Python 2.4: `set` and `frozenset` built-ins introduced Python 2.6: `sets` module deprecated You should change your code to use `set` instead of `sets.Set`. If you still wish to be able to support using Python 2.3, you can do...
Use the built-in `set` instead of importing and using `sets` module. From [documentation](http://docs.python.org/whatsnew/2.6.html): > > The sets module has been deprecated; > it’s better to use the built-in set > and frozenset types. > > >