qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
29
22k
response_k
stringlengths
26
13.4k
__index_level_0__
int64
0
17.8k
23,785,259
I'm new using Python 3.4 and I'll be using it for my internship in the next month. However, my instructor gave me a task to practice while I haven't started it yet. Thus, he gave me a set of data and he asked me to figure how to load this out. However, it keep showing me this: ``` Traceback (most recent call last): ...
2014/05/21
[ "https://Stackoverflow.com/questions/23785259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3661013/" ]
On the SelectionChanged event you can do this: ``` private void dataGridView1_SelectionChanged(object sender, EventArgs e) { if (dataGridView1.SelectedCells.Count > 2) { dataGridView1.SelectedCells[0].Selected = false; } } ``` This will prevent/undo selecting any more cells after selecting two. Fo...
You could try overriding SetSelectedRowCore, calling the base with adding your new limitation to the selected condition. ``` protected virtual void SetSelectedRowCore(int rowIndex,bool selected ) { base(rowIndex, selected && currentSelection < allowedSelectionCount); } ``` [SetSelectedRowCore](http://msdn.micr...
5,926
38,994,265
When we input : 10 output :01 02 03 04 05 06 07 08 09 10 When we input :103 output :001 002 003...010 011 012 013.....100 101 002 103 How to create this sequence in ruby or python ?
2016/08/17
[ "https://Stackoverflow.com/questions/38994265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Ruby implementation: ``` n = gets p (1..n.to_i).map{ |i| i.to_s.rjust(n.to_s.length, "0") }.join(" ") ``` Here `rjust` will add leading zeros.
A very basic Python implementation. Note that it's a generator so it returns one value at a time. ``` def get_range(n): len_n = len(str(n)) for num in range(1, n + 1): output = str(num) while len(output) < len_n: output = '0' + output yield output for i in get_range(100): ...
5,928
51,325,955
I am trying to scrape a website using `Selenium Firefox` (headless) driver in `python`. I read all the anchors in the webpage and go through them all one by one. But I want for the browser to wait for the `Ajax` calls on the page to be over before moving to another page. My code is the following: ``` import time fr...
2018/07/13
[ "https://Stackoverflow.com/questions/51325955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2378622/" ]
You should add a `0` in your conversion specification to indicate that you want zero-padding: ``` $test = sprintf('%06d', rand(1, 1000000)); // ^-- here ``` The conversion specifications are documented on [the `sprintf` manual page](http://php.net/manual/en/function.sprintf.php).
You can just replace the empty character with 0. ``` $test = str_replace(" ", "0", sprintf('%6d', rand(1, 1000000))); ```
5,933
39,948,588
How can I read the contents of a binary or a text file in a non-blocking mode? For binary files: when I `open(filename, mode='rb')`, I get an instance of `io.BufferedReader`. The documentation fort `io.BufferedReader.read` [says](https://docs.python.org/3.5/library/io.html#io.BufferedReader.read): > > Read and retur...
2016/10/09
[ "https://Stackoverflow.com/questions/39948588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336527/" ]
File operations are blocking. There is no non-blocking mode. But you can create a thread which reads the file in the background. In Python 3, [`concurrent.futures` module](https://docs.python.org/3.4/library/concurrent.futures.html#module-concurrent.futures) can be useful here. ``` from concurrent.futures import Thre...
I suggest using [**aiofiles**](https://github.com/Tinche/aiofiles) - a library for handling local disk files in asyncio applications. ``` import aiofiles async def read_without_blocking(): f = await aiofiles.open('filename', mode='r') try: contents = await f.read() finally: await f.close()...
5,935
48,146,921
I have a script that builds llvm/clang 3.42 from source (with configure+make). **It runs smooth on ubuntu 14.04.5 LTS**. When I upgraded to **ubuntu 17.04**, the build fails. Here is the building script: ``` svn co https://llvm.org/svn/llvm-project/llvm/tags/RELEASE_342/final llvm svn co https://llvm.org/svn/llvm-pro...
2018/01/08
[ "https://Stackoverflow.com/questions/48146921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3357352/" ]
That seems to be an issue with LLVM 3.4.2`tsan` (Thread Sanitizer) failing to build with GCC 6.x, as previously reported here: <https://aur.archlinux.org/packages/clang34-analyzer-split> It seems the inclusion of `stdlib.h` and `malloc.h` is conflicting, since both define `malloc` and friends. It's possible that thi...
I faced the same problem on my Ubuntu 16.10. It has default gcc 6.2. You need to instruct LLVM build system to use gcc 4.9. Also, I suggest you remove GCC6 completely. ``` $ sudo apt-get remove g++-6 gcc-6 cpp $ sudo apt-get install gcc-4.9 g++4.9 $ export CC=/usr/bin/gcc-4.9 $ export CXX=/usr/bin/g++-4.9 $ export CPP...
5,937
35,245,401
I work with conda environments and need some pip packages as well, e.g. pre-compiled wheels from [~gohlke](http://www.lfd.uci.edu/~gohlke/pythonlibs/). At the moment I have two files: `environment.yml` for conda with: ``` # run: conda env create --file environment.yml name: test-env dependencies: - python>=3.5 - anac...
2016/02/06
[ "https://Stackoverflow.com/questions/35245401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5276734/" ]
Pip dependencies can be included in the `environment.yml` file like this ([docs](https://conda.io/docs/user-guide/tasks/manage-environments.html#create-env-file-manually)): ``` # run: conda env create --file environment.yml name: test-env dependencies: - python>=3.5 - anaconda - pip - numpy=1.13.3 # pin version for c...
Just want to add that adding a wheel in the directory also works. I was getting this error when using the entire URL: ``` HTTP error 404 while getting http://www.lfd.uci.edu/~gohlke/pythonlibs/f9r7rmd8/opencv_python-3.1.0-cp35-none-win_amd64.whl ``` Ended up downloading the wheel and saving it into the same directo...
5,938
55,746,170
I am trying to implement a neural network for an NLP task with a convolutional layer followed up by an LSTM layer. I am currently experimenting with the new Tensorflow 2.0 to do this. However, when building the model, I've encountered an error that I could not understand. ``` # Input shape of training and validation s...
2019/04/18
[ "https://Stackoverflow.com/questions/55746170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7274157/" ]
The issue is a dimensionality issue. Your feature is of shape `[..., 1, 512]`; therefore, `MaxPooling1D` `pooling_size` 2 is bigger than 1 causing the issue. Adding `padding="same"` will solve the issue. ``` model = tf.keras.Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(None, 512))) model.add(tf.ker...
**padding="same"** should solve your issue. Change below line: `model.add(tf.keras.layers.MaxPooling1D(2, padding="same"))`
5,944
23,793,774
``` omnia@ubuntu:~$ psql --version psql (PostgreSQL) 9.3.4 omnia@ubuntu:~$ pg_dump --version pg_dump (PostgreSQL) 9.2.8 omnia@ubuntu:~$ dpkg -l | grep pg ii gnupg 1.4.11-3ubuntu2.5 GNU privacy guard - a free PGP replacement ii gpgv 1.4.11-3ubuntu2...
2014/05/21
[ "https://Stackoverflow.com/questions/23793774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7595/" ]
``` sudo rm /usr/bin/pg_dump sudo ln -s /usr/lib/postgresql/9.3/bin/pg_dump /usr/bin/pg_dump ```
The `pgdg60` package suffix leads me to believe these packages are not from the official Ubuntu repository. Try looking into `/etc/apt/sources.list` or `/etc/apt/sources.list.d` and see if you have any third party PPA's or repositories specified. Try getting the Postgresql packages either from your Ubuntu repo (althou...
5,945
64,808,992
I am stuck with code below. Either I cannot find simple answer to my problem due to not narrow enough search or I am just too blind to see. Anyway I am looking to put the "+" and "-" buttons to use. They suppose to literally do what their assigned symbols do. With my level of python knowledge I can only achieve that by...
2020/11/12
[ "https://Stackoverflow.com/questions/64808992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11618118/" ]
Currently, there is one solution **Real-World Super-Resolution via Kernel Estimation and Noise Injection**. The author proposes a degradation framework RealSR, which provides realistic images for super-resolution learning. It is a promising method for shakiness or motion effect images super-resolution. The method is d...
I've also been working on this super-resolution field and found some promising results but haven't tried yet, [first paper](https://doi.org/10.1016/j.heliyon.2021.e08341) (license plate base text) they implement the image enhancement first then do the super-resolution in a later stage. [second paper](https://arxiv.org/...
5,948
69,280,273
So, I have a list of dicts in python that looks like this: ``` lis = [ {'action': 'Notify', 'type': 'Something', 'Genre': 10, 'date': '2021-05-07 01:59:37'}, {'action': 'Notify', 'type': 'Something Else', 'Genre': 20, 'date': '2021-05-07 01:59:37'} ... ] ``` Now I want `lis` to be in a way, such that **each individu...
2021/09/22
[ "https://Stackoverflow.com/questions/69280273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11903403/" ]
You might harness [`collections.OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict) for this task as follows ``` import collections order = ['date', 'Genre', 'action', 'type'] dct1 = {'action': 'Notify', 'type': 'Something', 'Genre': 10, 'date': '2021-05-07 01:59:37'} dct2 = {'act...
Try this: ``` def sort_dct(li, mapping): return {v: li[v] for k,v in mapping.items()} out = [] mapping = {1:'date', 2:'Genre', 3:'action', 4:'type'} for li in lis: out.append(sort_dct(li,mapping)) print(out) ``` Output: ``` [{'date': '2021-05-07 01:59:37', 'Genre': 10, 'action': 'Notify', 'type': 'S...
5,949
36,534,186
I'm having this problem with a python script I'm writing that calls an exe file (subrocess.Popen). I'm redirecting the stdout and stderr to PIPE, but i cant read (subprocess.Popen.stdout.readline()) any output. I did try to run the exec file in windows cli and redirecting both stdout and stderr... and nothing happens....
2016/04/10
[ "https://Stackoverflow.com/questions/36534186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6185152/" ]
Does this work? Set the alpha of the extra lines to 0 (so they become transparent. Using geom\_line as geom\_density uses alpha for fill only. (system problems prevent testing) ``` ggplotly( ggplot(diamonds, aes(depth, colour = cut)) + geom_density() + geom_line(aes(text = paste("Clarity: ", clarity)), stat=...
I realize that this is an old answer, but the main problem here is that you're trying to do something that's logically impossible. `clarity` and `cut` are two separate dimensions, so you can't simply put the `clarity` in a tooltip on the line that's grouped by `cut`, because that line represents diamonds of all differ...
5,951
54,900,964
Hi I have a question with regards to python programming for my assignment The task is to replace the occurrence of a number in a given value in a recursive manner, and the final output must be in integer i.e. digit\_swap(521, 1, 3) --> 523 where 1 is swapped out for 3 Below is my code and it works well for s = 0 - 9...
2019/02/27
[ "https://Stackoverflow.com/questions/54900964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9369481/" ]
Conversion to string is unnecessary, this can be implemented much easier ``` def digit_swap(n, d, s): if n == 0: return 0 lower_n = (s if (n % 10) == d else (n % 10)) higher_n = digit_swap(n // 10, d, s) * 10 return higher_n + lower_n assert digit_swap(521, 1, 3) == 523 assert digit_swap(65132, 1...
For example `int(00)` is casted to 0. Therefore a zero is discarded. I suggest not to cast, instead leave it as a string. If you have to give back an `int`, you should not cast until you return the number. However, you still discard 0s at the beginning. So all in all, I would suggest just return strings instead of ints...
5,952
13,083,026
Imagine I have a script, let's say `my_tools.py` that I import as a module. But `my_tools.py` is saved twice: at `C:\Python27\Lib` and at the same directory from where the script is run that does the import. Can I change the order where python looks for `my_tools.py` first? That is, to check first if it exists at `C...
2012/10/26
[ "https://Stackoverflow.com/questions/13083026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105929/" ]
You can manipulate `sys.path` as much as you want... If you wanted to move the current directory to be scanned last, then just do `sys.path[1:] + sys.path[:1]`. Otherwise, if you want to get into the nitty gritty then the [imp module](http://docs.python.org/library/imp.html) can be used to customise until your hearts c...
You can modify [`sys.path`](http://docs.python.org/library/sys.html#sys.path), which will determine the order and locations that Python searches for imports. (Note that you must do this *before* the import statement.)
5,954
46,092,292
I would like to split strings like the following: ``` x <- "abc-1230-xyz-[def-ghu-jkl---]-[adsasa7asda12]-s-[klas-bst-asdas foo]" ``` by dash (`-`) on the condition that those dashes must not be contained inside a pair of `[]`. The expected result would be ``` c("abc", "1230", "xyz", "[def-ghu-jkl---]", "[adsasa7as...
2017/09/07
[ "https://Stackoverflow.com/questions/46092292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3521006/" ]
You could use look ahead to verify that there is no `]` following sooner than a `[`: [`-(?![^[]*\])`](https://regex101.com/r/x0WbVt/2) So in R: ``` strsplit(x, "-(?![^[]*\\])", perl=TRUE) ``` ### Explanation: * `-`: match the hyphen * `(?! )`: negative look ahead: if that part is found after the previously matche...
I am not familiar with `r` language, but I believe it can do regex based search and replace. Instead of struggling with one single regex split function, I would go in 3 steps: * replace `-` in all `[....]` parts by a invisible char, like `\x99` * split by `-` * for each element in the above split result(array/list), r...
5,956
57,398,668
I don't have o picture but I am asking did question because I am a beginner using python
2019/08/07
[ "https://Stackoverflow.com/questions/57398668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11897155/" ]
`input()` takes user input as a string. It's very safe. ``` >>> usr = input('Enter some input: ') Enter some input: hello, world >>> usr "hello, world" ``` `eval()` will execute a string as if it were python code. It's very dangerous. ``` >>>eval(input('Make it happen!')) Make it happen! print('hello') hello >>>eva...
`eval()` is used to evaluate an expression and `input()` is used to take user input. Here are the examples: ``` #evaluates expression >> eval('5+2') >> 7 # Takes user input >> input() 10 (user enters) >> 10 #evaluates user input >> eval('input()') 15 (user enters) >> 15 ```
5,959
37,776,724
I've just completed [Tatiana Tylosky's tutorial for Python](https://www.thinkful.com/learn/intro-to-python-tutorial/#Creating-Your-Pypet) and created my own Python pypet. In her tutorial, she shows how to do a "for" loop consisting of: ``` cat = { 'name': 'Fluffy', 'hungry': True, 'weight': 9.5, 'age'...
2016/06/12
[ "https://Stackoverflow.com/questions/37776724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6456667/" ]
I would enclose your feed `for` loop in a `for` loop that iterates three times. I would use something like: ``` for _ in range(3): for pet in pets: feed(pet) print pet ``` `for _ in range(3)` iterates three times. Note that I used `_` because you are not using the iteration variable, see e.g. [Wh...
Programming languages let you embed one structure in another. Put your current loop under a for loop that runs three times, as @intboolstring's answer already showed. Here are two more things you should do now: 1. Don't compare against `True`. `if pet["Hungry"] == True:` is better written as ``` if pet["Hungry"]: ...
5,960
59,391,988
I am trying to set up dockerized production environment for Flask application with gunicorn. I follow this [Digital Ocean's](https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04) instructions together with [testdriven's one](https://testdriven.io/blog/...
2019/12/18
[ "https://Stackoverflow.com/questions/59391988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4765864/" ]
1. Close `Visual Studio`. 2. Delete the `*.testlog` files in: *solutionfolder*\.vs\*solution name*\v16\TestStore\*number*.
I faced the same issue right now. A cleanup helped. As I had cleanup issues with VS in the last time (some DB-lock prevents a real cleanup to happen), my working cleanup was this way: 1. Close VS. 2. Git Bash in solution folder: `git clean -xfd` Probably it helps.
5,962
52,305,075
Per [Google's Cloud Datastore Emulator installation instructions](https://cloud.google.com/datastore/docs/tools/datastore-emulator), I was able to install and run the emulator in a *bash* terminal window without problem with `gcloud beta emulators datastore start --project gramm-id`. I also setup the environment varia...
2018/09/13
[ "https://Stackoverflow.com/questions/52305075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1181911/" ]
> > gcloud auth application-default login > > > This will prompt you to login through a browser window and will set your GOOGLE\_APPLICATION\_CREDENTIALS correctly for you. [[1]](https://cloud.google.com/docs/authentication/production#calling)
In theory you should be able to use mock credentials, e.g.: ``` class EmulatorCreds(google.auth.credentials.Credentials): def __init__(self): self.token = b'secret' self.expiry = None @property def valid(self): return True def refresh(self, _): raise RuntimeError('Sho...
5,971
42,068,203
I am learning to use scrapinghub.com which runs in python 2.x I have written a script which uses Scrapy, I have crawled a string like below: ``` %3Ctable%20width%3D%22100%25%22%3E%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3Ctr%3E%3Ctd%3E%3Cp%20style%3D%22colo...
2017/02/06
[ "https://Stackoverflow.com/questions/42068203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/339229/" ]
Your data is perfectly valid UTF-8, encoded into a URL (so URLEncoded). Your output indicates you are looking at a [Mojibake](https://en.wikipedia.org/wiki/Mojibake), where your own software (console, terminal, text editor), is using a *different* codec to interpret the UTF-8 data. I suspect your setup is using CP-1254...
I don't know why, but for some reason I get it to work on scrapinghub.com like below. Let say I have an HTML text like: ``` <html> <div class="a"> Some chinese text </div> <div class="b"> QUOTED text got chinese in it %3Ctable%20width%3D%22100%25%22%3E%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20...
5,972
9,851,156
I am managing a quite large python code base (>2000 lines) that I want anyway to be available as a single runnable python script. So I am searching for a method or a tool to merge a development folder, made of different python files into a single running script. The thing/method I am searching for should take code sp...
2012/03/24
[ "https://Stackoverflow.com/questions/9851156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/749014/" ]
It sounds like you're asking how to merge your codebase into a single 2000-plus source file-- are you really, really sure you want to do this? It will make your code harder to maintain. Python files correspond to modules, so unless your main script does `from modname import *` for all its parts, you'll lose the module ...
[waffles](https://bitbucket.org/ArneBab/waffles) seems to do exactly what you're after, although I've not tried it You could probably do this manually, something like: ``` # file1.py from .file2 import func1, func2 def something(): func1() + func2() # file2.py def func1(): pass def func2(): pass # __init__.py f...
5,973
61,452,787
I cannot install Django 3 on my Debian 9 system. I follow <https://www.rosehosting.com/blog/how-to-install-python-3-6-4-on-debian-9/> this guide to install a Python 3 because there is no Python 3 in Debian repositories: ```sh :~# python3 Python 3.5.3 (default, Sep 27 2018, 17:25:39) ``` ```sh ~# pip3 -V pip 9.0.1 f...
2020/04/27
[ "https://Stackoverflow.com/questions/61452787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4003516/" ]
For the latest versions of Django you must be using python 3.6, 3.7, or 3.8. You're currently using 3.5 <https://docs.djangoproject.com/en/3.0/faq/install/#faq-python-version-support>
install python3-venv by command: ``` sudo apt install python3-venv ``` and ``` mkdir my_django_app cd my_django_app; python3 -m venv venv ``` ref: <https://linuxize.com/post/how-to-install-django-on-debian-9>
5,974
39,849,641
I am using `flask migrate` to for database creation & migration in flask with flask-sqlalchemy. Everything was working fine until I changed my database user password contains '@' then it stopped working so, I updated my code based on [Writing a connection string when password contains special characters](https://stac...
2016/10/04
[ "https://Stackoverflow.com/questions/39849641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/873416/" ]
I have a solution for this issue after experiencing it as well. There's an issue with '%' (percent signs) in the db connection URI after you urlencode the string. I tried substituting the percent sign with double percent signs ('%%') which gets me past the interpolation error. However, that resulted in not being able...
You may want to look at <http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#mysql-unicode> I was having the same issue with my password and the mysql connector. using the mysql+pymysql connector allowed me to connect in application and in migration scripts.
5,975
36,329,606
This was the example picked from bokeh documentation. It is showing attribute error. I am using ipython in anaconda environment. ``` import pandas as pd from bokeh.charts import TimeSeries, output_file, show AAPL = pd.read_csv( "http://ichart.yahoo.com/table.csv?s=AAPL&a=0&b=1&c=2000&d=0&e=1&f=2010", ...
2016/03/31
[ "https://Stackoverflow.com/questions/36329606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6139075/" ]
Check which version you are using, If you are using 0.11.1 then you can use <http://docs.bokeh.org/en/0.11.1/docs/user_guide/plotting.html> for doing the same.
instead of using attribute index, set x = 'Date'. ``` p = TimeSeries(data, x ='Date', title="APPL", ylabel='Stock Prices') ```
5,978
55,648,776
In apache beam pipeline, I am taking input from cloud storage and trying to write it in biqguery table. But during the execution of pipeline getting this error. "AttributeError: 'module' object has no attribute 'storage'" ``` def run(argv=None): with open('gl_ledgers.json') as json_file: schema = json.load...
2019/04/12
[ "https://Stackoverflow.com/questions/55648776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11303943/" ]
This is probably related to `pipeline_options.view_as(SetupOptions).save_main_session = True`. Do you need that line? Try removing that and see if it fixes the problem. It is likely that one of your imports can not be pickled. Without imports I can't help you debug further. You could also try moving your imports into ...
Possibly a [duplicate](https://stackoverflow.com/questions/53860066/gitlab-ci-runner-cant-import-google-cloud-in-python), in which case the problem would be that `google-cloud-storage` needs to be installed, not `google-cloud`.
5,979
14,909,365
I Have planned to build an application with a server and multiple clients.When the clients connect to the server for the first time it must be given a id.Each time the client sends a request,the server sends the client a set of strings.the client then processes these strings and once it is done it again sends a request...
2013/02/16
[ "https://Stackoverflow.com/questions/14909365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2078134/" ]
Reason why your app is crashing because you are trying to deal with your GUI elements i.e `UIAlertView` in background thread, you need to run it on the main thread or try to use dispatch queues Using Dispatch Queues ``` dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); dispat...
Try to ``` - (IBAction)sendForm:(id)sender { [self performSelectorInBackground:@selector(loadData) withObject:activityIndicator]; [activityIndicator startAnimating]; UIAlertView* ahtung = [[UIAlertView alloc] initWithTitle:@"Спасибо" message:@"Ваша заявка принята!\nВ течение часа, Вам поступит звонок для подтвержд...
5,980
36,076,012
Say I have some class that manages a database connection. The user is supposed to call `close()` on instances of this class so that the db connection is terminated cleanly. Is there any way in python to get this object to call `close()` if the interpreter is closed or the object is otherwise picked up by the garbage c...
2016/03/18
[ "https://Stackoverflow.com/questions/36076012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1391717/" ]
The only way to ensure such a method is called if you don't trust users is using `__del__` ([docs](https://docs.python.org/2/reference/datamodel.html#object.__del__)). From the docs: > > Called when the instance is about to be destroyed. > > > Note that there are lots of issues that make using del tricky. For exa...
Define [`__enter__`](https://docs.python.org/2/reference/datamodel.html#object.__enter__) and [`__exit__`](https://docs.python.org/2/reference/datamodel.html#object.__exit__) methods on your class and then use it with the [`with` statement](https://docs.python.org/2/reference/compound_stmts.html#with): ``` with MyClas...
5,982
64,160,370
I am writhing a python script in order to communicate to my tello drone via wifi. Once connected with the drone I can send UDP packets to send commands (this works perfectly fine). I want to receive the video stream from the drone via UDP packets arriving at my udp server on port 11111. This is described in the SDK doc...
2020/10/01
[ "https://Stackoverflow.com/questions/64160370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13410369/" ]
Hi Those who are following murtaza workshop , and unable to get the video stream , Use Open CV library version 4.4.0.46, and python interpreter 3.9.0. Try to make sure you use the above specified versions.
I play with tello a lot recently. what I saw from you code is you have entered "command" by right the light should turn green. The once you "stream on" the should be a return message. Check this message to see if there is any error. The only apparent error is video source ID. You did what manually said. [![enter ima...
5,983
15,167,615
So basically my question relates to 'zip' (or izip), and this question which was asked before.... [Is there a better way to iterate over two lists, getting one element from each list for each iteration?](https://stackoverflow.com/questions/1919044/is-there-a-better-way-to-iterate-over-two-lists-getting-one-element-fro...
2013/03/01
[ "https://Stackoverflow.com/questions/15167615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448052/" ]
If you want to force broadcasting, you can use `numpy.lib.stride_tricks.broadcast_arrays`. Reusing your `cfun`: ``` def pyfun(a, b) : if not (np.isscalar(a) and np.isscalar(b)) : a_bcast, b_bcast = np.lib.stride_tricks.broadcast_arrays(a, b) return np.array([cfun(j, k) for j, k in zip(a_bcast, b_bc...
A decorator that optinally converts each of the arguments to a sequence might help. Here is the ordinary python (not numpy) version: ``` # TESTED def listify(f): def dolistify(*args): from collections import Iterable return f(*(a if isinstance(a, Iterable) else (a,) for a in args)) return dolistify @listi...
5,986
68,077,240
I have a python file that runs a machine learning algorithm that identifies circles in an image. From this python file, I am able to get all the coordinates (x and y) of every bounding box placed around the circles. I am appending all the coordinates into a local variable `xlist`/`ylist` (a list of all the integer valu...
2021/06/22
[ "https://Stackoverflow.com/questions/68077240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use the pickle library. It saves the data as its original data type only.
You can store them in a `.txt` file. **Try this** ``` file = open('xlistFile.txt', 'w') for item in xlist: file.write(str(item)) file.close() ``` You can do the same for ylist
5,989
74,060,609
Despite im used to program stuff, im new in Python so i decide to learn by myself. So, i install VS code and python. At the moment i tryied to use stuff like *tensorflow*, is showing an error saying that **my imports are missing**. I've already tryed to install everything again, search for a solution online and nothin...
2022/10/13
[ "https://Stackoverflow.com/questions/74060609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20234417/" ]
Whether there are **multiple versions of python** in your environment, which will make the pip installed in one version of python instead of the python you are using. Use shortcuts **"Ctrl+shift+P"** and type **"Python: Select Interpreter"** to choose the correct python. Then use `pip install packagename` to reinstall...
Confirm you have downloaded python correctly: * Open terminal * Run `python --version` + (if that doesn't work try `python3 --version`
5,991
73,269,344
I am new to python and I have a file that I am trying to read.. this file contains many lines and to determine when to stop reading the file I wrote this line: ``` while True: s=file.readline().strip() # this strip method cuts the '' character presents at the end # if we reach at the end of the file we'll b...
2022/08/07
[ "https://Stackoverflow.com/questions/73269344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19711709/" ]
The thing you are looking for is called "end of file" character or EOF [how to find out wether a file is at its eof](https://stackoverflow.com/questions/10140281/how-to-find-out-whether-a-file-is-at-its-eof)
You can iterate on the opened file ``` lines = [] with open("some-file.txt") as some_file: for line in some_file: lines.append(line) ```
5,992
35,360,863
I'm trying to code a python script that finds an unknown number with the least amount of tries possible. All I know is the number is < 10000 Everytime I make a wrong input I get an "error" response. When I find the right number I get a "success" response. Let's assume in this case the number is 124. How would you ...
2016/02/12
[ "https://Stackoverflow.com/questions/35360863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5647184/" ]
If the number being `< 10000` is *all* you know, you have to try all numbers between `1` and `9999` (inclusive). The binary search algorithm as suggested in the comments does not help since a miss does not tell you if you are too high or too low. ``` for i in range(1, 10000): if i == number_you_are_looking_for: ...
I believe the fastest way is to use binary search which gives the answer in O(log n). ``` def binary_search(n, min_value, max_value): tries = 0 found = False if max_value < min_value: print("Maximum value must be bigger than the minimum value") elif n < min_value or n > max_value: pri...
5,997
34,032,681
Hi I'm seriously stuck when trying to filter out my xml document. Here is some example of the contents: ``` <sentence id="1" document_id="Perseus:text:1999.02.0029" > <primary>millermo</primary> <word id="1" /> <word id="2" /> <word id="3" /> <word id="4" /> </sentence> <sentence id="2" document_i...
2015/12/02
[ "https://Stackoverflow.com/questions/34032681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5628041/" ]
A loop and `String.format` should give you what you need: ``` for (int i = 1; i <= 10; i++) { String bob = String.format("C:\\bob\\Myfile%02d.txt", Integer.valueOf(i)); // ... } ``` The format pattern `%02d` pads an integer with a zero given that it is less than two digits in length, as defined in the [synta...
If you want to walk through subdirectories you may also try: ``` try { Files.walk(Paths.get(directory)).filter(f -> Pattern.matches("myFile\\d{2}\\.txt", f.toFile().getName())).forEach(f -> { System.out.println("WHAT YOU WANT TO DO WITH f"); }); } catch (IOException e) { e.printStackTrace()...
5,998
49,627,914
I'm trying to execute a shell command through python. The command is like the following one: ``` su -c "lftp -c 'open -u user,password ftp://127.0.0.1; get ivan\'s\ filename.pdf' " someuser ``` So, when I try to do it in python: ``` command = "su -c \"lftp -c 'open -u user,password ftp://127.0.0.1; get ivan\'s\ f...
2018/04/03
[ "https://Stackoverflow.com/questions/49627914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8369505/" ]
If you printed your test string you would notice that it results in the following: ``` su -c "lftp -c 'open -u user,password ftp://127.0.0.1; get ivan's\ filename.pdf' " someuser ``` The problem is that you need to escape the slash that you use to escape the single quote in order to keep Python from eating it. ``` ...
Using subprocess.call() is the best and more secure way to perform this task. Here's an example from the [documentation page](https://docs.python.org/2/library/subprocess.html#subprocess.call): ``` subprocess.call(["ls", "-l"]) # As you can see we have here the command and a parameter ``` About the error I think it...
5,999
44,869,938
i have create an image processing python function. my system have 4 cores + 4 threads. i want to use multiprocessing to speed up my function,but anytime to use multiprocessing packages my function is not faster and is 1 minute slowly. any idea why ?first time use multiprocessing packages. main function : ``` if __n...
2017/07/02
[ "https://Stackoverflow.com/questions/44869938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5738116/" ]
`multiprocessing.Pool.map()` does not automatically make a function run in parallel. So doing `Pool.map(my_function(single_input))` will not make it run any faster. In fact, it may make it slower. The purpose of `map()` is to allow you to run the same function *multiple times* in parallel if you have *multiple inputs*...
You're executing the same function with the same parameters in a sub-process - this is bound to be slower as, at the very least, there is a system overhead of creating a new process, and then comes the Python's own overhead. It creates a whole new interpreter, stack, GIL... and that takes time. On POSIX systems this o...
6,000
45,179,302
Tornado has an open socket, and I can't seem to get it closed. I was really surprised as I've turned my computer on and off since the last time I ran this server a week ago, and terminal is not running. All in all, I thought this server was off for the past week. The things I've tried so far are the solution to this ...
2017/07/19
[ "https://Stackoverflow.com/questions/45179302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4808079/" ]
Interesting. Firstly, you should call `close()` method for `tornado.ioloop.IOLoop` **object**, not for **class object**. You can get current `tornado.ioloop.IOLoop` object using the method `tornado.ioloop.IOLoop.current()`. Example: ``` my_ioloop = tornado.ioloop.IOLoop.current() my_ioloop.close(all_fds=True) ``` ...
In my case, the issue was not with Tornado specifically, but with a process it started which continued even after it lost track of it. When I restarted my computer, OSX kept track of the process, but Tornado did not. The solution was to find open ports and close the one Tornado was using. The answer comes from here o...
6,001
47,585,705
How do I make a file from a dictionary in python? For example this is my dictionary: dict = {'a':1,'b':2,'c':3} How do I make it into the first sentence of a file that shows this? a,1.b,2.c,3. Thank you to anyone who answers my question.
2017/12/01
[ "https://Stackoverflow.com/questions/47585705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8922904/" ]
You can try this: ``` f = open('file.txt', 'w') dict = {'a':1,'b':2,'c':3} f.write('.'.join('{},{}'.format(a, b) for a, b in dict.items())+'.\n') f.close() ```
``` import json mydict = {'a':1,'b':2,'c':3} with open('dict_file.txt', 'w') as file: file.write(json.dumps(mydict)) ``` Hope this helps.
6,002
40,784,720
I don't know if it is possible or not. I am trying to find a way of sorting a nested list on the following condition 1. i want to sort form 1 point to another (NOT the whole list only part of it) 2. the sorting should be done on the basis of 3rd element of the sublists an Idea of what i want: ``` PAE=[['a',0,8],...
2016/11/24
[ "https://Stackoverflow.com/questions/40784720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5650215/" ]
Sort the slice **and write it back**: ``` >>> PAE[1:4] = sorted(PAE[1:4], key=itemgetter(2)) >>> PAE [['a', 0, 8], ['b', 2, 1], ['d', 7, 2], ['c', 4, 3], ['e', 8, 4]] ```
This should do : ``` from operator import itemgetter PAE=[['a',0,8], ['b',2,1], ['c',4,3], ['d',7,2], ['e',8,4]] split_index = 1 print PAE[:split_index]+sorted(PAE[split_index:],key=itemgetter(2)) #=> [['a', 0, 8], ['b', 2, 1], ['d', 7, 2], ['c', 4, 3], ['e', 8, 4]] ```
6,003
13,787,566
I haven't used my python/virtual environments in a while, but I do have virtualenvironment wrapper installed also. My question is, in the doc page it says to do this: ``` export WORKON_HOME=~/Envs $ mkdir -p $WORKON_HOME $ source /usr/local/bin/virtualenvwrapper.sh $ mkvirtualenv env1 ``` I simply did this at my pr...
2012/12/09
[ "https://Stackoverflow.com/questions/13787566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39677/" ]
If `WORKON_HOME` is not set, your default virtualenv folder will be set to `~/.virtualenvs` (see [virtualenvwrapper.sh l.118](https://bitbucket.org/dhellmann/virtualenvwrapper/src/a766226010beb5df341bcb4bceb2befaba8603d4/virtualenvwrapper.sh?at=default#cl-118)) You will also use `WORKON_HOME` to specify to `pip` wh...
> > I'm confused why I should be creating an environmental variable > WORKON\_HOME and point it to the ~/Envs folder? > > > It's optional. You're confused (like I was) because the documentation is confusing. > > What does that do and how come mine works fine w/o it? > > > It tells `virtualenvwrapper` which...
6,006
6,760,536
I often find myself writing class constructors like this: ``` class foo: def __init__(self, arg1, arg2, arg3): self.arg1 = arg1 self.arg2 = arg2 self.arg3 = arg3 ``` This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pyth...
2011/07/20
[ "https://Stackoverflow.com/questions/6760536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/403401/" ]
How about this? ``` class foo: def __init__(self, arg1, arg2, arg3): for _prop in dir(): setattr(self, _prop, locals()[_prop]) ``` This uses the builtin python dir function to iterate over *all* local variables. It has a minor side effect of creating an extraneous self reference but you could...
What about iterating over the explicit variable names? I.e. ``` class foo: def __init__(self, arg1, arg2, arg3): for arg_name in 'arg1,arg2,arg3'.split(','): setattr(self, arg_name, locals()[arg_name]) f = foo(5,'six', 7) ``` Resulting with ``` print vars(f) {'arg1': 5, 'arg2': 'six', 'a...
6,007
10,813,575
I am working on a html with selenium. After clicking the last link, pop up comes which says as save a file. using selenium I am recording all the events and then generating the selenium RC script. I want to know that how to get the pop up file from code using python?
2012/05/30
[ "https://Stackoverflow.com/questions/10813575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1297123/" ]
In the case of saving a file, you can get around the popup box by configuring the options of your browser profile. See [this](https://stackoverflow.com/questions/12099250/python-webcrawler-downloading-files/12099438) answer for an explanation using Firefox. General idea is that you need to tell Firefox itself to not pr...
Webdriver cannot communicate with the browser modal popup. But this can be done, check out the below link for your answer <http://blog.codecentric.de/en/2010/07/file-downloads-with-selenium-mission-impossible/>
6,017
24,374,400
I am trying to open an https URL using the [`urlopen`](https://docs.python.org/3.2/library/urllib.request.html#urllib.request.urlopen) method in Python 3's [`urllib.request`](https://docs.python.org/3.2/library/urllib.request.html) module. It seems to work fine, but the documentation warns that "[i]f neither `cafile` n...
2014/06/23
[ "https://Stackoverflow.com/questions/24374400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28324/" ]
Works in python 2.7 and above ``` context = ssl.create_default_context(cafile=certifi.where()) req = urllib2.urlopen(urllib2.Request(url, body, headers), context=context) ```
Different Linux distributives have different pack names. I tested in Centos and Ubuntu. These certificate bundles are updates with system update. So you may just detect which bundle is available and use it with `urlopen`. ``` cafile = None for i in [ '/etc/ssl/certs/ca-bundle.crt', '/etc/ssl/certs/ca-certifica...
6,018
9,066,774
I downloaded Open ERP server & web, having decided against the thicker gtk. I added the 2 as projects in eclipse, pydev running on Ubuntu 11.10 and started then up. I went through the web client setup & I though the installation had been done. At some point though I had executed a script that tried to copy all the bits...
2012/01/30
[ "https://Stackoverflow.com/questions/9066774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/536187/" ]
I feel your pain. I went through the same process a couple of years ago when I started working with OpenERP. The good news is that it's not too hard to set up, and OpenERP runs smoothly in Eclipse with PyDev. Start by looking at the [developer book for OpenERP](http://doc.openerp.com/v6.0/developer/1_1_Introduction/in...
using eclipse kepler sr 1, pydev 3.1.0, openerp 7.0 from launchpad using bzr, ubuntu 13.10. This is how I got the whole thing loaded. I have skipped the part where I got the thing to work. This only covers retrieving the sources and being able to open/modify the openerp source in eclipse/pydev. There are three bzr rep...
6,028
46,893,460
When I try to let my bot join my voice channel, I get this error: `await client.join_voice_channel(voice_channel)` (line that generates the error) ``` Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 50, in wrapped ret = yield from coro(*args, **k...
2017/10/23
[ "https://Stackoverflow.com/questions/46893460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8715621/" ]
This is the code i use to make it work. ``` #Bot.py import discord from discord.ext import commands from discord.ext.commands import Bot from discord.voice_client import VoiceClient import asyncio bot = commands.Bot(command_prefix="|") async def on_ready(): print ("Ready") @bot.command(pass_context=True) async ...
Get rid of the > > from discord.voice\_client import VoiceClient > line and it shoudl be ok. > > >
6,029
61,249,502
Today, I was testing my old python script, it was about fetching some details from an API and write then in a file. Until my last test it was working perfectly fine but today when I executed the script it worked, I mean no error at all but it neither write nor created any file. The API is returning complete data - I te...
2020/04/16
[ "https://Stackoverflow.com/questions/61249502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8332158/" ]
Using `'a'` on the `open` call to open the file in append mode (as shown in your code) should work just fine. I don't think your issue is on the Python side. The next thing to check are your directory permissions: ``` $ ls -al domain.log -rw-r--r-- 1 taylor staff 60 Apr 16 07:57 domain.log ``` Here's my output a...
It may be related to file permission or its directory. Use `ls -la` to see file and folder permissions.
6,032
59,440,445
I'm trying to scrape farefetch.com (<https://www.farfetch.com/ch/shopping/men/sale/all/items.aspx?page=1&view=180&scale=282>) with Beautifulsoup4 and I am not able to find the same components (tags or text in general) of the *parsed* text (dumped to soup.html) as in the browser in the dev tools view (when searching for...
2019/12/21
[ "https://Stackoverflow.com/questions/59440445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8868950/" ]
Based on your comment, here is an example how you could extract some information from products that are on discount: ``` import requests from bs4 import BeautifulSoup url = "https://www.farfetch.com/ch/shopping/men/sale/all/items.aspx?page=1&view=180&scale=282" soup = BeautifulSoup(requests.get(url).text, 'html.pars...
The following helped me: instead of the following code ``` page_soup = soup(page_html, "html.parser") ``` use ``` page_soup = soup(page_html, "html") ```
6,033
50,967,265
Please advice how to convert following using python from: ``` 2010-01-04 00:00:00 ``` to: ``` 2010-04-01 00:00:00 ``` I have tried ``` df.Month = pd.to_datetime(df.Month, format('%Y/%m/%d')) ``` but didn't work Thanks in advance
2018/06/21
[ "https://Stackoverflow.com/questions/50967265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/405818/" ]
Use `.dt.strftime("%Y-%d-%m")` **Ex:** ``` import pandas as pd df = pd.DataFrame({"Date": ["2010-01-04 00:00:00"]}) print( pd.to_datetime(df["Date"]).dt.strftime("%Y-%d-%m") ) ``` **Output:** ``` 0 2010-04-01 Name: Date, dtype: object ```
try the following using datetime parser and returning it in a defined format: ``` from datetime import datetime old_date_string='2010-01-04 00:00:00' dt=datetime.strptime(s, '%Y-%m-%d %H:%M:%S') new_date_string=dt.strftime('%Y-%d-%m %H:%M:%S') ``` However, when you want to work with the date I would suggest using th...
6,034
25,326,649
I would like to know if there is a faster and more "pythonic" way of doing the following, e.g. using some built in methods. Given a pandas DataFrame or numpy array of floats, if the value is equal or smaller than 0.5 I need to calculate the reciprocal value and multiply with -1 and replace the old value with the newly ...
2014/08/15
[ "https://Stackoverflow.com/questions/25326649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2539824/" ]
If we are talking about **arrays**: ``` import numpy as np a = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6], dtype=np.float) print 1 / a[a <= 0.5] * (-1) ``` This will, however only return the values smaller than `0.5`. Alternatively use `np.where`: ``` import numpy as np a = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6], dt...
The typical trick is to write a general mathematical operation to apply to the whole column, but then use indicators to select rows for which we actually apply it: ``` df.loc[df.A < 0.5, 'A'] = - 1 / df.A[df.A < 0.5] In[13]: df Out[13]: A B C 0 -inf 0 E 1 -10.000000 1 L 2 -5.000000 ...
6,035
21,444,951
I had an app that was working properly with old verions of wxpython Now with wxpython 3.0, when trying to run the app, I get the following error ``` File "C:\Python27\lib\site-packages\wx-3.0-msw\wx\_controls.py", line 6523, in __init__ _controls_.DatePickerCtrl_swiginit(self,_controls_.new_DatePickerCtrl(*args...
2014/01/29
[ "https://Stackoverflow.com/questions/21444951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/433261/" ]
I know it's been a while since this question was asked, but I just had the same issue and thought I'd add my solution in case someone else finds this thread. Basically what's happening is that the locale of your script is somehow conflicting with the locale of the machine, although I'm not sure how or why. Maybe someon...
I've just faced the same kind of issue. It seems we need to set the locale before using the wx.App : ``` import locale locale.setlocale(locale.LC_ALL, 'C') ``` Two links helped me to solve this issue : * Solution found in PHP : <https://github.com/wxphp/wxphp/issues/108> * How to do the same in Python : [How to set...
6,038
11,908,725
``` #!/bin/python import os pipe=os.popen("ls /etc -alR| grep \"^[-l]\"|wc -l") #Expr1 a=int(pipe.read()) pipe.close() b=sum([len(files) for root,dirs,files in os.walk("/etc")]) #Expr2 print a print b print "a equals to b ?", str(a==b) #False print "Why?" ``` What is the **difference** between **Expr1**'s f...
2012/08/10
[ "https://Stackoverflow.com/questions/11908725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1545784/" ]
If you use walk, errors are ignored (see [this](http://docs.python.org/library/os.htm)), and ls sends a message for each error. These count as words.
On my machine, /etc is a symlink to /private/etc, so `ls /etc` has only one line of output. `ls /etc/` give the expected equivalence between `ls` and `os.walk`.
6,039
56,083,285
I'm trying to write a regex in python that that will either match a URL (for example <https://www.foo.com/>) or a domain that starts with "sc-domain:" but doesn't not have https or a path. For example, the below entries should pass ``` https://www.foo.com/ https://www.foo.com/bar/ sc-domain:www.foo.com ``` However ...
2019/05/10
[ "https://Stackoverflow.com/questions/56083285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3117494/" ]
``` ^((?:https://\S+)|(?:sc-domain:[^/\s]+))$ ``` You can try this. See demo. <https://regex101.com/r/xXSayK/2>
You can use this regex, ``` ^(?:https?://www\.foo\.com(?:/\S*)*|sc-domain:www\.foo\.com)$ ``` **Explanation:** * `^` - Start of line * `(?:` - Start of non-group for alternation * `https?://www\.foo\.com(?:/\S*)*` - This matches a URL starting with http:// or https:// followed by www.foo.com and further optionally ...
6,042
65,391,704
I am working with Jupyter Notebook, writing some python code using numpy library. For some reason, The output of arrays (as well as lists and strings) are displyed from right to left. [![example of an output of array in jupiter](https://i.stack.imgur.com/eGhQ2.png)](https://i.stack.imgur.com/eGhQ2.png)
2020/12/21
[ "https://Stackoverflow.com/questions/65391704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14864624/" ]
Is your system set up for Hebrew? Note that the `:[4] In` is on the right as well. That may trigger array output to be right-to-left. From [this comment on github](https://github.com/ipython/ipython/issues/10980): > > Press Ctrl-Shift-F to bring up the command palette. Search for 'rtl' > and select 'toggle rtl layou...
Thanks. Now it works fine. My browser was set to hebrew and by changing to english it fixed the problem.
6,044
28,079,035
OS: CentOS 6.6 Python 2.7 So, I've (re)installed Canopy after it suddenly stopped working after an abrupt shutdown. It worked fine immediately after the install (I installed as my default Python). But after one reboot, when I try to open it with /root/Canopy/canopy (the icon under applications no longer works, either),...
2015/01/21
[ "https://Stackoverflow.com/questions/28079035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4480411/" ]
It turns out that I was onto something with my last comment. I'd downloaded a bunch of biology modules that depend on python, and so many of them came with their own install. When I added the modules to ~/.bashrc, my bash began calling them in advance of my original CentOS install. Resetting ~/.bashrc and restarting (f...
Try seeing if you have `posixpath` by typing `import posixpath`: ``` >>> import os.path >>> os.path <module 'posixpath' from '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'> >>> ^D bash-3.2$ python >>> import posixpath >>> posixpath <module 'posixpath' from '/Library/Frameworks/Python.f...
6,045
17,703,956
I am using Hash in Ruby, just check whether a certain word is in the “pairs” class and replace them. Initially I code in python and want to convert it into ruby that I am not familiar with. Here is the ruby code I wrote. ``` import sys pairs = {'butter' => 'flies', 'cheese' => 'wheel', 'milk'=> 'expensive'} for line...
2013/07/17
[ "https://Stackoverflow.com/questions/17703956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592038/" ]
Try this: ``` pairs = {'butter' => 'flies', 'cheese' => 'wheel', 'milk'=> 'expensive'} line = ARGV.join(' ').split(' ').map do |word| pairs.include?(word) ? pairs[word] : word end.join(" ") puts line ``` This will loop over each item passed to the script and return the word or the replacement word, joined by a s...
`for` is generally not used in Ruby, as it's got some unusual scoping. Here's how I would write it: ``` pairs = { "butter" => "flies", "cheese" => "wheel", "milk" => "expensive" } until $stdin.eof? line = $stdin.gets pairs.each do |from, to| line = line.gsub(from, to) end line end ``` `import` doesn't ...
6,047
7,958,213
So I am trying to put the result of a query in a string. Let's say row by row (I don't need all the fields by the way), but that's not the point. I am using python against a sqlite db. the problem is that when some of the fields are null, python will write None instead of "" or some blank neutral thing. example: ```...
2011/10/31
[ "https://Stackoverflow.com/questions/7958213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/918420/" ]
Inheriting from *object* automatically brings the *type* metaclass along with it. This overrides your module level *\_\_metaclass\_\_* specification. If the metaclass is specified at the class level, then *object* won't override it: ``` def metaclass(future_class_name, future_class_parents, future_class_attrs): p...
The specification [specifies the order in which Python will look for a metaclass](http://docs.python.org/reference/datamodel.html?highlight=__metaclass__#customizing-class-creation): > > The appropriate metaclass is determined by the following precedence > rules: > > > * If `dict['__metaclass__']` exists, it is us...
6,048
17,682,571
This is the command that I am using. I have followed the steps in <https://developers.google.com/appengine/docs/python/tools/uploadingdata>. When I use the same command for the same application that I have hosted on the web, the command works and I can see the data in the datastore. But the same command is not working ...
2013/07/16
[ "https://Stackoverflow.com/questions/17682571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2582075/" ]
If your parameters are right but the authentication is failing, pass in the -oauth2 flag: appcfg.py --oauth2 update app.yaml Then the rest of your appcfg.py should authenticate. If it still doesn't work your appid or url is probably off.
if you are using mac, you should have administration privileges on your mac. if not, put sudo on the beginning of the command
6,049
22,726,553
Trying to iterate through a number string in python and print the product of the first 5 numbers,then the second 5, then the third 5, etc etc. Unfortunately, I just keep getting the product of the first five digits over and over. Eventually I'll append them to a list. Why is my code stuck? edit: Original number is an...
2014/03/29
[ "https://Stackoverflow.com/questions/22726553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3462587/" ]
There are a few problems with your code: 1) Your `s+=1` indentation is incorrect 2) It should be `s+=5` instead (assuming you want products of 1-5, 6-10, 11-15 and so on otherwise s+=1 is fine) ``` def product_of_digits(number): d = str(number) s = 0 while s < (len(d)-5): print (int(d[s])*int(d[s+...
numpy.product([int(i) for i in str(s)]) where s is the number.
6,052
35,539,657
Environment =========== * Raspberry Pi 2 * raspbian-jessie-lite * Windows 8.1 * PuTTY 0.66 (SSH) Issue ===== Can't get cron to execute a python script with sudo. The script deals with GPIO input so it should be called with sudo. The program is supposed to save temperature and humidity to files but `cat temp.txt` and...
2016/02/21
[ "https://Stackoverflow.com/questions/35539657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4061339/" ]
I suggest learning how to use Swing. You will have several different classes interacting together. In fact, it is considered good practice to keep separate the code which creates and manages the GUI from the code which performs the underlying logic and data manipulation.
I would recommend using netbeans to start with. From there you can easily select pre created classes such as Jframes. Much easier to learn. You can create a GUI from there by dragging and dropping buttons and whatever you need. Here is a youtube tut to create GUI's in netbeans. <https://www.youtube.com/watch?v=LFr06Z...
6,054
43,327,194
Is there a python library or API that can use a camera to detect LED lights at know locations? The lights will be different colors. I am interested in making an automated production test for a PCB. My board has many LEDs, and a test command makes the board turn LEDs on when some features work correctly. People may mis...
2017/04/10
[ "https://Stackoverflow.com/questions/43327194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3749646/" ]
It is quite possible to solve this. As @John Percival Hackworth said, opencv is a good choice to solve this. I can give you some pointers on how to go about it. * Take a picture of the board with LEDs, since you know the colors of LEDs, use that knowledge to filter the colors. For which I have given a code snippet. *...
[OpenCV](https://github.com/skvark/opencv-python%20'OpenCV') is a possible choice that would let you segue to another language later if needed.
6,059
44,469,620
Following is my code creating an HTTP or FTP connection depending on user input. The if and elif conditions somehow evaluate to FALSE all the time. Entering 1 and 0 both prints 'Sorry, wrong answer'. ``` domain = 'ftp.freebsd.org' path = '/pub/FreeBSD/' protocol = input('Connecting to {}. Which Protocol to use? (0-h...
2017/06/10
[ "https://Stackoverflow.com/questions/44469620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574481/" ]
Input in Python 3, which it looks like you are using, comes in as a string. You would need to cast it via `int()` (although this needs to be done with caution and exception handling in the event of bad input) in order to compare it to an integer.
Python input() takes input as Unicode string, you need to explicitly compare input as integer with 0 like, ``` if int(input) == 0: # Do something elif int(input) == 1: # Do something ```
6,060
42,566,496
I have a text file with this format: > > > ``` > 1 1 (101): 3.7e+08 1.2e+02 5.1234 > 2 1 (101): 3.5e+08 8.2e+02 6.2222 > 2 2 (101): 1.7e+08 2.2e+02 7.4567 > 3 1 (101): 8.7e+08 3.2e+02 9.2123 > > ``` > > I would like to get it into the following format: > > > ``` > 1 3.7e+08 1.2e+02 ...
2017/03/02
[ "https://Stackoverflow.com/questions/42566496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7649922/" ]
The complete solution was to use this code using ApplicationData.Current.LocalFolder.Path because we are not allowed to write files anywhere else then relative path to the application: ``` public static async Task<bool> TryDownloadFileAtPathAsync() { var createdFileId = await UserSnippets.CreateFileAsync(...
If `await DownloadFileAsync(item.Id)` retrieves the file in the resulting stream, then it is up to the caller of your method `GetCurrentUserFileAsync` to write the stream contents somewhere. That can be done using this code ``` var fileContent = await GetCurrentUserFileAsync(onedrivepath, onedrivefilename); using (va...
6,061
65,135,010
this select works in Workbench and Python: ``` #!/usr/bin/python3 import mysql.connector mydb = mysql.connector.connect( host="127.0.0.1", user="root", password="xxxxxxxx", database="gnucash" ) sqlcursor = mydb.cursor() sqlcursor.execute(""" SELECT MAX(transactions.num) AS nr , MAX(transactions.enter_date) ...
2020/12/03
[ "https://Stackoverflow.com/questions/65135010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14516823/" ]
In order to keep the columns when using agg you can use 'first' as given below: Code: ``` import pandas as pd rawdata = {'portfolio': ['port1', 'port2', 'port1', 'port2'], 'portfolioname': ['portfolioone', 'portfoliotwo', 'portfolioone', 'portfoliotwo'], 'date': ['04/12/2020', '04/12/2020', '04/12/20...
This is a touch inelegant but it shows you how to use groupby and then build a series of data. Then once the data is built move it into a dataframe. After most of the output data is assembled then use the output to work out the weight in dataframe. ``` data = [] for cname, dfsub in df1.groupby('code'): port = 'por...
6,062
58,612,306
I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error: ``` >>> import win32api Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: DLL load failed while importing win32api: The specified module could not be found. ``` ...
2019/10/29
[ "https://Stackoverflow.com/questions/58612306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12292714/" ]
The answer is in jupyter notebook github. <https://github.com/jupyter/notebook/issues/4980> `conda install pywin32` worked for me. I am using conda distribution and my virtual env is using Python 3.8
hi this question i'm solve as below: 1.check directory C:\Windows\System32, is exist these file? pythoncom37.dll pywintypes37.dll or pythoncom36.dll pywintypes36.dll the number is python version . 2. if the file is exist delete it. and then this issue will be solve.
6,064
46,279,333
``` @echo off start c:\Python27\python.exe C:\Users\anupam.soni\Desktop\WIND_ACTUAL\tool.py PAUSE ``` My script in tool.py is correctly working in **PyCharm IDE**, this bat is not working. **Note : file path and python path is correct.** Any other option to run python script independently
2017/09/18
[ "https://Stackoverflow.com/questions/46279333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8527475/" ]
I assume that in your Adapter, you hold an array of objects that represents the items you want to be displayed. Add a property to this object named for example `ButtonVisible` and set the property when you press the button. Complete sample adapter follows. This displays a list of items with a button that, when presse...
Set an array of boolean variables associated with each item. ``` @Override public void onBindViewHolder(final MyViewHolder holder, int position) { if(visibilityList.get(position)){ holder.button.setVisibility(View.VISIBLE); }else{ holder.button.setVisibility(View.GONE); } holder.mes...
6,074
61,550,294
For my basic, rudimentary Django CMS, in my effort to add a toggle feature to publish / unpublish a blog post (I’ve called my app ‘essays’ and the class object inside my models is `is_published`), I’ve encountered an OperationalError when trying to use the Admin Dashboard to add essay content. I’m expecting to be able ...
2020/05/01
[ "https://Stackoverflow.com/questions/61550294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6095646/" ]
There isn't column is\_published in essays\_essayarticle table of your db try to add column in db by adding new migration and see the change for a table whether this column is going to be added. The error isn't in your view rather it is in query.
I'm making the assumption that you deleted the migrations folder, if so when you makemigrations and migrate write the name of you app at the end example ``` python manage.py makemigrations app_name ```
6,076
4,527,495
I have a strange issue with python 2.6.5. If I call ``` p = subprocess.Popen(["ifup eth0"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() ``` with the interface eth0 being down, the python programm hangs. "p.communicate()" takes a minute or longer to finish. If the interface ...
2010/12/24
[ "https://Stackoverflow.com/questions/4527495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373361/" ]
You should check out the [warning](http://docs.python.org/library/subprocess.html#subprocess.call) under the `subprocess.call` method. It might be the reason of your problem. **Warning** > > Like Popen.wait(), this will > deadlock when using stdout=PIPE and/or > stderr=PIPE and the child process > generates enou...
``` p = subprocess.Popen(["ifup", "eth0"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() ``` Set `shell=False`, you don't need it. Try running this code, it should work. Notice how two arguments are separate elements in the list.
6,079
49,320,399
I want to call a REST api and get some json data in response in python. ``` curl https://analysis.lastline.com/analysis/get_completed -X POST -F “key=2AAAD5A21DN0TBDFZZ66” -F “api_token=IwoAGFa344c277Z2” -F “after=2016-03-11 20:00:00” ``` I know of python [request](http://docs.python-requests.org/en/latest/), but ho...
2018/03/16
[ "https://Stackoverflow.com/questions/49320399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3855999/" ]
Just include the parameter `data` to the .post function. ``` requests.post('https://analysis.lastline.com/analysis/get_completed', data = {'key':'2AAAD5A21DN0TBDFZZ66', 'api_token':'IwoAGFa344c277Z2', 'after':'2016-03-11 20:00:00'}) ```
-F means make a POST as form data. So in requests it would be: ``` >>> r = requests.post('http://httpbin.org/post', data = {'key':'value'}) ```
6,081
59,845,836
please help me what is my code problem?? my code writing name , mean(grades) in out put ``` import csv from statistics import mean with open('C:/Users/sina/Desktop/python pt/jalase19.csv' , 'r') as fo: reader = csv.reader(fo) for row in reader : name = row[0] grades = list() for grade in row[1:]: ...
2020/01/21
[ "https://Stackoverflow.com/questions/59845836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11828203/" ]
**You didn't do an indent after the "with" statement** As described [here](https://docs.python.org/2.5/whatsnew/pep-343.html) you have to do an indent after an "with" statement Your code should look like that: ``` import csv from statistics import mean with open('C:/Users/sina/Desktop/python pt/jalase19.csv' , 'r') ...
When opening your files you are missing indentation. See how the error points you to line 4? When opening a file using the [context manager](https://book.pythontips.com/en/latest/context_managers.html) and anytime you are using a control statement (if, else, for, etc.) the next line must be indented. ``` import csv fr...
6,083
16,894,490
I have some problems with this code... send not the integer image but some bytes, is there someone than can help me? I want to send all images I find in a folder. Thank you. CLIENT ====== ``` import socket import sys import os s = socket.socket() s.connect(("localhost",9999)) #IP address, port sb = 'c:\\python...
2013/06/03
[ "https://Stackoverflow.com/questions/16894490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2445800/" ]
To transfer a sequence of files over a single socket, you need some way of delineating each file. In effect, you need to run a small protocol on top of the socket which allows to you know the metadata for each file such as its size and name, and of course the image data. It appears you're attempting to do this, howeve...
The parameter to [`socket.recv`](http://docs.python.org/2/library/socket#socket.socket.recv) only specifies the maximum buffer size for receiving data packages, it doesn't mean exactly that many bytes will be read. So if you write: ``` strng = sc.recv(int(size)) ``` you won't necessarily get all the content, specia...
6,084
27,012,337
I'm trying to use ConfigParser to read a .cfg file for my pygame game. I can't get it to function for some reason. The code looks like this: ``` import ConfigParser def main(): config = ConfigParser.ConfigParser() config.read('options.cfg') print config.sections() Screen_width = config.getint('graphics...
2014/11/19
[ "https://Stackoverflow.com/questions/27012337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3033405/" ]
Your config file probably is not found. The parser will just produce an empty set in that case. You should wrap your code with a check for the file: ``` from ConfigParser import SafeConfigParser import os def main(): filename = "options.cfg" if os.path.isfile(filename): parser = SafeConfigParser() ...
I always use the `SafeConfigParser`: ``` from ConfigParser import SafeConfigParser def main(): parser = SafeConfigParser() parser.read('options.cfg') print(parser.sections()) screen_width = parser.getint('graphics','width') screen_height = parser.getint('graphics','height') ``` Also make sure th...
6,085
54,833,385
I have the following code (using dnspython), which works - but it uses globals which I'm not keen on. I was thinking that I could use a recursive function but there is no obvious end. Does anyone have any ideas on how this could be improved?? ``` import dns.resolver dns_resolver = dns.resolver.Resolver() dns_resolve...
2019/02/22
[ "https://Stackoverflow.com/questions/54833385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3595388/" ]
Here is a slightly cleaned-up recursive function with a properly local variable. ``` import dns.resolver def get_spf_count(domain_name, dns_resolver=None): if dns_resolver is None: dns_resolver = dns.resolver.Resolver() dns_resolver.nameservers = ['1.1.1.1', '1.0.0.1'] resolve_count = 0 ...
Why not pass `resolve_count` in as a variable, and have the function return the updated value? ``` def get_spf_count(domain_name, resolve_count): for answer in dns_resolver.query(domain_name, 'TXT'): spf = answer.to_text() if 'v=spf1' in answer.to_text() else None if spf: spf_records = ...
6,088
37,144,913
I am getting above error when I am running an iteration using FOR loop to build multiple models. First two models having similar data sets build fine. While building third model I am getting this error. The code where error is thrown is when I call sm.logit() using Statsmodel package of python: ``` y = y_mort.convert_...
2016/05/10
[ "https://Stackoverflow.com/questions/37144913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5286020/" ]
This error may also come due to wrong usage of API **Correct**: ```py X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=0.7, test_size=0.3, random_state=100 ) ``` **Incorrect**: ```py X_train, y_train, X_test, y_test = train_test_split( X, y, train_size=0.7, test_size=0.3, random_state...
It may be due to different indices in `x` and `y`. This may happen when we initially removed some values from dataframe and perform some operations on `x` after separating `x` and `y`. The indices in `y` will contain the missing indices from original dataframe while `x` will have continuous indices. It's best to do `da...
6,089
51,020,212
I am trying to download a package to call **sc2** and when I write `pip install sc2` into cmd prompt, I receive the error: > > Command "python setup.py egg\_info" failed with error code 1 in c:\users\user\appdata\local\temp\pip-install-q3ixb0\websockets. > > > Any help?
2018/06/25
[ "https://Stackoverflow.com/questions/51020212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9988239/" ]
**easy\_install** Worked of me. easy\_install sc2
Maybe are you behind a proxy or not connected? has you try to make ping to any url ?
6,099
63,708,795
I'm receiving a string like this sentence **"Mr,Pavol,Bujna,has arrived"** from a server. To my Raspberry Pi with Python sockets... It's working well, but need to split the sentence to separate variables. What I have now: `message2 = 'Mr,Pavol,Bujna,has arrived'` What I need: ``` firstname = 'Pavol' surname = 'Buj...
2020/09/02
[ "https://Stackoverflow.com/questions/63708795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13082942/" ]
message2 = 'Mr,Pavol,Bujna,has arrived' ``` words=message2.split(',') firstname=words[1] lastname=words[2] arravingLeaving=words[3] ``` or u could use tuple unpacking as well
Thanks, I figured it out myself meanwhile. Splitting message2 string to multiple variables ``` title, firstName, lastName, arravingLeaving = message2.split(",") print(title) print(firstName) print(lastName) print(arravingLeaving) ``` Whole code: ``` #!/usr/bin/python # -*- coding:utf-8 -*- impo...
6,100
13,256,735
In my application, I have one single thread that is performing very fast processing on log lines to produce a float value. There is usually only a single other thread performing slow reads on the values at intervals. Every so often, other threads can come and go and also perform once-off reads on those values. My ques...
2012/11/06
[ "https://Stackoverflow.com/questions/13256735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496445/" ]
Try this macro: ``` Sub ConsolidateRows() 'takes rows and consolidate one or many cells, based on one or many cells matching with above or below rows. Dim lastRow As Long, i As Long, j As Long Dim colMatch As Variant, colConcat As Variant '**********PARAMETERS TO UPDATE**************** Const strMatch As String = "A"...
The following VBA code should work for what you are trying to do. It assumes that your email addresses are in the range A2:A50000, so you can change this to fit your needs. If you are not too familiar with VBA, under the Developer Tab in Excel 2011 Mac, there should be an icon called Visual Basic Editor. Open VB and CM...
6,101
53,910,919
I want get the name (first line only) from the below raw content. Can you please help me? I want to get just `RAM KUMAR` only from the raw text using python. Raw Content: ``` "RAM KUMAR\n\nMarketing and Sales Professional\n\n+91.0000000000\n\nshri.babuji@shriresume.com, shri1.babuji@shriresume.com\n\nLinkedin.com/in/...
2018/12/24
[ "https://Stackoverflow.com/questions/53910919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3239174/" ]
No need to use regex, just simply do: ``` print(yourstring.split('\n')[0]) ``` Output: ``` RAM KUMAR ``` **Edit:** ``` with open(filename,'r') as f: print(f.read().split('\n')[0]) ```
Use [`split`](https://www.geeksforgeeks.org/python-string-split/) to do something like this perhaps: ``` txt_content = "RAM KUMAR\n\nMarketing and Sales Professional\n\n+91.0000000000\n\nshri.babuji@shriresume.com, shri1.babuji@shriresume.com\n\nLinkedin.com/in/ramkumar \t\t\t\t ...
6,102
28,465,477
I'm looking into how to compute as efficient as possible in python3 a dot product inside a double sum of the form: ``` import cmath for j in range(0,N): for k in range(0,N): sum_p += cmath.exp(-1j * sum(a*b for a,b in zip(x, [l - m for l, m in zip(r_p[j], r_p[k])]))) ``` where r\_np is a array of several...
2015/02/11
[ "https://Stackoverflow.com/questions/28465477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2519380/" ]
I used this to generate test data: ``` x = (1, 2, 3) r_p = [(i, j, k) for i in range(10) for j in range(10) for k in range(10)] ``` On my machine, this took `2.7` seconds with your algorithm. Then I got rid of the `zip`s and `sum`: ``` for j in range(0,N): for k in range(0,N): s = 0 for t in ra...
That double loop is a time killer in `numpy`. If you use vectorized array operations, the evaluation is cut to under a second. ``` In [1764]: sum_np=0 In [1765]: for j in range(0,N): for k in range(0,N): sum_np += np.exp(-1j * np.inner(x_np,(r_np[j] - r_np[k]))) In [1766]: sum_np Out[1766]: (2116.33165264...
6,105
61,354,963
``` >>> 1/3 0.3333333333333333 >>> 1/3+1/3+1/3 1.0 ``` I can't understand why this is 1.0. Shouldn't it be `0.9999999999999999`? So I kind of came up with the solution that python has an automatic rounding for it's answer, but if than, the following results can't be explained... ``` >>> 1/3+1/3+1/3+1/3+1/3+1/3 1.9...
2020/04/21
[ "https://Stackoverflow.com/questions/61354963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13376385/" ]
This is one of the subtle points of IEEE-754 arithmetic. When you write: ```py >>> 1/3 0.3333333333333333 ``` the number you see printed is a "rounded" version of the number that is internally stored as the result of `1/3`. It's just what the Double -> String conversion in the printing process decided to show you. B...
This question may provide some answers to the floating point error [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) With the brackets, the compiler is breaking down the addition into smaller pieces, reducing the possibility of a floating point which is not supp...
6,108
50,120,062
I have a 1D `numpy` array. The difference between two succeeding values in this array is either one or larger than one. I want to cut the array into parts for every occurrence that the difference is larger than one. Hence: ``` arr = numpy.array([77, 78, 79, 80, 90, 91, 92, 100, 101, 102, 103, 104]) ``` should become...
2018/05/01
[ "https://Stackoverflow.com/questions/50120062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2776885/" ]
One Pythonic way would be - ``` np.split(arr, np.flatnonzero(np.diff(arr)>1)+1) ``` Sample run - ``` In [10]: arr Out[10]: array([ 77, 78, 79, 80, 90, 91, 92, 100, 101, 102, 103, 104]) In [11]: np.split(arr, np.flatnonzero(np.diff(arr)>1)+1) Out[11]: [array([77, 78, 79, 80]), array([90, 91, 92]), array([1...
Another way with slicing, getting the appropriate indices using `np.diff`: ``` import numpy as np def split(arr): idx = np.pad(np.where(np.diff(arr) > 1)[0]+1, (1,1), 'constant', constant_values = (0, len(arr))) return [arr[idx[i]: idx[i+1]] for i in range(len(idx)-1)] ``` Result: ``` arr = np....
6,111
63,709,660
I'm trying to connect to an SFTP server using Python and Paramiko, but I'm getting this error (the same error occurs when I use pysftp): ```none starting thread (client mode): 0x17ccde50L Local version/idstring: SSH-2.0-paramiko_2.7.2 Remote version/idstring: SSH-2.0-OpenSSH_7.2 Connected (version 2.0, client OpenSSH_...
2020/09/02
[ "https://Stackoverflow.com/questions/63709660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5754267/" ]
This topic suggests that you may have obsolete dependencies: <https://github.com/paramiko/paramiko/issues/1027> [The solution by @bieli](https://github.com/paramiko/paramiko/issues/1027#issuecomment-374145838) seems to help many of those who face the problem: ``` sudo pip uninstall cryptography -y && sudo apt-get ...
In the sample below, you may see absolute paths to a few of the dependencies because I'm running the Python script on a remote server without internet. Therefore, .whl files had to be copied from my PC to the remote server. Of these dependencies, "**cffi**" was upgraded to version 1.11.2 and eventually resolved the iss...
6,112
56,904,802
I want functions in a class to store their returned values in some data structure. For this purpose I want to use a decorator: ```py results = [] instances = [] class A: def __init__(self, data): self.data = data @decorator def f1(self, a, b): return self.data + a + b @decorator ...
2019/07/05
[ "https://Stackoverflow.com/questions/56904802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2015614/" ]
You will need to use `CodeIdTokenToken` response type, according to the [documentation](https://openid.net/specs/openid-connect-core-1_0.html#HybridAuthRequest) `options.ResponseType = OpenIdConnectResponseType.CodeIdTokenToken;`
I managed to fix this. To anyone that would encounter this issue, set the response type to **Code** to get both the id\_token and the access\_token. This will instruct Open ID Connect to use the authorization code flow. ``` options.ResponseType = OpenIdConnectResponseType.Code ```
6,113
61,039,847
I am making Exam app with kivy(python) and I have problem with getting correct answer. I have dictonary of translates from latin words to slovenian words exemple(Keys are latin words, values are slovenian words): ``` Dic = {"Aegrotus": "bolnik", "Aether": "eter"} ``` So the problem is when 2 or 3 latin words mean sa...
2020/04/05
[ "https://Stackoverflow.com/questions/61039847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11590506/" ]
Firstly, you have to be able to get the text output from the app shown in the picture, then you use your dictionary to check it. And the way to design the dictionary makes it difficult to check. You should design it that way: key is only one string, and values is a list. For example: ``` Dic = {"A": ["od"], "ab": ["o...
Do you only need to translate from latin -> slovenian and not the other way around? If so, just make every key a single word. It's OK for multiple keys to have the same value: ```py Dic = { "Aegrotus": "bolnik", "Aether": "eter", "A": "od", "ab": "od", "Acutus": ("Akuten", "Akutna", "Akutno"), "Aromaticus": ("...
6,114
51,187,904
Trying to read a `Parquet` file in PySpark but getting `Py4JJavaError`. I even tried reading it from the `spark-shell` and was able to do so. I cannot understand what I am doing wrong here in terms of the Python APIs that it is working in Scala and not in PySpark; ``` spark = SparkSession.builder.master("local").appNa...
2018/07/05
[ "https://Stackoverflow.com/questions/51187904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5129047/" ]
I figured out what was going wrong exactly. The `spark-shell` was using `Java 1.8`, but `PySpark` was using `Java 10.1`. There is some issue with Java 1.9/10 and Spark. Changed the default Java version to 1.8.
Spark runs on Java 8/11. For switching between Java versions, you can add this to your .bashrc/.zshrc file: ```sh alias j='f(){ export JAVA_HOME=$(/usr/libexec/java_home -v $1) };f' ``` Then in your terminal: ```sh source .zshrc ``` ```sh j 1.8 ``` ```sh java -version ``` This will change the version system-...
6,117
5,838,307
I'd like to create a drop-in replacement for python's `list`, that will allow me to know when an item is added or removed. A subclass of list, or something that implements the list interface will do equally well. I'd prefer a solution where I don't have to reimplement all of list's functionality though. Is there a easy...
2011/04/29
[ "https://Stackoverflow.com/questions/5838307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143091/" ]
To see what functions are defined in list, you can do ``` >>> dir(list) ``` Then you will see what you can override, try for instance this: ``` class MyList(list): def __iadd__(self, *arg, **kwargs): print "Adding" return list.__iadd__(self, *arg, **kwargs) ``` You probably need to do a few mo...
The [documentation for userlist](http://docs.python.org/release/2.5.2/lib/module-UserList.html) tells you to subclass `list` if you don't require your code to work with Python <2.2. You probably don't get around overriding at least the methods which allow to add/remove elements. Beware, this includes the slicing operat...
6,120
18,619,205
To start I will mention that I am new to the Python Language and come from a networking background. If you are wondering why I am using Python 2.5 it is due to some device constraints. What I am trying to do is count the number of lines that are in a string of data as seen below. (not in a file) ``` data = ['This','...
2013/09/04
[ "https://Stackoverflow.com/questions/18619205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2240963/" ]
`list.count` is used to get the count of an item in list, but you need to do a substring search in each item to get the count as 4. ``` >>> data = ['This','is','some','test','data','\nThis','is','some','test','data','\nThis','is','some','test','data','\nThis','is','some','test','data','\n'] ``` Total number of items...
Your first code does not work because you only have one `'\n'` in your actual list of strings. When you compare `'\n'` to something like `'nThis'`, then it will say that `\n` is not equal to that string and not include it in the count. What you can do is join the list into a string like so: ``` x = ''.join(num) ``` ...
6,121
54,997,210
Im currently writing a program in python where I have to figure out smileys like these `:)`, `:(`, `:-)`, `:-(` should be replace if it is followed by special characters and punctuation should be replaced in this pattern : ex : `Hi, this is good :)#` should be replaced to `Hi, this is good :)`. I have created regex pa...
2019/03/05
[ "https://Stackoverflow.com/questions/54997210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4045224/" ]
One approach is to use the following pattern: ``` (:\)|:\(|:-\)|:-\()[^A-Za-z0-9]+ ``` This matches *and* captures a smiley face, then matches any number of non alphanumeric characters immediately afterwards. The replacement is just the captured smiley face, thereby removing the non alpha characters. ``` input = "H...
you can escape special characters with `\` try: ``` re.sub("[^a-zA-Z0-9:):D:\-))]+", " " , words) ```
6,122
37,451,031
I have some python code to unzip a file and then remove it (the original file), but my code catches an exception: it cannot remove the file, because it is in use. I think the problem is that when the removal code runs, the unzip action has not finished, so the exception is thrown. So, how can I check the run state of ...
2016/05/26
[ "https://Stackoverflow.com/questions/37451031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2213922/" ]
The documentation for ZipFile says: > > ZipFile is also a context manager and therefore supports the [with](https://docs.python.org/2/reference/compound_stmts.html#with) statement. > > > So, I'd recommend doing the following: ``` with zipfile.ZipFile(lfilename) as file: file.extract(filename, dir) remove(lfi...
Try closing the file before removing it. ``` file = zipfile.ZipFile(lfilename) for filename in file.namelist(): file.extract(filename,dir) file.close() remove(lfilename) ```
6,124
33,687,594
I have been trying to debug this issue, but can't seem to figure it out. When debugging I can see that all the variables are where they should be, but I can't seem to get them out. When running I get the error message `'dict' object is not callable` This is the full error message from Django ``` Environment: Req...
2015/11/13
[ "https://Stackoverflow.com/questions/33687594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5039579/" ]
Dictionaries need square brackets ``` form_counter_currency = form.cleaned_data['form_counter_currency'] ``` although you may want to use `get` so you can provide a default ``` form_counter_currency = form.cleaned_data.get('form_counter_currency', None) ```
import this ``` from rest_framework.response import Response ``` Then after write this in **views.py** file ``` class userlist(APIView): def get(self,request): user1=webdata.objects.all() serializer=webdataserializers(user1,many=True) return Response(serializer.data) def post(self): pass ```
6,127
7,748,563
*Disclaimer: complete rewrite for clarity as of 10/14/2011* **Given** the `number` primitive in JavaScript is an [IEEE 754](http://en.wikipedia.org/wiki/IEEE_754-2008) 64-bit floating point (*known in other languages as a double*), and [using floats to model currencies is a **bad idea**](https://stackoverflow.com/ques...
2011/10/13
[ "https://Stackoverflow.com/questions/7748563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902839/" ]
Both [bigdecimal.js](https://github.com/jhs/bigdecimal.js/) and [node-bigint](https://github.com/substack/node-bigint) have arbitrary precision. I'd go with bigint. bigdecimal is a GWT version of of Java's BigDecimal, clocking in at 113kb, so the code is not what one would call *readable*. **update:** [money.js](http...
There is a GREAT $.money class the does almost everything you could ever want from money in the ku4js-kernel library. You can find the documentation [here](http://kodmunki.github.io/ku4js-kernel/#money). Have fun! :{)}
6,128
67,579,796
I am trying to change the JSON format using python. The received message has some key-value pairs and needs to change certain key names before forwarding the message. for normal key-value pairs, I have used "data. pop" method, data["newkey"]=data.pop("oldkey") . But it got complicated with nested key-values. This is ju...
2021/05/18
[ "https://Stackoverflow.com/questions/67579796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15715705/" ]
If the keys gonna be in the same format you can do something like this. ``` d = { "ev": "contact_form_submitted", "et": "form_submit", "id": "cl_app_id_001", "uid": "cl_app_id_001-uid-001", "mid": "cl_app_id_001-uid-001", "t": "Vegefoods - Free Bootstrap 4 Template by Colorlib", "p": "http...
Use the following code it will successfully convert it. ``` json1={ "atrk1": "form_varient", "atrv1": "red_top", "atrt1": "string", "atrk2": "ref", "atrv2": "XPOWJRICW993LKJD", "atrt2": "string" } json2={} keys=[] values=[] types=[] for i in json1: if i[:4]=='atrk': keys.append(json1[...
6,130
58,740,865
I'm trying to scrape this page/iframe with selenium/python but I can't insert any text in this selected form. [link](https://ibb.co/cF8ZRZP) ```py from selenium import webdriver from time import sleep driver = webdriver.Firefox() url = 'http://web.transparencia.pe.gov.br/despesas/despesa-geral/' driver.get(url) slee...
2019/11/07
[ "https://Stackoverflow.com/questions/58740865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7651009/" ]
In such kind of situation, the right tool is to use [std::integer\_sequence](https://en.cppreference.com/w/cpp/utility/integer_sequence) ``` #include <iostream> #include <utility> template <size_t N> void make() { std::cout << N << std::endl; } template <size_t... I> void do_make_helper(std::index_sequence<I...>) ...
As a start point with handcrafted index list: ``` template <size_t N> int make(); template<> int make<1>() { std::cout<< "First" << std::endl; return 100; } template<> int make<2>() { std::cout << "Second" << std::endl; return 200; } template<> int make<3>() { std::cout << "Third" << std::endl; return 100; } struct ...
6,131
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.co...
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
Here it is. By the way, if you need this operation often, you may create a function for `color_ins` creation, based on `pixel_ins`. Or even for any subnamedtuple! ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._...
`Point._fields + Color._fields` is simply a tuple. So given this: ``` from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) f = Point._fields + Color._fields ``` `type(f)` is just `tuple`. T...
6,134
44,535,068
I want to cover a image with a transparent solid color overlay in the shape of a black-white mask Currently I'm using the following java code to implement this. ``` redImg = new Mat(image.size(), image.type(), new Scalar(255, 0, 0)); redImg.copyTo(image, mask); ``` I'm not familiar with the python api. So I want ...
2017/06/14
[ "https://Stackoverflow.com/questions/44535068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2640554/" ]
Now after I deal with all this Python, OpenCV, Numpy thing for a while, I find out it's quite simple to implement this with code: ``` image[mask] = (0, 0, 255) ``` -------------- the original answer -------------- I solved this by the following code: ``` redImg = np.zeros(image.shape, image.dtype) redImg[:,:] = (0...
The idea is to convert the mask to a binary format where pixels are either `0` (black) or `255` (white). White pixels represent sections that are kept while black sections are thrown away. Then set all white pixels on the mask to your desired `BGR` color. **Input image and mask** ![](https://i.stack.imgur.com/OfGZF.p...
6,142
57,251,368
Kindly need some help please :) I have two date-time's i am using the date-time.combine to concatenate one is datetime.date (pretty much todays date) - the other is datetime.time (which is a manually defined time) keep getting stuck with the below error; ``` Traceback (most recent call last): File "sunsetTimer.py"...
2019/07/29
[ "https://Stackoverflow.com/questions/57251368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11847814/" ]
Look at how you have defined `currentTime`: ``` currentTime = localtimesTZ() ``` Your `localtimesTZ()` actually returns a tuple `currentTime, tday, todayDate`, which is what is assigned to `currentTime`. Not sure why you are doing that; returning just the `currentTime` should be sufficient, since it is a `datetime....
It sounds like you are just trying to do a simple comparison of a manually set date and check if that day is today. If that is the case it would be simpler to use the same class datetime. Below is a simple example checking if today (manually defined) is today (defined by python) from datetime import datetime ``` toda...
6,145
6,265,517
Can anyone name a language with all the following properties: 1. Has algebraic data types 2. Has good support for linear algebra 3. Is fast(-er than python, at least) 4. Has at least some functional programming ability (I don't need monads) 5. Has been heard of, is not dead, and can interface on a C calling level
2011/06/07
[ "https://Stackoverflow.com/questions/6265517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787480/" ]
Scala ===== According to [Wikipedia](http://en.wikipedia.org/wiki/Algebraic_data_type) it has algebraic datatypes. And it is [fast](http://www.scribd.com/doc/57021877/Loop-Recognition-in-C-Java-Go-Scala). Scala is both functional and object oriented. And it's a young language with a growing userbase but still to some ...
I'd say C and C++. And they work well with: * [Matlab](http://www.mathworks.com/products/matlab/) * [Maple](http://www.maplesoft.com/products/Maple/)
6,147
54,722,389
First off, let me say that yes I have researched this extensively for a few days now with no luck. I have looked at numerous examples and similar situations such as [this one](https://stackoverflow.com/questions/35149265/python-super-method-class-name-not-defined), but so far nothing has been able to resolve me issue. ...
2019/02/16
[ "https://Stackoverflow.com/questions/54722389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348576/" ]
[Here](https://stackoverflow.com/questions/38778158/how-to-do-nested-class-and-inherit-inside-the-class?rq=1) they do it like this ``` super(MainClass.InnerSubClass, self).__init__(thing, otherThing) ``` So that you can test it here is the full working example ``` class SomeClass(object): def __init__(self)...
If you have reasons for not using `MainClass.InnerSubClass`, you can also use `type(self)` or `self.__class__` ([OK, but which one](https://stackoverflow.com/questions/1060499/difference-between-typeobj-and-obj-class)) inside `__init__` to get the containing class. This works well lots of layers deep (which shouldn't h...
6,150
17,903,820
code below creates a layout and displays some text in the layout. Next the layout is displayed on the console screen using raw display module from urwid library. (More info on my complete project can be gleaned from questions at [widget advice for a console project](https://stackoverflow.com/questions/17846930/required...
2013/07/28
[ "https://Stackoverflow.com/questions/17903820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2534758/" ]
It means that self.\_started has been evaluated to False. ``` assert <Some boolean expression>, "Message if exp is False" ``` If the expression is evaluated to True, nothing special will happen, but if the expression is evaluated to False an AssertionError exception will be thrown. You can try/except the line if yo...
You call `formLayout` before you `start` the screen. `formLayout` calls `ui.draw_screen`, which requires that the screen has been started.
6,152
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', ...
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Thanks for all the answers and comments ! Thought for a while and got another answer in my previous way I have written the code. So, I am posting it. ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] e = d[:] # just a bit of trick/spice >>> for i in d: ... if d.count(i) == 1: ... e.remov...
You can also do like this : ``` data=[1,2,3,4,1,2,3,1,2,1,5,6] first_list=[] second_list=[] for i in data: if data.count(i)==1: first_list.append(i) else: second_list.append(i) print (second_list) ``` Result ====== [1, 2, 3, 1, 2, 3, 1, 2, 1]
6,153
15,000,311
I am having trouble to start a python script and get the parameters I send to the script. ![enter image description here](https://i.stack.imgur.com/z2Pnj.jpg) As you can see if I start the following test script with python comand, it works, if not, well, no arguments are passed to the script :/ ``` import optparse i...
2013/02/21
[ "https://Stackoverflow.com/questions/15000311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2095037/" ]
Check out [ImageResizer](http://imageresizing.net) - it's a suite of NuGet packages designed for this exact purpose. It runs eBay in Denmark, MSN Olympics, and a few other big sites. Dynamic image processing can be done safely and efficiently, but not in a sane amount of code. It's [trickier than it appears](http://...
I wouldn't recommend this but you can do next thing: ``` using (Image img = Image.FromStream(originalImage)) { using (Bitmap bitmap = new Bitmap(img, width, height)) { bitmap.Save(outputStream, ImageFormat.Jpeg); } } ``` Be aware that this could cause OutOfMemoryException.
6,163
14,486,802
What are common uses for Python's built-in `coerce` function? I can see applying it if I do not know the `type` of a numeric value [as per the documentation](http://docs.python.org/2/library/functions.html#coerce), but do other common usages exist? I would guess that `coerce()` is also called when performing arithmetic...
2013/01/23
[ "https://Stackoverflow.com/questions/14486802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/839375/" ]
Its a left over from [early python](http://docs.python.org/release/1.5.2/ref/numeric-types.html), it basically makes a tuple of numbers to be the same underlying number type e.g. ``` >>> type(10) <type 'int'> >>> type(10.0101010) <type 'float'> >>> nums = coerce(10, 10.001010) >>> type(nums[0]) <type 'float'> >>> type...
Python core programing says: > > Function coerce () provides the programmer do not rely on the Python interpreter, but custom two numerical type conversion." > > > e.g. ``` >>> coerce(1, 2) (1, 2) >>> >>> coerce(1.3, 134L) (1.3, 134.0) >>> >>> coerce(1, 134L) (1L, 134L) >>> >>> coerce(1j, 134L) (1j, (134+0j)) >>...
6,164