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
73,027,674
I have a Vertex AI notebook that contains a lot of python and jupyter notebook as well as pickled data files in it. I need to move these files to another notebook. There isn't a lot of documentation on google's help center. Has someone had to do this yet? I'm new to GCP.
2022/07/18
[ "https://Stackoverflow.com/questions/73027674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5917787/" ]
Can you try these steps in this [article](https://cloud.google.com/vertex-ai/docs/workbench/user-managed/migrate). It says you can copy your files to a [Google Cloud Storage Bucket](https://cloud.google.com/storage/) then move it to a new notebook by using gsutil tool. In your notebook's terminal run this code to copy...
I'm assuming that both notebooks are on the same GC project and that you have the same permissions on both, ok? There are many ways to do that... Listing some here: 1. The hardest to execute, but the simplest by concept: You can download everything for your computer/workstation from the original notebook instance, th...
10,468
1,997,327
Given this python code: ``` import webbrowser webbrowser.open("http://slashdot.org",new=0) webbrowser.open("http://cnn.com",new=0) ``` I would expect a browser to open up, load the first website, then load the second website *in the same window*. However, it opens up in a new window (or new tab depending on which br...
2010/01/04
[ "https://Stackoverflow.com/questions/1997327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83879/" ]
Note that the documentation specifically avoids guarantees with the language *if possible*: <http://docs.python.org/library/webbrowser.html#webbrowser.open> Most browser settings by default specify tab behavior and will not allow Python to override it. I have seen it in the past using Firefox and tried your example on...
I added a delay between successive invocations of `webbrowser.open()`. Then each was opened in a new tab instead of a separate window (on my Windows 10 machine). ```py import time ... time.sleep(0.5) ```
10,469
27,214,901
Please consider the following short Python 2.x script: ``` #!/usr/bin/env python class A(object): class B(object): class C(object): pass def __init__(self): self.c = A.B.C() def __init__(self): self.b = A.B() def main(): a = A() print "%s: %r" % (type(a)...
2014/11/30
[ "https://Stackoverflow.com/questions/27214901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476371/" ]
Here are two demonstrative programs one for C++ 2003 and other for C++ 2011 that do the search **C++ 2003** ``` #include <iostream> #include <string> #include <vector> #include <algorithm> #include <utility> #include <functional> struct FindName : std::unary_function<bool, cons...
I strongly advise you to use a data structure with an overloaded equality operator instead of `vector<string>` (especially since it seems like the third element should be saved in an integer, not a string). Anyway, this is one possibility: ``` auto iter = std::find_if( std::begin(a_words), std::end(a_words), ...
10,470
24,804,667
I'm trying to wrap a C library for python using SWIG. I'm on a linux 64-bit sytem (Gentoo) using the standard system toolchain. The library (SUNDIALS) is installed on my system with shared libraries in `/usr/local/lib` My interface file is simple (to start with) ``` %module nvecserial %{ #include "sundials/sundials_...
2014/07/17
[ "https://Stackoverflow.com/questions/24804667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184986/" ]
We'll I've got it working by linking in an extra library. It seems `libsundials_nvecserial.so` and brethren don't contain the symbol N\_VLinearSum. The SUNDIALS make process places functions and symbols from `sundials_nvector.h` into different .so files, somewhat counter intuitively. For now, I got this working with ...
Instead of ``` gcc -shared /usr/local/lib/libsundials_nvecserial.so nvecserial_wrap.o -o _nvecserial.so ``` try ``` gcc -shared -L/usr/local/lib nvecserial_wrap.o -o _nvecserial.so -lsundials_nvecserial ``` The -l should be at end otherwise the lib may not be searched for symbols. This is explained in the ld ma...
10,473
38,791,685
I want to generate a single executable file from my python script. For this I use pyinstaller. I had issues with mkl libraries because I use numpy in the script. I used this [hook](https://github.com/pyinstaller/pyinstaller/issues/1881 "hook") so solve the issue, it worked fine. But it does not work if I copy the sing...
2016/08/05
[ "https://Stackoverflow.com/questions/38791685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5521383/" ]
When I faced problem described here <https://github.com/ContinuumIO/anaconda-issues/issues/443> my workaround was `pyinstaller -F --add-data vcruntime140.dll;. myscript.py` `-F` - collect into one *\*.exe* file `.` - Destination path of dll in exe file from docs <http://pyinstaller.readthedocs.io/en/stable/spec-fi...
As the selected answer didn't work for the case of using **libportaudio64bit.dll**, I put my working solution here. For me, the working solution is to add **\_sounddevice\_data** folder where the .exe file is located then making a **portaudio-binaries** folder in it and finally putting **libportaudio64bit.dll** in the...
10,474
10,550,870
I have some Pickled data, which is stored on disk, and it is about 100 MB in size. When my python program is executed, the picked data is loaded using the `cPickle` module, and all that works fine. If I execute the python multiple times using `python main.py` for example, each python process will load the same data m...
2012/05/11
[ "https://Stackoverflow.com/questions/10550870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/406930/" ]
If you're on Unix, one possibility is to load the data into memory, and then have the script use [`os.fork()`](http://docs.python.org/library/os.html#os.fork) to create a bunch of sub-processes. As long as the sub-processes don't attempt to *modify* the data, they would automatically share the parent's copy of it, with...
Depending on how seriously you need to solve this problem, you may want to look at memcached, if that is not overkill.
10,479
41,612,654
I got an error after I modified the User Model in django. when I was going to create a super user, it didn't prompt for username, instead it skipped it, anyway the object propery username still required and causing the user creation to failed. ``` import jwt from django.db import models from django.contrib.auth.model...
2017/01/12
[ "https://Stackoverflow.com/questions/41612654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3465227/" ]
`REQUIRED_FIELD` should be `REQUIRED_FIELDS` (plural), otherwise you won't be prompted for a username (or any other required fields) because Django did not find anything in `REQUIRED_FIELDS`. As an example, I use this UserManager in one of my projects: ``` class UserManager(BaseUserManager): def create_user(self,...
This bit doesn't make sense: ``` USERNAME_FIELD = 'email' REQUIRED_FIELD = ['username'] ``` Why have you set `USERNAME_FIELD` to "email"? Surely it should be "username".
10,480
48,617,779
I am receiving the error: `ImportError: No module named MySQLdb` whenever I try to run my local dev server and it is driving me crazy. I have tried everything I could find online: 1. `brew install mysql` 2. `pip install mysqldb` 3. `pip install mysql` 4. `pip install mysql-python` 5. `pip install MySQL-python` 6. `eas...
2018/02/05
[ "https://Stackoverflow.com/questions/48617779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4918575/" ]
When you are in the virtual env (`source venv/bin/activate`), just run in terminal: ``` sudo apt-get install python3-mysqldb sudo apt-get install libmysqlclient-dev pip install mysqlclient ``` You don't have to import anything in your py files. The first one is just in case, but the other two work perfectly by them...
Turns out I had the wrong python being pointed to in my virtualenv. It comes preinstalled with its own default python version and so, I created a new virtualenv and used the `-p` to set the python path to my own local python path.
10,481
21,807,660
I am trying to run the first example [here](http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html), but I am getting this error. I am using Ubuntu 13.10. ``` Failed to load OpenCL runtime OpenCV Error: Unknown error code -220 (OpenCL function is not availab...
2014/02/16
[ "https://Stackoverflow.com/questions/21807660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1852142/" ]
As for the OpenCL failure, try installing required packages: `sudo apt-get install ocl-icd-opencl-dev` Worked for me. My guess is that OCL is a part of the `opencv_core` module, and if it failed to initialise, then many other components might behave strange.
> > Failed to load OpenCL runtime > > > Most probably there is some problem with your installation. If you are not working with GPU, then I recommend you to turn off all CUDA/OpenCL modules in OpenCV during compilation. > > error: (-215) scn == 3 || scn == 4 in function cvtColor > > > This error says your in...
10,483
54,140,922
I want to create a multiprocessing echo server. I am currently using telnet as my client to send messages to my echo server.Currently I can handle one telnet request and it echos the response. I initially, thought I should intialize the pid whenever I create a socket. Is that correct? How do I allow several clients to...
2019/01/11
[ "https://Stackoverflow.com/questions/54140922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9005618/" ]
It's probably a good idea to understand which are blocking system calls and which are not. `listen` for example is not blocking and `accept` is blocking one. So basically - you created one process through `Process(..)`, that blocks at the `accept` and when a connection is made - handles that connection. Your code sho...
The initial part of setting up the server, binding, listening etc (your `create_socket`) should be in the master process. Once you `accept` and get a socket, you should spawn off a separate process to take care of that connection. In other words, your `start_socket` should be spawned off in a separate process and sho...
10,485
23,922,691
I am trying to add argv[0] as variable to the SQL query below and running into compilation error below,what is the syntax to fix this? ``` #!/usr/bin/python import pypyodbc as pyodbc from sys import argv component_id=argv[0] server_name='odsdb.company.com' database_name='ODS' cnx = pyodbc.connect("DRIVER={SQL Ser...
2014/05/28
[ "https://Stackoverflow.com/questions/23922691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3654069/" ]
Don't use string interpolation. Use SQL parameters; these are placeholders in the query where your database will insert values: ``` SQL = '''\ SELECT Top 1 cr.ReleaseLabel FROM [ODS].[v000001].[ComponentRevisions] cr WHERE cr.ComponentId = ? ORDER BY cr.CreatedOn DESC ''' resp_rows_obj = db_cursor.exec...
to retrieve 1st command line argument do `component_id=argv[1]` instead of 0 which is the script name... better yet, look at [argparse](https://docs.python.org/2/howto/argparse.html)
10,486
24,093,888
I am looking to do a large number of reverse DNS lookups in a small amount of time. I currently have implemented an asynchronous lookup using socket.gethostbyaddr and concurrent.futures thread pool, but am still not seeing the desired performance. For example, the script took about 22 minutes to complete on 2500 IP add...
2014/06/07
[ "https://Stackoverflow.com/questions/24093888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2521829/" ]
Because of the [Global Interpreter Lock](https://docs.python.org/dev/glossary.html#term-global-interpreter-lock), you should use `ProcessPoolExecutor` instead. <https://docs.python.org/dev/library/concurrent.futures.html#processpoolexecutor>
please, use [asynchronous DNS](http://code.google.com/p/adns-python/), everything else will give you a very poor performance.
10,488
61,380,858
I want to create pandas data frame with multiple lists with different length. Below is my python code. ``` import pandas as pd A=[1,2] B=[1,2,3] C=[1,2,3,4,5,6] lenA = len(A) lenB = len(B) lenC = len(C) df = pd.DataFrame(columns=['A', 'B','C']) for i,v1 in enumerate(A): for j,v2 in enumerate(B): for k,...
2020/04/23
[ "https://Stackoverflow.com/questions/61380858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999109/" ]
You can add random values of each list to total length and then use [`DataFrame.sample`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html): ``` A=[1,2] B=[1,2,3] C=[1,2,3,4,5,6] L = [A,B,C] m = max(len(x) for x in L) print (m) 6 a = [np.hstack((np.random.choice(x, m - len(x)), x...
You can use transpose to achieve the same. EDIT: Used random to randomize the output as requested. ``` import pandas as pd from random import shuffle, choice A=[1,2] B=[1,2,3] C=[1,2,3,4,5,6] shuffle(A) shuffle(B) shuffle(C) data = [A,B,C] df = pd.DataFrame(data) df = df.transpose() df.columns = ['A', 'B', 'C'] df....
10,491
47,726,664
I am trying to send messages from one python script to another using MQTT. One script is a publisher. The second script is a subscriber. I send messages every 0.1 second. Publisher: ``` client = mqtt.Client('DataReaderPub') client.connect('127.0.0.1', 1883, 60) print("MQTT parameters set.") # Read from all files co...
2017/12/09
[ "https://Stackoverflow.com/questions/47726664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2892909/" ]
You need to call the network loop function in the publisher as well so the client actually gets some time to do the IO (And the dual handshake for the QOS2). Add `client.loop()` after the call to `client.publish()` in the client: ``` import paho.mqtt.client as mqtt import time client = mqtt.Client('DataReaderPub') c...
When I ran your code, the subscriber was often missing the last packet. I was not otherwise able to reproduce the problems you described. If I rewrite the publisher like this instead... ``` from time import sleep import paho.mqtt.client as mqtt client = mqtt.Client('DataReaderPub') client.connect('127.0.0.1', 1883, ...
10,492
47,486,930
The following script generates a 2d list in python: ``` matrix = [[0 for row in range (5)] for col in range (5)] i = 2 matrix[i][i] = 1 matrix[i+1][i] = 1 matrix[i][i+1] = 1 matrix[i+1][i+1] = 1 for row in matrix: for item in row: print(item,end=" ") print() print() ``` The generated 2d list...
2017/11/25
[ "https://Stackoverflow.com/questions/47486930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3913519/" ]
In order for this combination to work you need to make sure your `virtual-repeat-container` is kept in sync. If you write a simple 'refresh' function that gets called on open select: ``` function () { return $timeout(function () { $scope.$broadcast("$md-resize"); }, 100); }; ``` it should be enough. ...
According to <https://github.com/angular/material/issues/10868> this post, different angularjs version has different behaviour. Return $timeout function should have also `window.dispatchEvent(new Event('resize'));` statement. Final $timeout function looks like this. ``` return $timeout(function() { $scope.$broadca...
10,494
55,399,396
My searches lead me to the Pywin32 which should be able to mute/unmute the sound and detect its state (on Windows 10, using Python 3+). I found a way using an AutoHotkey script, but I'm looking for a pythonic way. More specifically, I'm not interested in playing with the Windows GUI. *Pywin32 works using a Windows DLL...
2019/03/28
[ "https://Stackoverflow.com/questions/55399396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7227370/" ]
You can use the Windows Sound Manager by paradoxis (<https://github.com/Paradoxis/Windows-Sound-Manager>). ``` from sound import Sound Sound.mute() ``` Every call to `Sound.mute()` will toggle mute on or off. Have a look at the `main.py` to see how to use the setter and getter methods.
If you're also building a GUI, wxPython (and I would believe other GUI frameworks) have access to the windows audio mute "button".
10,495
10,868,410
I'm a little new to web crawlers and such, though I've been programming for a year already. So please bear with me as I try to explain my problem here. I'm parsing info from Yahoo! News, and I've managed to get most of what I want, but there's a little portion that has stumped me. For example: <http://news.yahoo.com/...
2012/06/03
[ "https://Stackoverflow.com/questions/10868410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1433227/" ]
The page is being generated via JavaScript. Check if there is a mobile version of the website first. If not, check for any APIs or RSS/Atom feeds. If there's *nothing* else, you'll either have to manually figure out what the JavaScript is loading and from where, or use [Selenium](http://seleniumhq.org/) to automate a ...
Using the Web Console in Firefox you can pretty easily see what requests the page is actually making as it runs its scripts, and figure out what URI returns the data you want. Then you can request that URI directly in your Python script and tease the data out of it. It is probably in a format that Python already has a ...
10,496
46,382,384
I'm playing around with [Chalice](http://chalice.readthedocs.io/en/latest/) for the first time as I am trying to evaluate it as a possible replacement framework to migrate my existing Python Flask APIs from EC2 to Lambda. From an Amazon Linux EC2 instance, I added some dependencies to a virtualenv I'm playing with. I ...
2017/09/23
[ "https://Stackoverflow.com/questions/46382384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2620746/" ]
You can remove "MySQL-python==1.2.5" from your requirements.txt (since it's already present in your vendor directory) See this [issue](https://github.com/aws/chalice/issues/626) in the Chalice repo for more info.
Looking at what you have in your directory listing you provided, I noticed you don't have a **init**.py file. This file identifies the folder as a library file. Put that in your vendors directory.
10,497
61,874,962
Running into installation error in python 3.8 for tensorflow and i'm wondering how to downgrade without losing my environments in pycharm.
2020/05/18
[ "https://Stackoverflow.com/questions/61874962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13435259/" ]
1. [Download](https://www.python.org/downloads/) and install Python 3.7 2. In PyCharm, go to 'File' -> 'Settings' -> 'Project: <...>' -> 'Project Interpreter', and select 'Python 3.7' in the 'Project Interpreter' dropdown. 3. If you don't see it, click on the settings icon next to it, go to the 'System Interpreter' tab...
Step1 : **Go to Preferences:** [![enter image description here](https://i.stack.imgur.com/IBt7K.png)](https://i.stack.imgur.com/IBt7K.png) Step 2: Go to Python Interpreter [![enter image description here](https://i.stack.imgur.com/S5bVB.png)](https://i.stack.imgur.com/S5bVB.png) Step 3: click Show All [![enter ima...
10,498
61,353,951
I have tried to install Facebook Prophet in Anaconda on Ubuntu following the instructions at: <https://facebook.github.io/prophet/docs/installation.html#installation-in-python>. In Anaconda Navigator, when I click on the environment, fbprophet is listed along with the other installed packages. The problem is that whe...
2020/04/21
[ "https://Stackoverflow.com/questions/61353951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9415043/" ]
It seems that you have installed the package in a separate environment in anaconda. I think when you are running jupyter notebook, it is running from the base environment, But actually you need to run it from the library environment. So if the case is this you need to install jupyter notebook in the other environment a...
Recently the fbprophet project renamed to prophet. If you are referring to it using old name you should install the old version. ``` pip/conda/mamba/whatever install prophet ```
10,500
21,866,036
When I import a subpackage in a package, can I rely on the fact that the parent package is also imported ? e.g. this works ``` python -c "import os.path; print os.getcwd()" ``` Shouldn't I explicitly `import os` for `os.getcwd` to be available ?
2014/02/18
[ "https://Stackoverflow.com/questions/21866036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/346286/" ]
It works and it is reliable. What happens under the hood is when you do ``` import os.path ``` then `os` gets imported and then `os.path`.
Yes, you can rely on it always working. Python has to include `os` in the namespace for `os.path` to work. What won't work is using the `from os import path` notation. In that case, the os module is *not* brought into the namespace, only `path`.
10,506
57,076,851
I want to plot a bode plot of a system with the python control systems library. This is fairly easy. The problem is the plot of the margins. It is no problem to plot the phase margin. But how can I plot the gain margin? So far, this is a part of my code: ```py import control as cn %matplotlib notebook import matplotl...
2019/07/17
[ "https://Stackoverflow.com/questions/57076851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6883478/" ]
Not the most elegant solution but hey it works for me. ``` ###Import modules import numpy as np import control as ctl import matplotlib.pyplot as plt ##Functions def plot_margins(sys): mag,phase,omega = ctl.bode(sys,dB=True,Plot=False) magdB = 20*np.log10(mag) phase_deg = phase*180.0/np.pi Gm,Pm,Wcg,W...
Starting in version 0.8 of `control`, the [`bode_plot`](https://python-control.readthedocs.io/en/0.8.3/generated/control.bode_plot.html) function (also aliased as `bode`) has an option to plot margins. ```py import control sys = control.tf([1], [1, 1]) # example transfer function control.bode_plot(sys, margins=True)...
10,511
467,602
Following from this [OS-agnostic question](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python), specifically [this response](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291), similar to data available from the likes of /proc/meminfo o...
2009/01/22
[ "https://Stackoverflow.com/questions/467602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2183/" ]
There was a similar question asked: [How to get current CPU and RAM usage in Python?](https://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage-in-python) There are quite a few answers telling you how to accomplish this in windows.
You can try using the systeminfo.exe wrapper I created a while back, it's a bit unorthodox but it seems to do the trick easily enough and without much code. This should work on 2000/XP/2003 Server, and should work on Vista and Win7 provided they come with systeminfo.exe and it is located on the path. ``` import os, r...
10,512
19,890,824
How to store the get Facebook profile picture of a user while logging in through Facebook and saving it in my userprofile model. I found this link which says how to do so using django-social-auth, <https://gist.github.com/kalamhavij/1662930>. but signals is now deprecated and I have to use pipeline. Any idea how can ...
2013/11/10
[ "https://Stackoverflow.com/questions/19890824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/683634/" ]
This is how it worked with me. (from <https://github.com/omab/python-social-auth/issues/80>) Add the following code to pipeline.py: ``` from requests import request, HTTPError from django.core.files.base import ContentFile def save_profile_picture(strategy, user, response, details, is_new=F...
Assuming you already configured `SOCIAL_AUTH_PIPELINE`, there aren't many differences with signals approach. Just create needed pipeline (skipping all imports, they're obvious) ``` def update_avatar(backend, details, response, social_user, uid,\ user, *args, **kwargs): if backend.__class__ == F...
10,517
70,543,710
I am learning C# and have been taking a lot of online courses. I am looking for a simpler/neater way to enumerate a list within a list. In python we can do something like this in just one line: ``` newListofList=[[n,i] for n,i in enumerate([List1,List2,List3])] ``` Does it have to involve lambda and Linq in C#? if ...
2021/12/31
[ "https://Stackoverflow.com/questions/70543710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740222/" ]
Just a *constructor* will be enough: ``` List<List<string>> familyListss = new List<List<string>>() { new List<string> { "Mary", "Mary_sister", "Mary_father", "Mary_mother", "Mary_brother" }, new List<string> { "Peter", "Peter_sister", "Peter_father", "Peter_mother", "Peter_brother" }, new List<string> { "John",...
Are you taking about something like this? ``` int i = 0; familyListss.ForEach(f => { familyData.Add(i, f);i++; }); ``` This is refactored from ``` int i = 0; foreach (var f in familyListss) { familyData.Add(i, f); i++; } ``` With a small extension method, you can build in an index to foreach to make it o...
10,520
3,234,402
Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ?
2010/07/13
[ "https://Stackoverflow.com/questions/3234402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215939/" ]
Yes, you can. I started learning Django with very little Python knowledge too. As long as you have another language behind your belt, preferably a web based one (as you do), I don't think you're biting off too much at once. Python's a pretty easy language to pick up too. Just have to get used to the significant white ...
Sure you can! Django requires minimal knowledge about using python from the command line, but if you're comfortable with that, then there shouldn't be an issue. Django has excellent documentation and a good tutorial aimed at beginners that does not expect you to be a high-level Python programmer. Here's the link to th...
10,521
33,615,096
How can I use single quote and double quote same time as string python? For example: ``` string = "Let's print "Happines" out" ``` result should be Let's print `"Happines"` out I tried to use backslash but it prints out a `\` before 's that should be.
2015/11/09
[ "https://Stackoverflow.com/questions/33615096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5230597/" ]
In python there's lots of ways to write string literals. For this example you can: ``` print('Let\'s print "Happiness" out') print("Let's print \"Happiness\" out") print('''Let's print "Happiness" out''') print("""Let's print "Happiness" out""") ``` Any of the above will behave as expected.
Taking this string: ``` string = "Let's print "Happines" out" ``` If you want to mix quotes, use the triple single quotes: ``` >>> string = '''Let's print "Happines" out''' >>> print(string) Let's print "Happines" out ``` Using triple quotes is acceptable too: ``` >>> string = """Let's print "Happines" out"""...
10,530
61,501,891
I have an issue with Rsyslog's 'omprog' module when trying to get it to interact with my python (2.7) code. Rsyslog is supposed to send desired messages to python's stdin, yet it does not receive anything. I wonder if anyone else has had better success with this output module? **Rsyslog.conf** ``` module(load="omprog...
2020/04/29
[ "https://Stackoverflow.com/questions/61501891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10192040/" ]
Here is one approach using `tidyverse`. You can `group_by(Species)` and set `Method` to "Both" if both Bottom fishing and Trolling are included in Method within that Species. Then afterwards, you can `group_by` both Species and Method, and use `fill` to replace `NA` with known values. In the end, use `slice` to keep on...
This should get you started. You can add the other columns to the summarize function. ``` library(tidyverse) fish_catch %>% select(-Bait, -Released, -Kept) %>% group_by(Species) %>% summarize(Method = paste0(Method, collapse = "")) %>% mutate(Method = fct_recode(Method, "both" = "TrollingBottom fishing")) #...
10,531
8,011,017
Simple problem, how to find the first non-zero digit after decimal point. What I really need is the distance between the decimal point and the first non-zero digit. I know I could do it with a few lines but I'd like to have some pythonic, nice and clean way to solve this. So far I have this ``` >>> t = [(123.0, 2), ...
2011/11/04
[ "https://Stackoverflow.com/questions/8011017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/181337/" ]
The easiest way seems to be ``` x = 123.0 dist = int(math.log10(abs(x))) ``` I interpreted the second entry in each pair of the list `t` as your desired result, so I chose `int()` to round the logarithm towards zero: ``` >>> [(int(math.log10(abs(x))), y) for x, y in t] [(2, 2), (1, 1), (0, 0), (0, 0), (-1, -1), (-4...
One way to focus on the digits after the decimal point is to remove the integer part of the number, leaving on the fractional part, with something like `x - int(x)`. Having isolated the fractional part, you could let python do the counting for you with a `%e` presentation (that also helps take care of rounding issues)...
10,532
46,215,954
I get a .csv file with values inside and one of the columns contains durations in the format hh:mm:ss for example 06:42:13 (6 hours, 42 minutes and 13 seconds). Now I want to compare this time with a given time for example 00:00:00 because I have to handle the information in that row different. time is the value I got...
2017/09/14
[ "https://Stackoverflow.com/questions/46215954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8592446/" ]
Do this instead: ``` if time.strip() == "00:00:00": do something else: do something different ```
Instead of doing string comparisions, using inbuilt `datetime` library to create datetime objects. Use [`datetime.strptime`](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior) to convert date string.
10,538
22,599,617
How do i fix this error, this is the message that i get: ```none Traceback (most recent call last): File "C:\Users\Games\Desktop\hendeagon.py", line 28, in <module> font = pygame.font.SysFont(None, 48) File "C:\Python33\lib\site-packages\pygame\sysfont.py", line 614, in SysFont return constructor(fontname, size, set_b...
2014/03/24
[ "https://Stackoverflow.com/questions/22599617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3453049/" ]
[`.attr()`](https://api.jquery.com/attr/) is for HTML attributes, not for CSS properties. You're looking for [`.css()`](http://api.jquery.com/css/): ``` var cssProp = $(this).css('text-decoration'); // Gets the CSS property's value $(this).css('text-decoration', 'line-through'); // Sets the CSS property's value ```
Text decoration isn't an attribute it's a CSS value. Attributes are things like href, class and id on an HTML element. Try this: ``` $(this).css("text-decoration", "line-through"); ```
10,541
68,171,360
I am trying to create a Neural Network class made up of Neuron objects wired together. My Neuron class has 1. **Dendrites** The number of dendrites is specified in the parameters when the class is initialised. The Dendrites are stored in a list whose index stores the voltages of each Dendrite. eg: `neuron1.dendrit...
2021/06/29
[ "https://Stackoverflow.com/questions/68171360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5618307/" ]
Might not be the best solution, but just my 2c. If you want the other neuron's dendrites to be updated as well, you can declare the connections like so: ``` axonConns = [(n1.dendrites, 0), (n2.dendrites, 1), (n3.dendrites, 2)] ``` You need to pass the list of the dendrites itself, and define which of the dendrites a...
You aren't properly reassigning the values of outputDendrites in your class method. ``` def fire(self): self.outputPotential = self.voltsOut self.firing = self.on print("Neuron is firing!") # Store the axonConnections into a temporary list for parsing since we'll be changing the values WHILE interating...
10,542
56,577,890
I am trying to run GitLab's job using their shared Runners, I've created a `.gitlab-ci.yml` and kept it at my project's root, Configured AWS creds as the environment variables - ``` AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_DEFAULT_REGION ``` under `Settings -> CI / CD -> Variables` [![enter image descript...
2019/06/13
[ "https://Stackoverflow.com/questions/56577890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5433178/" ]
You can use ``` - pip install awscli - aws configure set aws_access_key_id $AWS_ACCESS_KEY_ID - aws configure set aws_secret_access_key $AWS_SECRET_ACCESS_KEY - aws configure set region $AWS_DEFAULT_REGION ``` instead of ``` - mkdir ~/.aws/ - touch ~/.aws/credentials - pip install awscli - printf "[eb-cli]\naws_acc...
In your code, the profile is set to 'eb-cli' for your credentials ``` printf "[eb-cli]\naws_access_key_id = %s\naws_secret_access_key = %s\nregion = %s\n" "$AWS_ACCESS_KEY_ID" "$AWS_SECRET_ACCESS_KEY" "$AWS_DEFAULT_REGION" >> ~/.aws/credentials ``` The command you should use is ``` aws s3 ls --profile eb-cli ``` ...
10,545
6,074,034
I wish to execute os.system('ls') in python. the return value of this statement is an error code integer..but I want to get the contents of the present directory as a string. How to accomplish this?
2011/05/20
[ "https://Stackoverflow.com/questions/6074034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/748051/" ]
[`os.listdir(".")`](http://docs.python.org/library/os.html#os.listdir) --- In general, if you want to call a function and get the arguments, you should use [`subprocess.Popen()`](http://docs.python.org/library/subprocess.html#subprocess.Popen). But a lot of the basic directory stuff is in the `os` module so you don't...
Python as build-in functionality like os.listdir() or os.walk() for listing stuff on the filesystem. Running 'ls' yourself is very bad-style. In general look at the documentation of the subprocess module giving you all flexibility for interacting with external commands.
10,546
69,563,630
I have a huge python list as the following example: ``` ls = ['name: John', 'John has ', '4 yellow ', 'cars.', 'name: Angelina', 'Angelina has ', '5 yellow', 'cars.'] ``` I would like to join this information in this formatting: ``` ls = ['name: John', 'John has 4 yellow cars.', 'name: Angelina', 'Angelina has 5 ye...
2021/10/14
[ "https://Stackoverflow.com/questions/69563630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11601412/" ]
You can use `itertools.groupby`: ```py import itertools ls = ['name: John', 'John has ', '4 yellow ', 'cars.', 'name: Angelina', 'Angelina has ', '5 yellow', 'cars.'] g = itertools.groupby(ls, lambda x: x.startswith('name: ')) output = [''.join(v) for _, v in g] print(output) # ['name: John', 'John has 4 yellow cars...
Concatenate all the lines that don't begin with `name:` in a variable, then append that to the result when you get to the next `name:` line. ``` ls2 = [] temp_string = '' for line in lines: line = line.rstrip('\n') if line.startswith('name:'): if temp_string: ls2.append(temp_string) ...
10,547
70,658,581
I am looking to create accounts on Brownie for deploying contracts but I am not sure how to do this. I have looked online how to do this and I havent found it. I am running python 3.7 and have brownie installed and working as intended. I have also run brownie using a gnache cli. Any help would be great!
2022/01/10
[ "https://Stackoverflow.com/questions/70658581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17855149/" ]
To create accounts on brownie use ``` brownie accounts new account-name ``` you can then add your private key as well as password encrypt. You can check to see if this account was made correctly using ``` brownie accounts list ```
I understand that you are trying to add accounts through the brownie ./scripts folder: add.py ``` from brownie import accounts def add_account(): print(len(accounts) for i in range(10): accounts.add() #adds a random account with mnemonic & address to the network print(len(accounts)) def main(): ...
10,550
51,666,871
I have a flask app with a single file (app.py) a large code base size of 6K lines which i want to modularize by making Separate files for each group of route handlers. Which one is the proper approach creating Class for similar routes like user and giving member functions like login, register user.py ``` class User: ...
2018/08/03
[ "https://Stackoverflow.com/questions/51666871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2547270/" ]
You should almost never use classes for flask routes as they are inherantly static, and so are not really suited for having instances made of them The easiest solution is just to separate related routes into modules, as shown in the second part of your question. If I were you I would also look into Flask's blueprints...
The latter is Pythonic. Don't use classes when you don't need instance data; use modules.
10,551
66,421,969
I have a main folder with some .xlsx, .ipynb, .jpeg and some subfolders in it. Now I want to convert all my .xlsx files in my main folder to PDFs. It is a routine work that I have to do everyday, I would appreciate if you teach me how to do it in python. \*all the files have some data in the first sheet of the workbo...
2021/03/01
[ "https://Stackoverflow.com/questions/66421969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13403801/" ]
Is there anything you have already tried ? I suggest testing out pywin32. 1. Download pywin32 ```sh python3 -m pip install pywin32 ``` 2. Write a script to automate. ```py import win32com.client from pywintypes import com_error # Path to original excel file WB_PATH = r'~/path/to/file.xlsx' # PDF path when saving...
try like this : ``` saveFormat = self.SaveFormat workbook = self.Workbook(self.dataDir + "Book1.xls") #Save the document in PDF format workbook.save(self.dataDir + "OutBook1.pdf", saveFormat.PDF) \# Print message print "\n Excel to PDF conversion performed successfully." ```
10,552
48,924,007
I am trying to compare two `strings` in `python 3.6` and if they are not equal then print a message and exit. My current code is: ``` location = 'United States of America' if location.lower() != 'united states of america' or location.lower() != 'usa': print('Location was different = {}'.format(location.lower())) ...
2018/02/22
[ "https://Stackoverflow.com/questions/48924007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2966197/" ]
Your condition: ``` if location.lower() != 'united states of america' or location.lower() != 'usa': ``` will never be `False`, since `location.lower()` can't be 2 different strings at the same time. I suspect you want: ``` if location.lower() != 'united states of america' and location.lower() != 'usa': ```
You are looking for an AND condition instead of a OR condition in your if statement. If you change that you should be set
10,553
13,348,880
I am trying to compile the source codes for a simulator which uses C++ and Python. However, it gives me this error: ``` Error: can't find Python.h header in ['path-to-my-python/include/python2.6'] Install Python headers (package python-dev on Ubuntu and RedHat) ``` However, I can see that the header file is there an...
2012/11/12
[ "https://Stackoverflow.com/questions/13348880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1762469/" ]
I have written my own AutoCompleteBox control, available at <https://github.com/igorkulman/AutoCompleteBox>
I don't think there is anything built in, but have you checked open source? This was the first thing that showed up when I binged for it on google: <http://autocompleteboxwinrt.codeplex.com/SourceControl/changeset/view/19567>
10,554
73,829,933
I have a dataframe ``` import pandas as pd data_as_dict={'CHROM': {232: 1, 233: 1, 234: 1, 10: 'chr15', 11: 'chr15'}, 'POS_GRCh38': {232: 10506158, 233: 109655507, 234: 113903258, 10: '67165147', 11: '67163292'}, 'REF': {232: 'G', 233: 'CAAA', 234: 'G', 10: 'G', 11: 'C'}, 'Effect_allele': {232: 'A', 233: 'C', 234:...
2022/09/23
[ "https://Stackoverflow.com/questions/73829933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4701887/" ]
Assuming you want to print every 5th line starting from a specific line number: ``` $ seq 20 | awk 'NR==4{c=4} c && !((++c) % 5)' 4 9 14 19 $ seq 20 | awk 'NR==2{c=4} c && !((++c) % 5)' 2 7 12 17 $ seq 20 | awk 'NR==6{c=4} c && !((++c) % 5)' 6 11 16 ``` `c && !((++c) % 5)` says: > > If `c` is set then increment ...
Simply ``` awk 'NR%5 == 4' file ``` will do the job. Alternatively, if you have GNU `sed`: ``` sed -n 4~5p file ``` --- **Edit:** A general solution to the problem of printing every *n*th line starting with line *s* using `awk` could be, for example, like that: ``` awk -v s=6 -v n=5 'NR>=s && NR%n == s%n' fi...
10,556
45,182,153
I saw at [concurrency is not parallelism](https://blog.golang.org/concurrency-is-not-parallelism) slide that golang can do like this: ``` func main() { go boring("Boring!") fmt.Println("I'm listening.") time.Sleep(2 * time.Second) fmt.Println("You're boring; I'm leaving.") } ``` The result look like ...
2017/07/19
[ "https://Stackoverflow.com/questions/45182153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8218546/" ]
Instead of sleeping after running run\_until\_complete, you can use [timeouts](https://docs.python.org/3/library/asyncio-task.html#timeouts). This way, it would be something like: ``` async def main(): print('Hello') try: await asyncio.wait_for(boring('boring!'), timeout=2.0) print('Maybe not t...
`loop.run_forever()` if blocking the execution. As your code is running in a single thread, you need to modify your code to something like this: ``` async def boring(msg): for i in itertools.count(0): print(msg, i) await asyncio.sleep(random.random() % 1e3) async def hello(task): print('Hello...
10,566
714,242
What are your opinions and expectations on [Google's Unladen Swallow](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)? From their project plan: > > We want to make Python faster, but we > also want to make it easy for large, > well-established applications to > switch to Unladen Swallow. > > > 1. Prod...
2009/04/03
[ "https://Stackoverflow.com/questions/714242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/60711/" ]
I have high hopes for it. 1. This is being worked on by several people from Google. Seeing as how the BDFL is also employed there, this is a positive. 2. Off the bat, they state that this is a branch, and not a fork. As such, it's within the realm of possibility that this will eventually get merged into trunk. 3. Most...
I'm sorry to disappoint you, but when you read [PEP 3146](http://www.python.org/dev/peps/pep-3146/) things look bad. The improvement is by now minimal and therfore the compiler-code gets more complicated. Also removing the GIL has many downsides. Btw. PyPy seems to be faster then Unladen Swallow in [some tests](http:...
10,567
53,799,912
Iam trying to pre-process text as a part of NLP.I am new to it.I am not getting why i am unable to replace the digits ``` para = "support leaders around the world who do not speak for the big polluters, but who speak for all of humanity, for the indigenous people of the world, for the first 100 people.In 90's it see...
2018/12/16
[ "https://Stackoverflow.com/questions/53799912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464351/" ]
For replacing all digits from a string, you can the `re` module, for matching and replacing regex patterns. From your last example: ``` import re processed_words = [re.sub('\d',' ', word) for word in tokenized] ```
Is this what you want to do? Or am I missing the point? ``` import re para = """support leaders around the world who do not speak for the big polluters, but who speak for all of humanity, for the indigenous people of the world, for the first 100 people.In 90's it seems true.""" tokenized = para.split(' ') new_para...
10,577
47,740,542
``` def lines(file): for line in file: yield line yield '\n' def blocks(file): block = [] for line in lines(file): if line.strip(): block.append(line) elif block: yield ''.join(block).strip() block = [] with open(r'test_input.txt', 'r') as f:...
2017/12/10
[ "https://Stackoverflow.com/questions/47740542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9080044/" ]
Your issue is caused by this line: ``` lines = lines(f) ``` With this assignment, you're overwriting the `lines` generator function with its own return value. That means that when `blocks` tries to call `lines` again (which seems a little buggy to me, but not the main issue), it gets the generator object instead of ...
Your problem is not related to Python3. This error exists with Python 2.6. I do not know exactly what you try to do but your code do not throws error replacing `blocks` function with : ``` def blocks(file): block = [] for line in file: # here, replace lines(file) with file if line.strip(): ...
10,580
27,224,458
I'm using Python's Scrapy to do some web scraping, and I'm trying to get the text in the last td of my last tr in the html below. ``` <table class="infobox" style="float: right; width: 225px; text-align: left; -moz-border-radius:10px; font-size: 85%" cellpadding="2"> <tr style="vertical-align: top;"> <td>...
2014/12/01
[ "https://Stackoverflow.com/questions/27224458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3892678/" ]
You should create user because tests create test database (not your) everytime. ``` User.objects.create_user(username=<client_username>, password=<client_password>) ``` Now create Client and login ``` self.c = django.test.client.Client() self.c.login(username=<client_username>, password=<client_password>) ```
You can override request headers for every client request like this example: ``` def test_report_wrong_password(self): headers = dict() headers['HTTP_AUTHORIZATION'] = 'Basic ' + base64.b64encode('user_name:password') response = self.client.post( '/report/', content_type='application/json',...
10,581
1,897,939
I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example: ``` from twisted.protocols import basic class MyChat(basic.LineReceiver): ...
2009/12/13
[ "https://Stackoverflow.com/questions/1897939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117603/" ]
Don't confuse "Twisted" with "`twistd`". When you use "`twistd`", you *are* running the program with Python. "`twistd`" is a Python program that, among other things, can load an application from a `.tac` file (as you're doing here). The "Twisted Command Prompt" is a Twisted installer-provided convenience to help out p...
Maybe one of `run` or `runApp` in [twisted.scripts.twistd](http://twistedmatrix.com/documents/9.0.0/api/twisted.scripts.twistd.html) modules will work for you. Please let me know if it does, it will be nice to know!
10,582
57,652,922
Say I want to use [black](https://black.readthedocs.io/en/stable/index.html) as an API, and do something like: ``` import black black.format("some python code") ``` Formatting code by calling the `black` binary with `Popen` is an alternative, but that's not what I'm asking.
2019/08/26
[ "https://Stackoverflow.com/questions/57652922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2142577/" ]
You could try using `format_str`: ``` from black import format_str, FileMode res = format_str("some python code", mode=FileMode()) print(res) ```
Use `black.format_file_contents`. *e.g.* ```py import black mode = black.FileMode() fast = False out = black.format_file_contents("some python code", fast, mode) ``` <https://github.com/psf/black/blob/19.3b0/black.py#L642>
10,592
38,788,816
I need to install dryscrape for python but I got error, what's the problem? ``` C:\Users\parvij\Anaconda3\Scripts>pip install dryscrape ``` I got this: ``` Collecting dryscrape Collecting webkit-server>=1.0 (from dryscrape) Using cached webkit-server-1.0.tar.gz Collecting xvfbwrapper (from dryscrape) Requirement ...
2016/08/05
[ "https://Stackoverflow.com/questions/38788816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4042278/" ]
Need to install <http://www.qt.io>. Also, The 5.6+ version of Qt removes the Qt WebKit module in favor of the new module Qt WebEngine. So far, webkit-server has not been ported to WebEngine (and likely won't be in the near future), so Qt <= 5.5 is a requirement.
From the [doc](http://dryscrape.readthedocs.io/en/latest/installation.html), you have to installed also [requirements](https://github.com/niklasb/dryscrape/blob/master/requirements.txt). You can do this as follow ``` pip install -r requirements.txt ``` After this retry to install **dryscrape**.
10,593
33,464,208
Is there a pythonic/efficient way to carry out a simple decrement operation on each element (or more accurately a subset of the elements) in a list of objects of an arbitrary class? I potentially have a large-ish (~ 10K) list of objects, each of which is updated periodically on the basis of a countdown "time to updat...
2015/11/01
[ "https://Stackoverflow.com/questions/33464208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1171112/" ]
Perhaps you could replace your flat list with a priority queue using the `heapq` module. The priorities would be the current time, plus the object's `ttu`. When the current time matched the top element's priority, you'd pop it off, do whatever your updating was, and then push it back into the queue with a new priority....
I think your code is already good; maybe you could add a single method called something like "beat" for performing both things: * checking if the object is ready to update and in that case handle the update, * or decrement in the other case; it would make your loop a little cleaner and simpler. It won't help much for...
10,598
39,029,068
I want to be able to execute the following code: ``` import numpy z=numpy.zeros(4) k="z[i-1]" for i in range(len(b)): z[i]=k ``` Which should return the same output as: ``` z=numpy.zeros(4) for i in range(6): z[i]=z[i-1] ``` If I execute the first code block, I get an expected error message: ``` File "...
2016/08/18
[ "https://Stackoverflow.com/questions/39029068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5510581/" ]
I think you're looking for the [builtin `eval()`](https://docs.python.org/2/library/functions.html#eval) Consider: ``` >>> z = numpy.zeros(4) >>> k = "10 + z[i-1]" >>> for i in range(1, 4): ... z[i] = eval(k) ... >>> z array([ 0., 10., 20., 30.]) ``` I made the expression a little more complex so you could ...
Do it as following: ``` import numpy z=numpy.zeros(4) k="z[i-1]" for i in range(len(b)): z[i]=eval(k) ``` But note eval can be a security problem: <http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html>
10,599
36,716,304
Im stuck with this very simple code were I'm trying to create a function that takes a parameter and adds 1 to the result and returns it but somehow this code gives me no results. (I've called the function to see if it works.) Somebody please help me since I'm very new to python :) ``` def increment(num): num += 1...
2016/04/19
[ "https://Stackoverflow.com/questions/36716304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6123798/" ]
Basics: `array[slice(a,b,c)]` is equivalent to `array[a:b:c]`, and to reverse ("flip") an array use `slice(None, None, -1)`, which is the same as `array[::-1]`. So let's build the random flips for each image: ``` >>> import random >> flips = [(slice(None, None, None), ... slice(None, None, random.choice([-1,...
Thanks to the [awesome answer of @BlackBear](https://stackoverflow.com/a/36716579/3250126), I was able to get starting. I noticed, however, such functionality would probably run very often and thus might benefit from some performance tweaks. In thinking of how to improve the performance I tackled two things: 1. use a...
10,601
48,789,294
I have a file that contains the raw data for an array of 32-bit floats. I would like to read this data and resemble it to floats and store them in a list. [![enter image description here](https://i.stack.imgur.com/1p1J9.jpg)](https://i.stack.imgur.com/1p1J9.jpg) How can I do this using python? Note: The data origina...
2018/02/14
[ "https://Stackoverflow.com/questions/48789294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1235291/" ]
The standard `struct` module is good for dealing with packed binary data like this. Here's a quick example: ``` dataFromFile = "\x67\x66\x1e\x41\x01\x00\x30\x41" # an excerpt from your data import struct numFloats = len(dataFromFile) // 4 # Try decoding it as little-endian print(struct.unpack("<" + "f" * numFloats...
you can read it the file, store it in a string then parse the string and convert to float: ``` with open(“testfile.txt”) as file: data = file.read() values = data.split(" ") floatValues = [float(x) for x in values] ``` or you can use some parser from the numpy module or the csv reading files modules
10,602
54,073,810
I was trying to get data(a list) from a file and assign this list to my python script list. I want to know how to do it without having to assign all varibles manually ``` Variables = [MPDev,WDev,DDev,LDev,PDev,MPAll,WAll,DAll,LAll,PAll,MPBlit,WBlit,DBlit,LBlit,PBlit,MPCour,WCour,DCour,LCour,PCour] dataupdate = open("...
2019/01/07
[ "https://Stackoverflow.com/questions/54073810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10236621/" ]
Get used to using data as a pandas dataframe. It's easy to read, easy to write. <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html> ``` import pandas as pd data = pd.read_csv("griddata.txt", names = ['MPDev', 'WDev', 'DDev', 'LDev', 'PDev', 'MPAll', 'WAll', 'DAll', 'LAll', 'PAll', 'M...
``` import ast Variables = [MPDev,WDev,DDev,LDev,PDev,MPAll,WAll,DAll,LAll,PAll,MPBlit,WBlit,DBlit,LBlit,PBlit,MPCour,WCour,DCour,LCour,PCour] dataupdate = open("tmp.txt","r") datalist = ast.literal_eval(dataupdate.read()) #Inside the file is written: #['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'...
10,603
58,869,851
I have an issue in using python with matrix multiplication and reshape. for example, I have a column `S` of size `(16,1)` and another matrix `H` of size `(4,4)`, I need to reshape the column `S` into `(4,4)` in order to multiply it with `H` and then reshape it again into `(16,1)`, I did that in matlab as below: ``` c...
2019/11/15
[ "https://Stackoverflow.com/questions/58869851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11082042/" ]
Simply do this: ``` S.shape = (4,4) for ij in range(16): y[:,:,ij] = H[:,:,ij] @ S S.shape = -1 # equivalent to 16 ```
There are two issues in your solution 1) reshape method takes a shape in the form of a single tuple argument, but not multiple arguments. 2) The shape of your y-array should be 16x1x16, not 4x4x16. In Matlab, there is no issue since it automatically reshapes `y` as you update it. The correct version would be the fol...
10,605
31,092,802
To install dependences, the [appengine-python-flask-skeleton docs](https://github.com/GoogleCloudPlatform/appengine-python-flask-skeleton) advise running this command: ``` pip install -r requirements.txt -t lib ``` That works simply enough. Now say I want to add the [Requests package](http://docs.python-requests.or...
2015/06/27
[ "https://Stackoverflow.com/questions/31092802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1093087/" ]
Like said, updating pip solves the issue for many, but for what it's worth I think you can get around all of this if the use of [virtualenv](https://virtualenv.pypa.io/en/latest/) is an option. Symlink `/path/to/virtualenv's/sitepackages/` to `lib/` and just always keep an up to date `requirements.txt` file. There are ...
Upgrading to the latest version of pip solved my problem (that issue had been closed): ``` pip install -U pip ``` Otherwise, as noted in that thread, you can always just wipe out your `lib` directory and reinstall from scratch. One note of warning: if you manually added additional packages to the `lib` directory not...
10,608
54,484,627
I want to monitor EC2 by using CloudWatch-SNS-lambda (python)-SNS-Email. When I testing my python code, i find out that CW alarm "Message" contain escape processing that i cant get specific value from "Message". I check the format of the alarm with code below. ``` from __future__ import print_function import json im...
2019/02/01
[ "https://Stackoverflow.com/questions/54484627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11002216/" ]
The `Message` is a JSON string. You need to convert it to a Python dictionary first. Then, you can access its properties easily. ```py Messagebody = event['Records'][0]['Sns']['Message'] message_dict = json.loads(Messagebody) metric_name = message_dict['Trigger']['MetricName'] ```
To remove the escape-processing, you should do the following: > > MessageBody = event['Records'][0]['Sns']['Message'] > > > MessageBody = json.loads(MessageBody) > > > Then to access the Metric Name, you can do: > > MetricName= event['Records'][0]['Sns']['Message']['Trigger']['MetricName'] > > >
10,609
37,991,717
Can anyone help me on a Python reverse shell one-liner for Windows (has to be windows one-liner). I am trying to modify the one for Linux which I have used many times but this is my first time for Windows. Linux one liner : ``` python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM...
2016/06/23
[ "https://Stackoverflow.com/questions/37991717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803649/" ]
(@rockstar: I think you and I are studying the same thing!) Not a one liner, but learning from David Cullen's answer, I put together this reverse shell for Windows. ``` import os,socket,subprocess,threading; def s2p(s, p): while True: data = s.recv(1024) if len(data) > 0: p.stdin.write...
From the [documentation](https://docs.python.org/2/library/socket.html#socket.socket.fileno) for `socket.fileno()`: > > Under Windows the small integer returned by this method cannot be used where a file descriptor can be used (such as os.fdopen()). Unix does not have this limitation. > > > I do not think you can...
10,610
50,100,629
When I try to run buildout for a existing project, which used to work perfectly fine, it now installs the incorrect version of Django, even though the version is pinned. For some reason, it's installing Django 1.10 even though I've got 1.6 pinned. (I know that's an old version, but client doesn't want me to upgrade ju...
2018/04/30
[ "https://Stackoverflow.com/questions/50100629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/433267/" ]
The reason it wasn't working is because the `[versions]` part cannot be extended
Pip can install a specific version of library using pip, you can try: pip install django==1.6.1
10,615
15,114,329
How do I save an open excel file using python= I currently read the excel workbook using XLRD but I need to save the excel file so any changes the user inputs are read. I have done this using a VBA script from within excel which saves the workbook every x seconds, but this is not ideal.
2013/02/27
[ "https://Stackoverflow.com/questions/15114329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2040544/" ]
This works on API level 10 for expanding ActionView e.g. SearchView ``` MenuItemCompat.expandActionView(mSearchMenuItem); ```
You always have the option of differentiating your solution depending on the current running version: ``` int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) { // pre honeycomb } else { // honeycomb and post } ``` I know this might not be exactly what you are looking for bu...
10,616
29,418,572
I am learning python and am stuck on a tutorial which as far as the guide goes should be working but isn't, i have seen similar questions asked but cant understand how they apply to the code i am following, the code fails at the end of the last line. ``` import os import time source = ["'C:\Users\Administrator\myfile...
2015/04/02
[ "https://Stackoverflow.com/questions/29418572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4707947/" ]
`target_dir` should not be created with brackets. ``` target_dir = 'C:\Users\Administrator\myfile' target = target_dir + os.sep + \ time.strftime('%Y%m%d%H%M%S') + '.zip' ``` --- Incidentally, take care with your backslashes, because they are also used to signify special characters in a string. For exampl...
target\_dir is a list, so in your example you need to do: ``` target = target_dir[0] + os.sep + \ time.strftime('%Y%m%dT%H%M%S') + '.zip' ``` You see that error because you are trying to add a list (target\_list) and strings together, apples and oranges.
10,618
56,251,211
I have a spark DataFrame consisting of 3 columns: `text1`, `text2` and `number`. I want to filter this DataFrame based on the following constraint: ```python (len(text1)+len(text2))>number ``` where `len` returns the number of words in `text1` or in `text2`. I tried the following: ```python common_df = common_df...
2019/05/22
[ "https://Stackoverflow.com/questions/56251211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11205562/" ]
[`pyspark.sql.functions.length()`](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.length) returns the character length of a string. If you want to count the words, you can use [`split()`](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.split) ...
You can use `length` from `pyspark.sql.functions`: ``` common_df[(F.length('text1') + F.length('text2')) > common_df['number']] ``` Note that `[]` is a substitute for `filter()`.
10,620
35,045,038
I installed `pytest` into a virtual environment (using `virtualenv`) and am running it from that virtual environment, but it is not using the packages that I installed in that virtual environment. Instead, it is using the main system packages. (Using `python -m unittest discover`, I can actually run my tests with the r...
2016/01/27
[ "https://Stackoverflow.com/questions/35045038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770429/" ]
In my case I was obliged to leave the venv (deactivate), remove pytest (pip uninstall pytest), enter the venv (source /my/path/to/venv), and then reinstall pytest (pip install pytest). I don't known exacttly why pip refuse to install pytest in venv (it says it already present). I hope this helps
you have to activate your python env every time you want to run your python script, you have several ways to activate it, we assume that your virtualenv is installed under /home/venv : 1- the based one is to run the python with one command line `>>> /home/venv/bin/python <your python file.py>` 2- add this line on th...
10,622
14,279,560
> > **Possible Duplicate:** > > [Is it possible to change the Environment of a parent process in python?](https://stackoverflow.com/questions/263005/is-it-possible-to-change-the-environment-of-a-parent-process-in-python) > > > I am using python 2.4.3. I tried to set my http\_proxy variable. Please see the belo...
2013/01/11
[ "https://Stackoverflow.com/questions/14279560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1970157/" ]
When you run this code, you set the environment variables, its working scope is only within the process. After you exit (exit the interactive mode of python), these environment will be disappear. As your code "os.system("echo $http\_proxy")" indicates, if you want to use these environment variables, you need run exter...
environment variables are not a "global database of settings"; setting the environment here doesn't have any effect there. the exception to this is that programs which invoke other programs can provide a different environment to their child programs. At the shell, when you type ``` [~/]$ FOO=bar baz ``` you're te...
10,628
40,009,858
I have a file called fName.txt in a directory. Running the following Python snippet would add 6 numbers into 3 rows and 2 columns into the text file through executing the loop (containing the snippet) three times. However, I would like to empty the file completely before writing new data into it. (Otherwise running th...
2016/10/12
[ "https://Stackoverflow.com/questions/40009858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6407935/" ]
You are using 'append' mode (`'a'`) to open your file. When this mode is specified, new text is appended to the existing file content. You're looking for the 'write' mode, that is `open(filename, 'w')`. This will override the file contents every time you **open** it.
Using mode 'w' is able to delete the content of the file and overwrite the file but prevents the loop containing the above snippet from printing two more times to produce two more rows of data. In other words, using 'w' mode is not compatible with the code I have given the fact that it is supposed to print into the fil...
10,629
56,701,359
I cannot install fbprophet or gcc7. I have manually installed a precompiled ephem. ``` Running setup.py install for fbprophet ... error ``` I have tried with python 3.6 and 3.7. I have tried running as administrator and without. My anaconda prompt cannot install anything without throwing errors. I would rather use...
2019/06/21
[ "https://Stackoverflow.com/questions/56701359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10005867/" ]
To solve this problem, I uninstalled my existing python 3.7 and anaconda. I re-installed anaconda *with one key difference.* I registered Anaconda as my default Python 3.7 during the Anaconda installation. This lets visual studio, PyDev and other programs automatically detect Anaconda as the primary version to use.
I tried to import fbprophet on Python Anaconda, however, I got some errors. This code works for me.. ``` conda install -c conda-forge/label/cf201901 fbprophet ```
10,630
31,478,962
So I have an array of numbers, and I want to plot how many times each number occurs in the array. X-axis should be the numbers in the array, and y-axis should be the number of times each number occurs in the array. Is there a way to program this in python? Also I have trouble when I try to import numpy or matplotlib.py...
2015/07/17
[ "https://Stackoverflow.com/questions/31478962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5120932/" ]
``` t = [1, 2, 3, 1, 2, 5, 6, 7, 8] #your original list of numbers noDuplicates = list(set(t)) #gets rid of duplicates in your list listOfTuples = [] for number in noDuplicates: count = t.count(number) newTuple = [number, count] listOfTuples.Append(newTuple) ``` This creates a list of tuples where the f...
your best bet would be to create a separate list to keep track of the number of occurrences in your first list where the number you are tracking is the index of the second list. ``` listOfNumbers = [2,3,4,2,6,4,2] listOfOccurrences = range(x) #x-1 is the largest number that should occur in the first list ...
10,640
19,363,736
I've tried using the AWS forums to get help but, oh boy, it's hard to get anything over there. In any case, [the original post](https://forums.aws.amazon.com/thread.jspa?threadID=136256&tstart=0) is still there. Here's the same question. I deployed a Python (Flask) app using Elastic Beanstalk and the Python containe...
2013/10/14
[ "https://Stackoverflow.com/questions/19363736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21420/" ]
I ended up opening a paid case with AWS support and they confirmed it was a bug in the Python container code. As a result of this problem, they have just released (10/25/2013) a new version of the container and any new environments will contain the fix. To fix any of your existing environments... well, you can't. You'...
You can also change the value of the said `/static` alias via the configuration console on your Elastic Beanstalk environment. Under the "Static Files" section, map the virtual path */static* to point to your directory *app/myapp/static/*
10,641
49,911,864
I am trying to convert a 16 bit 3-band RGB GeoTIFF file into an 8 bit 3-band JPEG file. It seems like the `gdal` library should work well for this. **My question is how do I specify the conversion to 8-bit output in the python gdal API, and how do I scale the values in that conversion? Also, how do I check to tell whet...
2018/04/19
[ "https://Stackoverflow.com/questions/49911864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1610428/" ]
You could use **options** like this ``` from osgeo import gdal scale = '-scale min_val max_val' options_list = [ '-ot Byte', '-of JPEG', scale ] options_string = " ".join(options_list) gdal.Translate('test.jpg', 'test.tif', options=options_string) ``` Choose the min and m...
I think the gdal way is to use [`gdal.TranslateOptions()`](http://gdal.org/python/osgeo.gdal-module.html#TranslateOptions). ``` from osgeo import gdal translate_options = gdal.TranslateOptions(format='JPEG', outputType=gdal.GDT_Byte, ...
10,642
57,189,055
I transferred some code from IDLE 3.5 (64 bits) to pycharm (Python 2.7). Most of the code is still working, for example I can import WD\_LINE\_SPACING from docx.enum.text, but for some reason I can't import WD\_ALIGN\_PARAGRAPH. At first, nearly non of the imports worked, but after I did pip install python-docx ...
2019/07/24
[ "https://Stackoverflow.com/questions/57189055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9434244/" ]
You can use this instead: ```py from docx.enum.text import WD_PARAGRAPH_ALIGNMENT ``` and then substitute `WD_PARAGRAPH_ALIGNMENT` wherever `WD_ALIGN_PARAGRAPH` would have appeared before. The reason this is happening is that the actual enum object is named `WD_PARAGRAPH_ALIGNMENT`, and a decorator is applied that ...
If someone uses pylint it can be easily suppressed with `# pylint: disable=E0611` added at the end of the import line.
10,643
55,648,849
I have a problem with a loop in Python. My folder looks like this: ``` |folder_initial |--data_loop |--example1 |--example2 |--example3 |--python_jupyter_notebook ``` I would like to loop through all files in data\_loop, open them, run a simple o...
2019/04/12
[ "https://Stackoverflow.com/questions/55648849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11335403/" ]
let try `margin:0 1px` for `.header` div
This code can fixed your problem but make sure that border width will be 1px fixed, if you want to change border-width you can remove border-width:thin to border:2px solid red; and so on. ``` .border { margin-bottom: 20px; border-radius: 3px; border: 1px #d43f3a solid; border-width: thin; } ```
10,644
24,351,087
I'm currently in the process of finding a nice GUI framework for my new project - and Kivy looks quite good. There are many questions here (like [this one](https://stackoverflow.com/questions/15281239/kivy-hello-world-not-working)) about Kivy requiring OpenGL >2.0 (not accepting 1.4) and problems arising from that. As...
2014/06/22
[ "https://Stackoverflow.com/questions/24351087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3762521/" ]
As mentioned in the comment, I am not going to solve every problem. But the main errors. Let the player be responsible for its position, not the game. Furthermore, I would make the player responsible for drawing itself, but that goes a bit too far for this answer. The following code should at least work. ``` public ...
The key solution which Nico included is just that you using the original rectangle coordinates you made when you draw: ``` Rectangle playerPos = new Rectangle( Convert.ToInt32(Player.Pos.X), Convert.ToInt32(Player.Pos.Y), 32, 32); ``` Here you make the rectangle using the players CURRENT ...
10,645
18,584,055
I've got an Ubuntu 12.04 x64 Server edition VM that I'm running python2.7 on and trying to install the MySQLdb package via the command (I've already got `easy_install` installed and working): ``` $ sudo easy_install MySQL-python ``` but I get the following traceback error when easy\_install tries to compile: ``` Tr...
2013/09/03
[ "https://Stackoverflow.com/questions/18584055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281488/" ]
You need to use subquery : ``` SELECT ( SELECT SUM(`total_amount`) FROM `civicrm_contribution` WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) ) - ( SELECT SUM(`fee_amount`) FROM `civicrm_participant` WHERE `contact_id`= (SELECT `id` FR...
You should limit the result of the subquery to 1 otherwise it will result in an error, the best way is to match the name using `'='` instead of `'like'` ``` SELECT ( SELECT SUM(`total_amount`) FROM `civicrm_contribution` WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2...
10,646
3,292,631
I realize that in most cases, it's preferred in Python to just access attributes directly, since there's no real concept of encapsulation like there is in Java and the like. However, I'm wondering if there aren't any exceptions, particularly with abstract classes that have disparate implementations. Let's say I'm writ...
2010/07/20
[ "https://Stackoverflow.com/questions/3292631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262271/" ]
> > Note: I've considered properties, but I don't think they're a cleaner solution. > > > [But they are.](http://docs.python.org/library/functions.html#property) By using properties, you'll have the class signature you want, while being able to use the property as an attribute itself. ``` def _get_id(self): re...
[Only behind a property.](http://www.archive.org/details/SeanKellyRecoveryfromAddiction)
10,650
4,424,342
When using the kwarg-style dict initialization: ``` In [3]: dict(a=1, b=2, c=3) Out[3]: {'a': 1, 'b': 2, 'c': 3} ``` for some reason, defining the key 'from' raises a syntax error: ``` In [4]: dict(to=0, from=1) ------------------------------------------------------------ File "<ipython console>", line 1 di...
2010/12/12
[ "https://Stackoverflow.com/questions/4424342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/226037/" ]
from is a keyword: ``` from threading import Thread ``` Python doesn't have context-sensitive keywords: A name is either a keyword, or can be used as an identifier. There used to be one exception: "as" used to be special-cased in import statements when it was first introduced, but has since been promoted to "full ke...
you can't use python keywords such as `from` in kwargs
10,659
52,305,578
So I am trying to use: ``` sift = cv2.xfeatures2d.SIFT_create() ``` and it is coming up with this error: ``` cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv_contrib\modules\xfeatures2d\src\sift.cpp:1207: error: (-213:The function/feature is not implemented) This algorithm is patented and is excluded in t...
2018/09/13
[ "https://Stackoverflow.com/questions/52305578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8573126/" ]
I had the same problem. It seems that SIRF and SURF are [no longer available in opencv > 3.4.2.16](https://github.com/DynaSlum/satsense/issues/13). I chose an older opencv-python and opencv-contrib-python versions and solved this problem. Here is the [history version](https://pypi.org/project/opencv-python/#history) ab...
It may be due to a mismatch of opencv version and opencv-contrib version. If you installed opencv from the source using CMake, and the source version is different from the version of opencv-contrib-python, uninstall the current opencv-contrib-python and do `pip install opencv-contrib-python==<version of the source>.X` ...
10,664
1,601,153
I want my custom made Django command to be executed every minute. However it seems like `python /path/to/project/myapp/manage.py mycommand` doesn't seem to work while at the directory `python manage.py mycommand` works perfectly. How can I achieve this ? I use `/etc/crontab` with: ``` ****** root python /path/to/proj...
2009/10/21
[ "https://Stackoverflow.com/questions/1601153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151937/" ]
I think the problem is that cron is going to run your scripts in a "bare" environment, so your DJANGO\_SETTINGS\_MODULE is likely undefined. You may want to wrap this up in a shell script that first defines DJANGO\_SETTINGS\_MODULE Something like this: ``` #!/bin/bash export DJANGO_SETTINGS_MODULE=myproject.settings...
**How to Schedule Django custom Commands on AWS EC-2 Instance?** **Step -1** ``` First, you need to write a .cron file ``` **Step-2** ``` Write your script in .cron file. ``` > > MyScript.cron > > > ``` * * * * * /home/ubuntu/kuzo1/venv/bin/python3 /home/ubuntu/Myproject/manage.py transfer_funds >> /home/ub...
10,669
3,236,983
My program has been written on python 3.1 (it was the biggest mistake I've ever made). Now I want to use a few modules that were written on 2.6. I know that it's possible to specify the interpreter in Unix `#!/usr/bin/python2.6`. But what if I use Windows? Does any way to specify the interpreter exist in Windows? Edi...
2010/07/13
[ "https://Stackoverflow.com/questions/3236983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248814/" ]
If you want to mix in the same runtime both 2.6 and 3.1 you may be interested in [execnet](http://codespeak.net/execnet/). Never tested directly, however * Edit: looking at you comments on another answer, I understood better the question
Maybe "Open with..." + 'Remember my choice' in context menu of explorer?
10,679
39,654,224
I am trying to come up with a neat way of doing this in python. I have a list of pairs of alphabets and numbers that look like this : ``` [(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)] ``` What I want to do is to create a new list for each alphabet and append all the numerical values to it. So, output sho...
2016/09/23
[ "https://Stackoverflow.com/questions/39654224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2272156/" ]
``` from collections import defaultdict data = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)] if __name__ == '__main__': result = defaultdict(list) for alphabet, number in data: result[alphabet].append(number) ``` or without collections module: ``` if __name__ == '__main__...
You can use `defaultdict` from the `collections` module for this: ``` from collections import defaultdict l = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)] d = defaultdict(list) for k,v in l: d[k].append(v) for k,v in d.items(): exec(k + "list=" + str(v)) ```
10,686
65,676,114
From one file, I'm trying to import and initialize a class from another file, where that class is initialized with a global variable defined in the calling file. My file setup looks like this. ``` folder ├──subfolder │ └── __init__.py │ └── sub.py ├──__init__.py ├──orig.py ``` My `orig.py` file looks like thi...
2021/01/11
[ "https://Stackoverflow.com/questions/65676114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3259896/" ]
You have got your program almost right. The only challenge I see is with resetting the variable `digit_total = 0` after each iteration. ``` def digital_root(n): n_str = str(n) while len(n_str) != 1: digit_total = 0 #move this inside the while loop for digit in n_str: digit_total += ...
Alex, running a recursive function would always be better than a while loop in such scenarios. Try this : ``` def digital_root(n): n=sum([int(i) for i in str(n)]) if len(str(n))==1: print(n) else: digital_root(n) ```
10,692
70,995,571
Im still VERY NEW to programming and python...Any help would be GREATLY appreciated.. I am doing a BMI calculator in my python class.. I actually got it working the way the instructor wanted but I wanted to just improve it slightly and I had no idea it was going to be this difficult. My original code that actually wor...
2022/02/05
[ "https://Stackoverflow.com/questions/70995571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17611193/" ]
Well, it's good that you are providing more information to the user than just printing out the BMI. But in this case, your test wants only a single number as output for validation. Your code is correct but. A few improvements which you can make in your code: ``` height = input("enter your height in m: ") weight = inp...
the testing you are using wants your print to be only the BMI calculated, so the last print should only be ``` print(BMI) ``` or you could try: ``` print("Your BMI is: ", BMI) ```
10,693
50,669,200
![enter image description here](https://i.stack.imgur.com/B0NS3.png) I need your help in understanding the distribution plot. I was going through tutorial on [this link](http://devarea.com/python-machine-learning-example-linear-regression/#.WxQmilMvxsN). At the end of the post they have mentioned: > > We can see fro...
2018/06/03
[ "https://Stackoverflow.com/questions/50669200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8285020/" ]
Reading through your comments, it is difficult to understand where exactly you are having a problem. I'm going to assume it's because you did not know how to write the other initializer due to your first comment: ``` `my object is simple "stuct" and I could not make "(dictionary: data)" -call.` ``` Here's the initia...
I finally found that simply swift firestore sdk still missing that function but it seams like it is in works and you can find discussion about that in [here](https://github.com/firebase/firebase-ios-sdk/issues/627) > > ...We've had something like this on our radar for a bit. Essentially we want to provide an equival...
10,700
21,611,328
I'm trying to unzip a file with `7z.exe` and the password contains special characters on it EX. `&)kra932(lk0¤23` By executing the following command: ``` subprocess.call(['7z.exe', 'x', '-y', '-ps^&)kratsaslkd932(lkasdf930¤23', 'file.zip']) ``` `7z.exe` launches fine but it says the password is wrong. This is a f...
2014/02/06
[ "https://Stackoverflow.com/questions/21611328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2065094/" ]
There is a big security risk in passing the password on the command line. With administrative rights, it is possible to retrieve that information (startup info object) and extract the password. A better solution is to open 7zip as a process, and feed the password into its standard input. Here is an example of a comman...
I'd suggest using a raw string and the shlex module (esp. on Windows) and NOT supporting any encoding other than ASCII. ``` import shlex import subprocess cmd = r'7z.exe x -y -p^&moreASCIIpasswordchars file.zip' subprocess.call(shlex.split(cmd)) ``` Back to the non-ASCII character issue... I'm pretty sure in Pytho...
10,701
74,611,463
I have this code ``` import numpy a=numpy.pad(numpy.empty([8,8]), 1, constant_values=1) print(a) ``` 50% of the times I execute it it prints a normal array, 50% of times it prints this ``` [[ 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.0...
2022/11/29
[ "https://Stackoverflow.com/questions/74611463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15673832/" ]
You can use [apache\_beam.io.jdbc](https://beam.apache.org/releases/pydoc/current/apache_beam.io.jdbc.html) to read from your MySQL database, and the [BigQuery I/O](https://beam.apache.org/documentation/io/built-in/google-bigquery/) to write on BigQuery. Beam knowledge is expected, so I recommend looking at [Apache Be...
If you only want to copy data from `MySQL` to `BigQuery`, you can firstly export your `MySql` data to `Cloud Storage`, then load this file to a `BigQuery` table. I think no need using `Dataflow` in this case because you don't have complex transformations and business logics. It only corresponds to a copy. [Export](ht...
10,703
62,482,387
I have done everything the documentation says to. * I added pip path and it is working but the python command is not working. [Image of path to my python38 DLL](https://i.stack.imgur.com/HSGzo.png) * The pip path which I added: `C:\Users\Harshal\AppData\Local\Programs\Python\Python38\Scripts python path : C:\Users\Ha...
2020/06/20
[ "https://Stackoverflow.com/questions/62482387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10537108/" ]
In some cases, `py` command works as well as `python` command, so you can try `py`: ``` py -V py -m pip # this is for pip, exactly for this python version ```
Add your python to system environment variables like your path. or Reinstall python and check the Add to path Checkbox while installing ``` Add to path ```
10,704
64,652,322
I'm currently struggling with python's bit operations as in python3 there is no difference anymore between 32bit integers (int) and 64bit integers (long). What I want is an **efficient** function that takes any integer and cuts the most significant 32 bits and then converts these 32 bits back to an integer with the co...
2020/11/02
[ "https://Stackoverflow.com/questions/64652322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10684977/" ]
Significantly simpler solution: Let [`ctypes`](https://docs.python.org/3/library/ctypes.html) do the work for you. ``` from ctypes import c_int32 def int32(val): return c_int32(val).value ``` That just constructs a `c_int32` type from the provided Python `int`, which truncates as you desire, then extracts the v...
use bitstring library which is excellent. ``` from bitstring import BitArray x = BitArray(bin='11000100010100010110101011111010') print(x.int) ```
10,705
20,534,999
Here is an example of failure from a shell. ``` >>> from traits.api import Dict >>> d=Dict() >>> d['Foo']='BAR' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'Dict' object does not support item assignment ``` I have been searching all over the web, and there is no indication of...
2013/12/12
[ "https://Stackoverflow.com/questions/20534999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2121874/" ]
I think your basic problem has to do with notification issues for traits that live outside the model object, and not with "how to access those objects" per se [edit: actually no this is not your problem at all! But it is what I thought you were trying to do when I read your question with my biased mentality towards pro...
Okay, I found the answer (kindof) in this question: [Traits List not reporting items added or removed](https://stackoverflow.com/questions/19041426/traits-list-not-reporting-items-added-or-removed) when including Dict or List objects as attributes in a class one should NOT do it this way: ``` class Foo(HasTraits): ...
10,706
66,047,199
So what i am basically trying to do is groups a set of mongo docs having the same `key:value` pair and return them in the form of a list of list. EX: ``` {"client":"abp","product":"a"},{"client":"aaj","product":"b"},{"client":"abp","product":"c"} ``` Output: ``` {"result": [ [{"client":"abp","product":"a"},{"clien...
2021/02/04
[ "https://Stackoverflow.com/questions/66047199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12408855/" ]
I would group by client and then create and array of product using $push. $push allows you to insert each grouped object in an array. ``` db.yourcollection.aggregate([ { $group: { _id: '$client', products: {$push: {client: '$client', product: '$product'}} } }]) ```
``` from operator import itemgetter from itertools import groupby x=[{"client":"abp","product":"a"},{"client":"aaj","product":"b"},{"client":"abp","product":"c"}] x.sort(key=itemgetter('client'),reverse=True) d=[list(g) for (k,g) in groupby(x,itemgetter('client'))] final = {} final['result']=d Output: {'result': [[{...
10,707
34,651,824
Currently `--resize` flag that I created is boolean, and means that all my objects will be resized: ``` parser.add_argument("--resize", action="store_true", help="Do dictionary resize") # ... # if resize flag is true I'm re-sizing all objects if args.resize: for object in my_obects: object.do_resize() `...
2016/01/07
[ "https://Stackoverflow.com/questions/34651824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/524743/" ]
In order to optionally accept a value, you need to set [`nargs`](https://docs.python.org/2/library/argparse.html#nargs) to `'?'`. This will make the argument consume one value if it is specified. If the argument is specified but without value, then the argument will be assigned the argument’s [`const`](https://docs.pyt...
You can add `default=False`, `const=True` and `nargs='?'` to the argument definition and remove `action`. This way if you don't pass `--resize` it will store False, if you pass `--resize` with no argument will store `True` and otherwise the passed argument. Still you will have to refactor the code a bit to know if you ...
10,708
24,818,096
I am new to python app development. When I tried a code I'm not able to see its output. My sample code is: ``` class name: def __init__(self): x = '' y = '' print x,y ``` When i called the above function like ``` some = name() some.x = 'yeah' some.x.y = 'hell' ``` When i called `some....
2014/07/18
[ "https://Stackoverflow.com/questions/24818096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3843420/" ]
First of all, you are defining the class with the wrong way, you should; ``` class name: def __init__(self): self.x = '' self.y = '' print x,y ``` Then, you are calling the wrong way, you should; ``` some = name() some.x = 'yeah' some.y = 'hell' ``` The problem is, `x` and `y` are `str...
`x` and `y` are two different variables on your instance `some`. When you call `some.x`, you are returning the string `'yeah'`. And then you call `.y`, you are actually trying to do `'yeah'.y`, which is why it says string object has no attribute `y`. So what you want to do is: ``` some = name() some.x = 'hell' some....
10,710
72,462,419
Given a website (for example stackoverflow.com) I want to download all the files under: ``` (Right Click) -> Inspect -> Sources -> Page ``` Please Try it yourself and see the files you get. **How can I do that in python?** I know how to retrive page source but not the source files. I tried searching this multiple ...
2022/06/01
[ "https://Stackoverflow.com/questions/72462419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19248696/" ]
To download website source files (mirroring websites / copy source files from websites) you may try [`PyWebCopy`](https://github.com/rajatomar788/pywebcopy/) library. To save any single page - ``` from pywebcopy import save_webpage save_webpage( url="https://httpbin.org/", project_folder="E://savedpages//...
The easiest way to do this is definitely not with Python. As you seem to know, you can download code to a single site w/ Command click > View Page Source or the sources tab of inspect element. To download all the files in a website's structure, you should use a web-scraper. For Mac, SiteSucker is your best option if ...
10,715
63,158,692
**Summarize the problem:** The Python package basically opens PDFs in batch folder, reads the first page of each PDF, matches keywords, and dumps compatible PDFs in source folder for OCR scripts to kick in. The first script to take all PDFs are **MainBankClass.py**. I am trying to use a docker-compose file to include ...
2020/07/29
[ "https://Stackoverflow.com/questions/63158692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12961386/" ]
> > single application in a single container ... need networks for different py files to communicate > > > You only have one container. Docker networks are for multiple containers to talk to one another. And Docker Compose has a default bridge network defined for all services, so you shouldn't need that if you wer...
So after days of searching regarding my case, I am closing this thread with an implementation of **single application in a single container** suggested on [this link](https://forums.docker.com/t/is-it-possible-to-run-python-package-with-multiple-py-scripts-in-docker-compose-yml/97094/8) from docker forum. Instead of go...
10,716
378,811
I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: ``` 500 Internal Server Error ``` When I check my error logs I see the message ``` Premature end of script headers ``` The only documentation of this error online says that it can be the result of having improper lin...
2008/12/18
[ "https://Stackoverflow.com/questions/378811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47514/" ]
One common error is the wrong path. I my case it was usr/bin/python. The other common error is not transferring the file in ASCII mode. I am using WinSCP where you can set it easily: Go to Options->Preferences->Transfers->click Edit and change the mode to Text. This code should work: ``` #!/usr/bin/python print "Cont...
Sounds to me like you're using a script written in Windows on a Unix machine, without first converting the line-endings from 0d0a to 0a. It should be easy to convert it. One way is with your ftp program; transfer the file in ASCII mode. The way I use with Metapad is to use File->FileFormat before saving.
10,717
58,604,645
I want to get all the installed patches on an `AWS EC2 instance`, So I run this code in `boto3`: ``` response = client.describe_instance_patches(InstanceId=instance_id, Filters=[{'Key': 'State','Values': ['Installed',]} ]) ``` My instance has a patch with a negative timestamp : ``` { "Patches": [ ...
2019/10/29
[ "https://Stackoverflow.com/questions/58604645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2337243/" ]
Assuming this is nothing to with service worker/PWA, the solution could be implemented by returning the front end version by letting the server return the current version of the Vue App everytime. `axiosConfig.js` ``` axios.interceptors.response.use( (resp) => { let fe_version = resp.headers['fe-version'] || 'd...
A possible problem could be that the browser is caching the `index.html` file. Try to disable cache for `index.html` like this: ``` <meta http-equiv="cache-control" content="max-age=0" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="expires" content="0" /> <meta http-equiv="expires" conten...
10,727
49,604,025
I'm trying to translate code that generates a Voronoi Diagram from Javascript into Python. This is a struggle because I don't know Javascript. I think I can sort-of make it out, but I'm still running into issues with things I don't understand. Please help me figure out what is wrong with my code. The code I've written...
2018/04/02
[ "https://Stackoverflow.com/questions/49604025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7944978/" ]
This seems a little bit like homework, so lets try to get you on the right track over outright providing the code to accomplish this. You're going to want to create a loop that performs your code a certain number of times. Let's say we just want to output a certain string 5 times. As an example, here's some really sim...
This worked for me. It creates a table using the .messagebox module. You can enter your name into the entry label. Then, when you click the button it returns "Hello (name)". ``` from tkinter import * from tkinter.messagebox import * master = Tk() label1 = Label(master, text = 'Name:', relief = 'groove', width = 19) e...
10,728
55,927,009
I'm trying to write a script that creates a playlist on my spotify account in python, from scratch and not using a module like *spotipy*. My question is how do I authenticate with my client id and client secret key using the *requests* module or grab an access token using those credentials?
2019/04/30
[ "https://Stackoverflow.com/questions/55927009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9128668/" ]
Try this full Client Credentials Authorization flow. First step – get an authorization token with your credentials: ``` CLIENT_ID = " < your client id here... > " CLIENT_SECRET = " < your client secret here... > " grant_type = 'client_credentials' body_params = {'grant_type' : grant_type} url='https://accounts.spo...
As it is referenced [here](https://developer.spotify.com/documentation/web-api/reference/playlists/create-playlist/), you have to give the Bearer token to the Authorization header, and using requests it is done by declaring the "headers" optional: ```py r = requests.post(url="https://api.spotify.com/v1/users/{your-use...
10,729
72,230,877
So I had created a python web scraper for my college capstone project that scraped around the web and followed links based on a random selection from the page. I utilized Python's request module to return links from a get request. I had it working flawlessly along with a graphing program that showed the program working...
2022/05/13
[ "https://Stackoverflow.com/questions/72230877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13450139/" ]
`Requests.Response.links` doesn't work like that [1]. It looks for [Links in the Header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link), not link elements in the Response body. What you want is to extract link *elements* from the Response body, so I would recommend something like `lxml` or `beautifuls...
Parsing links with `beautifulsoup4` is a possible solution: ```py import requests from bs4 import BeautifulSoup def get_links(url: str) -> list[str]: with requests.get(url) as response: soup = BeautifulSoup(response.text, features='html.parser') links = [] for link in soup.find_all('a'): ...
10,730
62,556,358
Sometimes when I run the code it gives me the correct output, other times it says "List index out of range" and other times it just continues following code. I found the code on: <https://www.codeproject.com/articles/873060/python-search-youtube-for-video> How can I fix this? ``` searchM = input("Enter the movie you ...
2020/06/24
[ "https://Stackoverflow.com/questions/62556358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13757098/" ]
The error occurs when no 'search results' have been obtained, such that search\_results[0] cannot be found. I would suggest you use an 'if/else' statement, something like: ``` if len(search_results) == 0: print("No search results obtained. Please try again.") else: print("Click on the link to watch the trail...
search[0] will return the first element of the list. However, if there are no elements in the list, there will not be a first element in the list, and "List index out of range". I recommend adding an if statement to check if the length of search\_results is greater than 0 and then printing search[0]. Hope this helps! ...
10,731
51,140,417
For the past 4 days I have been working to get taskwarrior and taskwarrior server running on windows 10. It has proven quite a challenge for me. I followed the steps written below: "Building the Stable Version" on <https://taskwarrior.org/docs/build.html> and created a folder: ``` C:\taskwarrior ``` Opened Develope...
2018/07/02
[ "https://Stackoverflow.com/questions/51140417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7437143/" ]
I'm not sure that it is still relevant to your problem, but I was able to build taskwarrior v2.5.1 under 64-bit cygwin (on Win7), using the `cmake` line from here: [TW-1845 Cygwin build fails, missing get\_current\_dir\_name](https://github.com/GothenburgBitFactory/taskwarrior/issues/1861) Namely, this `cmake` line fo...
I am likely to have misunderstood the context. GnuTLS Appears to be a program that works/is made for a linux/debian operating system. Nevertheless, the following two solutions were effective in: 1. Finding and using the UUID library in Windows. 2. Solving the XY-problem and using GnuTLS on a "windows pc" (with Linux...
10,732
33,355,299
I've already searched SO for how to flatten a list of lists (i.e. here:[Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python)) but none of the solutions I find addresses flattening a list of lists of lists to just a list of lists...
2015/10/26
[ "https://Stackoverflow.com/questions/33355299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2483176/" ]
If we apply the logic from [this answer](https://stackoverflow.com/a/952952/771848), should not it be just: ``` In [2]: [[item for subsublist in sublist for item in subsublist] for sublist in my_list] Out[2]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]] ``` And, similarly via [`itertools.chain()`](https://stackove...
You could use this recursive subroutine ``` def flatten(lst, n): if n == 0: return lst return flatten([j for i in lst for j in i], n - 1) mylist = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ] flatten(mylist, 1) #=> [[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4, 6], [1]] flatten(mylist, 2) #=> [1, 2,...
10,733