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 |
|---|---|---|---|---|---|---|
16,158,221 | I got this error:
```
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] mod_wsgi (pid=19481): Exception occurred processing WSGI script '/home/projects/treeio/treeio.wsgi'.
[Mon Apr 22 23:45:42 2013] [error] [client 192.168.1.88] Traceback (most recent call last):
[Mon Apr 22 23:45:42 2013] [error] [client 192.... | 2013/04/22 | [
"https://Stackoverflow.com/questions/16158221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2309182/"
] | try `GROUP BY` with `GROUP_CONCAT`
<http://www.mysqlperformanceblog.com/2006/09/04/group_concat-useful-group-by-extension/> | You could do this all in your query instead of relying on PHP.
```
Select item, group_concat(category) FROM yourtable GROUP BY Item
``` | 6,443 |
12,482,819 | I have been working with Beaglebone lately and have a question.
I have worked with TI microcontrollers before, setting the registers as I needed to.
From what I understand, the Angstrom distro (the one that comes with the board) let to set the registers of the processor as you want (through the kernel and class folde... | 2012/09/18 | [
"https://Stackoverflow.com/questions/12482819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1420553/"
] | After trying out a few variations this worked:
```
-:System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute
``` | Make sure you add this filter inside **Attribute Filter**:
```
-:System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute
```
 | 6,451 |
41,009,009 | I'm trying to create a function
```
rotate_character(char, rot)
```
that receives a character, "char" (a string with a length of 1), and an integer "rot". The function should return a new string with a length of 1, which is the result of rotating char by rot number of places to the right.
So an input of "A" for cha... | 2016/12/07 | [
"https://Stackoverflow.com/questions/41009009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3546086/"
] | ```
def rotate(letter, rot):
shift = 97 if letter.islower() else 65
return chr((ord(letter) + rot - shift) % 26 + shift)
letter = input('Enter a letter: ')
rot = int(input('Enter a number: '))
print(rotate(letter, rot))
``` | You can use the `string` module and then use the modulo operator to "wrap around" the end of the alphabet:
```
from string import lowercase
def rotate_char(char, rot):
i = lowercase.index(char)
return lowercase[(i + rot) % 25]
``` | 6,452 |
39,606,112 | I'm a beginner trying to write a program that will read in .exe files, .class files, or .pyc files and get the percentage of alphanumeric characters (a-z,A-Z,0-9). Here's what I have right now (I'm just trying to see if I can identify anything at the moment, not looking to count stuff yet):
```
chars_total = 0
chars_a... | 2016/09/21 | [
"https://Stackoverflow.com/questions/39606112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6856008/"
] | `viewWillLayoutSubviews` is called when view controller's view's bounds changed (usually happens when view loaded, or orientation changed, or if it's a child view controller, and its view was changed by the parent view controller), but before it's subview's bounds or position changes. You can override this method to ma... | You can call the `layoutSubviews()` of UIView when you are changing any constraint value which is inside the UIView and more then one element is effected by the constraint change. When you are performing some task by changing the constraint by taking an outlet of the constraint at runtime you can call this. But this is... | 6,453 |
52,072,784 | I am working on a positioning system.
The input I have is a dict which will give us circles of radius d1 from point(x1,y1) and so on.
The output I want is an array(similar to a 2D coordinate system) in which the intersecting area is marked 1 and rest is 0.
I tried this:
```
xsize=3000
ysize=2000
lis={(x1,y1):d1,(x2,y... | 2018/08/29 | [
"https://Stackoverflow.com/questions/52072784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10269207/"
] | As you are already using numpy, try to rewrite your operations in a vectorized fashion, instead of using loops.
```
# choose appropriate dtype for better perf
dtype = np.float32
# take all indices in an array
indices = np.indices((ysize, xsize), dtype=dtype).T
points = np.array(list(lis.keys()), dtype=dtype)
# squar... | Thanks for the answers!
I also found this:
```
pos=np.ones((xsize,ysize))
xx,yy=np.mgrid[:xsize,:ysize]
for element in lis:
circle=(xx-element[0])**2+(yy-element[1])**2
pos=np.logical_and(pos,(circle<(lis[element]**2)))
#pos&circle<(lis[element]**2 doesn't work(I read somewhere it does)
```
I needed thi... | 6,456 |
42,835,809 | are there any tutorials available about `export_savedmodel` ?
I have gone through [this article](https://www.tensorflow.org/versions/master/api_docs/python/contrib.learn/estimators) on tensorflow.org and [unittest code](https://github.com/tensorflow/tensorflow/blob/05d7f793ec5f04cd6b362abfef620a78fefdb35f/tensorflow/p... | 2017/03/16 | [
"https://Stackoverflow.com/questions/42835809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456105/"
] | if you are using tensorflow straight from the master branch there's a module tensorflow.python.estimator.export that provides a function for that:
```
from tensorflow.python.estimator.export import export
feature_spec = {'MY_FEATURE': tf.constant(2.0, shape=[1, 1])}
serving_input_fn = export.build_raw_serving_input_re... | You need to have tf.train.Example and tf.train.Feature and pass the input to input receiver function and invoke the model.
You can take a look at this example
<https://github.com/tettusud/tensorflow-examples/tree/master/estimators> | 6,457 |
70,068,198 | I have api like this :

I want to call this api in python, this is my code :
```
def get_province():
headers = {
'Content-type': 'application/json',
'x-api-key': api_key
}
response = requests.get(url, headers=headers)
return response.json()
```
But, i... | 2021/11/22 | [
"https://Stackoverflow.com/questions/70068198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17480369/"
] | **No Need for a LOOP**
Here is a little technique Gordon Linoff demonstrated some time ago.
1. Expand
2. Elimnate
3. Restore
You can substitute any `ODD` combination of characters/strings pairs like `§§` and `||`
**Example**
```
Select replace(replace(replace('my string to split',' ','><'),'<>',''),'><',' ')
`... | use charindex <https://www.w3schools.com/sql/func_sqlserver_charindex.asp> in a looping structure and then use a variable to keep track of the index position. | 6,462 |
14,444,012 | I am writing a bit of `python` code where I had to check if all values in `list2` was present in `list1`, I did that by using `set(list2).difference(list1)` but that function was too slow with many items in the list.
So I was thinking that `list1` could be a dictionary for fast lookup...
So I would like to find a fa... | 2013/01/21 | [
"https://Stackoverflow.com/questions/14444012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1376883/"
] | A fast way to achieve what you want will be using `all` and a generator comprehension.
```
s_list2 = set(list2)
all_present = all(l in s_list2 for l in list1)
```
This will be advantageous in the case that some elements of list1 are not present in list2.
Some timing. In the case where all values in the first list a... | You can convert the lists to sets and then use the method `issubset()` to check whether one is a subset of another set or not.
```
In [78]: import random
In [79]: lis2=range(100)
In [80]: random.shuffle(lis2)
In [81]: lis1=range(1000)
In [82]: random.shuffle(lis1)
In [83]: s1=set(lis1)
In [84]: all(l in s1 for l... | 6,463 |
11,962,123 | I am trying to make a query which I haven't been able to yet. My permanent view function is following:
```
function(doc) {
if('llweb_result' in doc){
for(i in doc.llweb_result){
emit(doc.llweb_result[i].llweb_result, doc);
}
}
}
```
Depending on the key, I filter the result. ... | 2012/08/14 | [
"https://Stackoverflow.com/questions/11962123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1277280/"
] | If you get duplicate pairs in the query results, it means that you have the duplicate `doc.llweb_result[i].llweb_result` values in each document.
You can change the view function to emit only one of these values (as the key). One way to do so would be:
```
function(doc) {
if ('llweb_result' in doc) {
dis... | I don't know anything about `couchdb-python` but CouchDB supports either a single `key` or multiple `keys` in an array. So, take a look in your `couchdb-python` docs for how to supply `keys=[0,1,2]` as a parameter.
Regarding getting just the unique values, take a look [at this section of *CouchDB The Definitive Guide*... | 6,466 |
7,045,371 | I recently learned I could run a server with this command:
```
sudo python -m HTTPSimpleServer
```
**My question: how do I terminate this server when done with it?** | 2011/08/12 | [
"https://Stackoverflow.com/questions/7045371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/873392/"
] | Type Control-C. Simple as that. | You might want to check the HttpServer class in [this servlet module](http://code.google.com/p/verse-quiz/source/browse/trunk/servlet.py) for a modification that allows the server to be quit. If the handler raises a SystemExit exception, the server will break from its serving.
---
```
class HttpServer(socketserver.Th... | 6,467 |
2,706,129 | I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython.
I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free.
I plan to implement an expression tree, and a method to evaluate it in postfix order.
The problem I run into right away is:
```
class Node {
... | 2010/04/24 | [
"https://Stackoverflow.com/questions/2706129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/169415/"
] | No, because the object would be infinitely large (because every `Node` has as members two other `Node` objects, which each have as members two other `Node` objects, which each... well, you get the point).
You can, however, have a pointer to the class type as a member variable:
```
class Node {
char *cargo;
No... | No, but it can have a reference or a pointer to itself:
```
class Node
{
Node *pnode;
Node &rnode;
};
``` | 6,468 |
48,490,382 | Gnome desktop has 2 clipboards, the X.org (saves every selection) and the legacy one (CTRL+C). I am writing a simple python script to clear both clipboards, securely preferably, since it may be done after copy-pasting a password.
The code that I have seen over here is this:
```
# empty X.org clipboard
os.system("xcli... | 2018/01/28 | [
"https://Stackoverflow.com/questions/48490382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9213435/"
] | I know three ways to clear the clipboard from Python. First using tkinter:
```
try:
from Tkinter import Tk
except ImportError:
from tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.destroy()
```
Second with xclip, but I use xclip like this:
```
echo -n | xclip -selection clipboard
```
Does it... | I have figured out:
```
#CLIPBOARD cleaner
subprocess.run(["xsel","-bc"])
#PRIMARY cleaner
subprocess.run(["xsel","-c"])
```
This one cleans both buffers, and leaves no zombie processes at all. Thanks for everyone who suggested some of them. | 6,474 |
40,942,338 | I'm working on a python AWS Cognito implementation using boto3. `jwt.decode` on the IdToken yields a payload that's in the form of a dictionary, like so:
```py
{
"sub": "a uuid",
"email_verified": True,
"iss": "https://cognito-idp....",
"phone_number_verified": False,
"cognito:username": "19407ea0-... | 2016/12/02 | [
"https://Stackoverflow.com/questions/40942338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/119041/"
] | As I noted in a comment, the bulk of your work can be done by a dict comprehension:
```
lst = get_user() # or something similar, lst is a list of dicts
parsed_res = {k["Name"]:k["Value"] for k in lst}
```
This only differs from your expected output in that it contains `'true'` and `'false'` whereas you want bools in... | A dictionary comprehension, as Andras answered above, is a simple, Pythonic one-liner for your case. Some style guidelines ([such as Google's](https://google.github.io/styleguide/pyguide.html?showone=List_Comprehensions#List_Comprehensions)), however, recommend against them if they introduce complex logic or take up mo... | 6,476 |
67,448,604 | I have a pandas DataFrame containing rows of nodes that I ultimately would like to *connect* and turn into a graph like object. For this, I first thought of converting this DataFrame to something that resembles an adjacency list, to later on easily create a graph from this. I have the following:
A pandas Dataframe:
`... | 2021/05/08 | [
"https://Stackoverflow.com/questions/67448604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5560529/"
] | One option would be to apply the following function - it's not completely vectorised because Dataframes don't particularly like embedding mutable objects like lists, and I don't think you can apply set operations in a vectorised way. It does cut down the number of comparisons needed though.
```
def f(x):
check = d... | TRY:
```
k=0
def test(x):
global k
k+=1
test_df = df[k:]
return list(test_df[test_df['start'] == x].index)
df['adjancy_matrix'] = df.end.apply(test,1)
```
**OUTPUT:**
```
id start end cases adjancy_matrix
0 0 A B [c1,c2,c44] [1, 6]
1 1 B C [c2,c1,c3] ... | 6,477 |
40,041,463 | I installed OpenCV 3.1.0 and CUDA 8.0 in Ubuntu 16.04. When I check "nvcc --version" to check the CUDA version, it is 8.0. But when I try to compile a C++ OpenCV program I get the following error:
```
Could NOT find CUDA: Found unsuitable version "7.5", but required
is exact version "8.0" (found /usr/local/cuda)
``... | 2016/10/14 | [
"https://Stackoverflow.com/questions/40041463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4136920/"
] | I had a similar issue after upgrading from CUDA 8.0 to 9.1. When I compiled my code and got error "found unsuitable version (CUDA 8.0)". In my case, it's the problem of previous cmake files. Just deleted previous files generated by cmake and then it worked fine. | Environment Variables
As part of the CUDA environment, you should add the following in the .bashrc file of your home folder.
```
export CUDA_HOME=/usr/local/cuda-7.5
export LD_LIBRARY_PATH=${CUDA_HOME}/lib64
PATH=${CUDA_HOME}/bin:${PATH}
export PATH
``` | 6,479 |
39,656,433 | I need to download incoming attachment without past attachment from mail using Python Script.
For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments.
Please anyone help me to download attachment using python script or java. | 2016/09/23 | [
"https://Stackoverflow.com/questions/39656433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5693776/"
] | ```
import email
import imaplib
import os
class FetchEmail():
connection = None
error = None
mail_server="host_name"
username="outlook_username"
password="password"
self.save_attachment(self,msg,download_folder)
def __init__(self, mail_server, username, password):
self.connection = imaplib.IMAP4_SSL(mail_server)
... | ```
import win32com.client #pip install pypiwin32 to work with windows operating sysytm
import datetime
import os
# To get today's date in 'day-month-year' format(01-12-2017).
dateToday=datetime.datetime.today()
FormatedDate=('{:02d}'.format(dateToday.day)+'-'+'{:02d}'.format(dateToday.month)+'-'+'{:04d}'.format(dateT... | 6,481 |
70,580,711 | How can I change my slurm script below so that each python job gets a unique GPU? The node had 4 GPUs, I would like to run 1 python job per each GPU.
The problem is that all jobs use the first GPU and other GPUs are idle.
```
#!/bin/bash
#SBATCH --qos=maxjobs
#SBATCH -N 1
#SBATCH --exclusive
for i in `seq 0 3`; do
... | 2022/01/04 | [
"https://Stackoverflow.com/questions/70580711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7242276/"
] | If the solution proposed by @Iagows doesn't work for you, have a look at this:
[flutter\_launcher\_icons-issues](https://github.com/fluttercommunity/flutter_launcher_icons/issues/324#issuecomment-1005736502) | The issue is explained in the readme of the plugin, section "Dependency incompatible". It says
```
Because flutter_launcher_icons >=0.9.0 depends on args 2.0.0 and flutter_native_splash 1.2.0 depends on args ^2.1.1, flutter_launcher_icons >=0.9.0 is incompatible with flutter_native_splash 1.2.0.
And because no version... | 6,486 |
60,548,289 | I don't know why I am getting this error. Below is the code I am using.
**settings.py**
```
TEMPLATE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "mysite", "static", "templates"),)
```
**urls.py**
```
from django.urls import path
from django.conf.urls import include, url
from django.contrib.auth import views as... | 2020/03/05 | [
"https://Stackoverflow.com/questions/60548289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5227269/"
] | The problem comes from the "this" scope.
Either you have to bind the function you're using in the class.
```
constructor( props ){
super( props );
this.resetTimer = this.resetTimer.bind(this);
}
```
A second option is to use arrow functions when you declare your functions in order to maintain the scope of "th... | instead of writing
```
`resetTimer() {
this.setState(initialState);
}`
```
use arrow function
`const resetTimer=()=> {
this.setState(initialState);
}`
this will work | 6,496 |
64,965,247 | I was developing a bot on discord, and I want to log when user roles changes. I tried the code below and that was just starting.
```py
TOKEN = ""
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
@client.event
async def on_message(message):
print... | 2020/11/23 | [
"https://Stackoverflow.com/questions/64965247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14041512/"
] | Your intents should be enabled both on the portal and the code itself.
Here is how you do it in the code.
```py
intents = discord.Intents().all()
client = discord.Client(intents=intents)
```
And according to the [docs of on\_memebr\_update](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_member_updat... | You should activate that from your code like:
```py
intents = discord.Intents.default()
intents.members = True
intents.presences = True
client= discord.Client(intents=intents)
```
[reference for more information](https://discordpy.readthedocs.io/en/latest/intents.html) | 6,501 |
61,296,763 | I have trained a CNN in Matlab 2019b that classifies images between three classes. When this CNN was tested in Matlab it was functioning fine and only took 10-15 seconds to classify an image. I used the exportONNXNetwork function in Maltab so that I can implement my CNN in Tensorflow. This is the code I am using to use... | 2020/04/18 | [
"https://Stackoverflow.com/questions/61296763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Maybe you could try to understand what part of the code takes a long time this way:
```
import onnx
from onnx_tf.backend import prepare
import numpy as np
from PIL import Image
import datetime
now = datetime.datetime.now()
onnx_model = onnx.load('trainednet.onnx')
tf_rep = prepare(onnx_model)
filepath = 'filepath.p... | You should consider some points while working on TensorFlow with Python. A GPU will be better for work as it fastens the whole processing. For that, you have to install CUDA support. Apart from this, the compiler also sometimes matters. I can tell VSCode is better than Spyder from my experience.
I hope it helps. | 6,502 |
50,315,645 | I have a simple script which is using [signalr-client-py](https://github.com/TargetProcess/signalr-client-py) as an external module.
```
from requests import Session
from signalr import Connection
import threading
```
When I try to run my script using the `sudo python myScriptName.py` I get an error:
```
Traceback... | 2018/05/13 | [
"https://Stackoverflow.com/questions/50315645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128702/"
] | By default sudo runs commands in different environment.
You can ask sudo to preserve environment with `-E` switch.
```
sudo -E python myScriptName.py
```
It comes with it's own security risks. So be careful | You need to check where signalr is installed. sudo runs the program in the environment available to root and if signalr is not installed globally it won't be picked up. Try 'sudo pip freeze' to see what is available in the root environment. | 6,506 |
16,170,268 | I have written a python27 module and installed it using `python setup.py install`.
Part of that module has a script which I put in my bin folder within the module before I installed it. I think the module has installed properly and works (has been added to site-packages and scripts). I have built a simple script "test... | 2013/04/23 | [
"https://Stackoverflow.com/questions/16170268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2270903/"
] | Are you using `distutils` or `setuptools`?
I tested right now, and if it's distutils, it's enough to have
`scripts=['bin/script_name']`
in your `setup()` call
If instead you're using setuptools you can avoid to have a script inside bin/ altogether and define your entry point by adding
`entry_points={'console_scrip... | Please check your installed module for using condition to checking state of global variable `__name__`.
I mean:
```
if __name__ == "__main__":
```
Global variable `__name__` changing to "`__main__`" string in case, then you starting script manually from command line (e.g. python sample.py).
If you using this conditi... | 6,509 |
36,212,431 | I want to using python to open two files at the same time, read one line from each of them then do some operations. Then read the next line from each of then and do some operation,then the next next line...I want to know how can I do this. It seems that `for` loop cannot do this job. | 2016/03/25 | [
"https://Stackoverflow.com/questions/36212431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5362936/"
] | ```
file1 = open("some_file")
file2 = open("other_file")
for some_line,other_line in zip(file1,file2):
#do something silly
file1.close()
file2.close()
```
note that `itertools.izip` may be prefered if you dont want to store the whole file in memory ...
also note that this will finish when the end of either fil... | Why not read each file into a list each element in the list holds 1 line.
Once you have both files loaded to your lists you can work line by line (index by index) through your list doing whatever comparisons/operations you require. | 6,510 |
23,769,001 | I would like to know if it is possible to enable gzip compression
for Server-Sent Events (SSE ; Content-Type: text/event-stream).
It seems it is possible, according to this book:
<http://chimera.labs.oreilly.com/books/1230000000545/ch16.html>
But I can't find any example of SSE with gzip compression. I tried to
send ... | 2014/05/20 | [
"https://Stackoverflow.com/questions/23769001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2753095/"
] | TL;DR: If the requests are not cached, you likely want to use zlib and declare Content-Encoding to be 'deflate'. That change alone should make your code work.
---
If you declare Content-Encoding to be gzip, you need to actually use gzip. They are based on the the same compression algorithm, but gzip has some extra fr... | There's also middleware you can use so you don't need to worry about gzipping responses for each of your methods. Here's one I used recently.
<https://code.google.com/p/ibkon-wsgi-gzip-middleware/>
This is how I used it (I'm using bottle.py with the gevent server)
```
from gzip_middleware import Gzipper
import bottl... | 6,513 |
47,310,884 | I need to passively install Python in my applications package installation so i use the following:
```
python-3.5.4-amd64.exe /passive PrependPath=1
```
according this: [3.1.4. Installing Without UI](https://docs.python.org/3.6/using/windows.html#installing-without-ui) I use the PrependPath parameter which should ad... | 2017/11/15 | [
"https://Stackoverflow.com/questions/47310884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7031374/"
] | Ok, from my point of view it seems to be bug in Python Installer and I can not find any way how to make it works.
I have founds the following workaround:
Use py.exe which is wrapper for all version of Python on local machine located in C:\Windows so you can run it directly from CMD anywhere thanks to C:\Windows is st... | try powershell to do that
```
Start-Process -NoNewWindow .\python.exe /passive
``` | 6,514 |
34,076,773 | So i have an empty main frame called `MainWindow` and a `WelcomeWidget` that gets called immidiatley on program startup and loads inside the main frame. Then i want the button `next_btn` inside `WelcomeWidget` to call `LicenseWidget` QWidget inside the `MainWindow` class . How do i do that?
Here is my code:
**Main.py... | 2015/12/03 | [
"https://Stackoverflow.com/questions/34076773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3855967/"
] | `QWizard` might be of use. Another way would be to layout both widgets in a `QVerticalLayout` and hide the one you are not interested in. The visible one takes then up all the space.
It could even be completely constructed in QtCreator .. just `hide()` what you don't want to see and `show()` what you want to see.
It ... | ```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Main.py
#
# Copyright 2015 Ognjen Galic <gala@thinkpad>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the L... | 6,518 |
56,914,224 | I have a dataframe as shown in the picture:
[problem dataframe: attdf](https://i.stack.imgur.com/9e5y4.png)
I would like to group the data by Source class and Destination class, count the number of rows in each group and sum up Attention values.
While trying to achieve that, I am unable to get past this type error:... | 2019/07/06 | [
"https://Stackoverflow.com/questions/56914224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9003184/"
] | @Adam.Er8 and @jezarael helped me with their inputs. The unhashable type error in my case was because of the datatypes of the columns in my dataframe.
[Original df and df imported from csv](https://i.stack.imgur.com/soqF0.png)
It turned out that the original dataframe had two object columns which i was trying to use ... | try using [`.agg`](https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.core.groupby.DataFrameGroupBy.agg.html) as follows:
```py
import pandas as pd
attdf = pd.read_csv("attdf.csv")
print(attdf.groupby(['Source Class', 'Destination Class']).agg({"Attention": ['sum', 'count']}))
```
Output:
```
... | 6,519 |
5,475,259 | I run a small VPS with 512M memory of memory that currently hosts 3 very low traffic PHP sites and a personal email account.
I have been teaching myself Django over the last few weeks and am starting to think about deploying a project.
There seem to be a very large number of methods for deploying a Django site. Given... | 2011/03/29 | [
"https://Stackoverflow.com/questions/5475259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/570068/"
] | There aren't really a great number of ways to do it. In fact, there's the recommended way - via Apache/mod\_wsgi - and all the other ways. The recommended way is fully documented [here](http://docs.djangoproject.com/en/1.3/howto/deployment/modwsgi/).
For a low-traffic site, you should have no trouble fitting it in you... | Django has documentation describing possible [server arrangements](http://code.djangoproject.com/wiki/ServerArrangements). For light weight, yet very robust set up, I'd recommend Nginx setup. It's much lighter than Apache. | 6,520 |
50,552,404 | So far `pandas` read through all my CSV files without any problem, however now there seems to be a problem..
When doing:
```
df = pd.read_csv(r'path to file', sep=';')
```
I get:
>
> OSError Traceback (most recent call
> last) in ()
> ----> 1 df = pd.read\_csv(r'path
> Übersicht\Input\test\test.csv', sep=';')
... | 2018/05/27 | [
"https://Stackoverflow.com/questions/50552404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2252633/"
] | I ran into a similar problem. It turned out the CSV I had downloaded had no permissions at all. The error message from pandas did not point this out, making it hard to debug.
Check that your file have read permissions | pandas read\_csv OSError: Initializing from file failed
We could try `chmod 600 file.csv`. | 6,522 |
65,645,999 | For some context, I am coding some geometric transformations into a python class, adding some matrix multiplication methods. There can be many 3D objects inside of a 3D "scene". In order to allow users to switch between applying transformations to the entire scene or to one object in the scene, I'm computing the geomet... | 2021/01/09 | [
"https://Stackoverflow.com/questions/65645999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10151432/"
] | One line:
```py
def apply_centroid_transform(point, centroid, reverse=False):
return [point[i] - [1, -1][reverse]*centroid[j] for i, j in enumerate('xyz')]
```
It is not very readable, but it is very concise :) | Well, if you like, you can do this:
```
def apply_centroid_transform(point, centroid, reverse=False):
op = float.__sub__ if reverse else float.__add__
return [op(p_i, c_i) for p_i, c_i in zip(point, centroid)]
``` | 6,532 |
26,199,343 | I have a bunch of `Album` objects in a `list` (code for objects posted below). 5570 to be exact. However, when looking at unique objects, I should have 385. Because of the way that the objects are created (I don't know if I can explain it properly), I thought it would be best to add all the objects into the list, and t... | 2014/10/05 | [
"https://Stackoverflow.com/questions/26199343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4027606/"
] | when you do mvvm and wanna use button then you should use DelegateCommand or RelayCommand. if you use this then you just have to implement the ICommand properly (CanExecute!) the Command binding to the button will handle IsEnabled for you.
```
<Button Command="{Binding MyRemoveCommand}"></Button>
```
cs.
```
pu... | As far as i can see in your MVVM there is a bool "CanRemove". You can bind this to your buttons visibility with the already [BooleanToVisibilityConverter](http://msdn.microsoft.com/en-us/library/system.windows.controls.booleantovisibilityconverter%28v=vs.110%29.aspx) which is provided by .NET | 6,535 |
3,904,033 | Is there an easy way to get a python code segment to run every 5 minutes?
I know I could do it using time.sleep() but was there any other way?
For example I want to run this every 5 minutes:
```
x = 0
def run_5():
print "5 minutes later"
global x += 5
print x, "minutes since start"
```
That's only a fa... | 2010/10/11 | [
"https://Stackoverflow.com/questions/3904033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472006/"
] | you can do it with the threading module
```
>>> import threading
>>> END = False
>>> def run(x=0):
... x += 5
... print x
... if not END:
... threading.Timer(1.0, run, [x]).start()
...
>>> threading.Timer(1.0, run, [x]).start()
>>> 5
10
15
20
25
30
35
40
```
Then when you want it to stop, set `E... | You might want to have a look at `cron` if you are running a \*nix type OS. You could easily have it run you program every 5 minutes
<http://www.unixgeeks.org/security/newbie/unix/cron-1.html>
<https://help.ubuntu.com/community/CronHowto> | 6,538 |
3,113,002 | After doing web development (php/js) for the last few years i thought it is about time to also have a look at something different. I thought it may be always good to have look of different areas in programming to understand some different approaches better, so i now want to have look at GUI development.
As programmin... | 2010/06/24 | [
"https://Stackoverflow.com/questions/3113002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/276382/"
] | The first thing to realize is that you'll get more mileage out of understanding Qt than understanding PyQt. Most of the good documentation discusses Qt, not PyQt, so getting conversant with them (and how to convert that code to PyQt code) is a lifesaver. Note, I don't actually recommend *programming* Qt in C++; Python ... | I had this bookmark saved:
<http://www.harshj.com/2009/04/26/the-pyqt-intro/> | 6,541 |
18,905,026 | When trying to unit test a method that returns a tuple and I am trying to see if the code accesses the correct tuple index, python tries to evaluate the expected call and turns it into a string.
`call().methodA().__getitem__(0)` ends up getting converted into `'().methodA'`
in my `expected_calls` list for the assertio... | 2013/09/19 | [
"https://Stackoverflow.com/questions/18905026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373628/"
] | To test for `mock_object.account['xxx1'].patch(body={'status': 'active'})`
I had to use the test:
```
mock_object.account.__getitem__.assert_has_calls([
call('xxxx1'),
call().patch(body={'status': 'active'}),
])
```
I can't explain why this works, this looks like weird behaviour, possibly a bug in mock, but ... | I've just stumbled upon the same problem. I've used the solution/work-around from here:
<http://www.voidspace.org.uk/python/mock/examples.html#mocking-a-dictionary-with-magicmock>
namely:
```
>> mock.__getitem__.call_args_list
[call('a'), call('c'), call('d'), call('b'), call('d')]
```
You can skip the magic funct... | 6,546 |
14,366,668 | I've been working on learning python and somehow came up with following codes:
```
for item in list:
while list.count(item)!=1:
list.remove(item)
```
I was wondering if this kind of coding can be done in c++. (Using list length for the for loop while decreasing its size) If not, can anyone tell me why?
... | 2013/01/16 | [
"https://Stackoverflow.com/questions/14366668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1948847/"
] | I am not a big Python programmer, but it seems like the above code removes duplicates from a list. Here is a C++ equivalent:
```
list.sort();
list.unique();
```
As for modifying the list while iterating over it, you can do that as well. Here is an example:
```
for (auto it = list.begin(), eit = list.end(); it != ei... | In C++, you can compose something like this from various algorithms of the standard library, check out remove(), find(), However, the way your algorithm is written, it looks like O(n^2) complexity. Sorting the list and then scanning over it to put one of each value into a new list has O(n log n) complexity, but ruins t... | 6,547 |
49,889,153 | I am running an RNN on a signal in fixed-size segments. The following code allows me to preserve the final state of the previous batch to initialize the initial state of the next batch.
```
rnn_outputs, final_state = tf.contrib.rnn.static_rnn(cell, rnn_inputs, initial_state=init_state)
```
This works when the batch... | 2018/04/17 | [
"https://Stackoverflow.com/questions/49889153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4008884/"
] | In tensorflow the only thing that is kept after returning from a call to `sess.run` are variables. You should create a variable for the state, then use `tf.assign` to assign the result from your RNN cell to that variable. You can then use that Variable in the same way as any other tensor.
If you need to initialize the... | So, I came here looking for an answer earlier, but I ended up creating one.
Similar to above posters about making it assignable...
When you build your graph, make a list of sequence placeholders like..
```
my_states = [None] * int(sequence_length + 1)
my_states[0] = cell.zero_state()
for step in steps:
cell_ou... | 6,552 |
38,552,688 | I am trying to filter all the `#` keywords from the tweet text. I am using `str.extractall()` to extract all the keywords with `#` keywords.
This is the first time I am working on filtering keywords from the tweetText using pandas. Inputs, code, expected output and error are given below.
Input:
```
userID,tweetText... | 2016/07/24 | [
"https://Stackoverflow.com/questions/38552688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056548/"
] | If you are not too tied to using `extractall`, you can try the following to get your final output:
```
from io import StringIO
import pandas as pd
import re
data_text = """userID,tweetText
01, home #sweet home
01, #happy #life
02, #world peace
03, #all are one
"""
data = pd.read_csv(StringIO(data_text),header=0)
d... | The `extractall` function requires a regex pattern **with capturing groups** as the first argument, for which you have provided `#`.
A possible argument could be `(#\S+)`. The braces indicate a capture group, in other words what the `extractall` function needs to extract from each string.
Example:
```
data="""01, ho... | 6,553 |
22,714,864 | I'm trying to craft a regex able to match anything up to a specific pattern. The regex then will continue looking for other patterns until the end of the string, but in some cases the pattern will not be present and the match will fail. Right now I'm stuck at:
```
.*?PATTERN
```
The problem is that, in cases where t... | 2014/03/28 | [
"https://Stackoverflow.com/questions/22714864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3472731/"
] | You could try using `split`
If the results are of length 1 you got no match. If you get two or more you know that the first one is the first match. If you limit the split to size one you'll short-circuit the later matching:
```
"HI THERE THEO".split("TH", 1) # ['HI ', 'ERE THEO']
```
The first element of the resul... | The Python documentation includes a brief outline of the differences between the `re.search()` and `re.match()` functions <http://docs.python.org/2/library/re.html#search-vs-match>. In particular, the following quote is relevant:
>
> Sometimes you’ll be tempted to keep using re.match(), and just add .\* to the front ... | 6,558 |
62,461,709 | currently, I'm trying to execute a python code that extracts information from the snowflake.
When I running my code in my PC executed well, but if I try to run the code in a VM It shows me this error:
[](https://i.stack.imgur.com/DTXuD.png)
The VM is ... | 2020/06/19 | [
"https://Stackoverflow.com/questions/62461709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6153466/"
] | The Pandas python library requires some extra native libraries (DLLs) to load certain submodules due to use of C-extensions.
Very recent Pandas versions, after 1.0.1, [are facing a build distribution issue](https://github.com/pandas-dev/pandas/issues/32857) currently, where their published packages are not carrying th... | Please make sure to have the [Snowflake Python Connector prerequisites](https://docs.snowflake.com/en/user-guide/python-connector-install.html#prerequisites) installed.
You can try the following commands:
```
// Install Python
sudo yum install python36
// Install pip
curl https://bootstrap.pypa.io/get-pip.py -o get-... | 6,560 |
36,676,629 | I use the following trick in some of my Python scripts to drop into an interactive Python REPL session:
```
import code; code.InteractiveConsole(locals=globals()).interact()
```
This usually works well on various RHEL machines at work, but on my laptop (OS X 10.11.4) it starts the REPL seemingly without readline sup... | 2016/04/17 | [
"https://Stackoverflow.com/questions/36676629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6215905/"
] | Just `import readline`, either in the script or at the console. | The program `rlwrap` solves this problem in general, not just for Python but also for other programs in need of this feature such as `telnet`. You can install it with `brew install rlwrap` if you have Homebrew (which you should) and then use it by inserting it at the beginning of a command, i.e. `rlwrap python repl.py`... | 6,561 |
21,421,987 | Somewhat a python/programming newbie here.
I am trying to access a specified range of tuples from a list of tuples, but I only want to access the first element from the range of tuples. The specified range is based on a pattern I am looking for in a string of text that has been tokenized and tagged by nltk. My code:
... | 2014/01/29 | [
"https://Stackoverflow.com/questions/21421987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2680443/"
] | Probably the simplest method uses a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions). This statement creates a list from the first element of every tuple in your list:
```
print [tup[0] for tup in tagged[counter:counter+7]]
```
Or just for fun, if the tuples are always ... | Have you tried zip?
also
item[0] for item in name | 6,562 |
22,026,177 | I'm getting a strange error from the Django tests, I get this error when I test Django or when I unit test my story app. It's complaining about multiple block tags with the name "content" but I've renamed all the tags so there should be zero block tags with the name content. The test never even hits my app code, and fa... | 2014/02/25 | [
"https://Stackoverflow.com/questions/22026177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319434/"
] | You can use `while` and `each` like this:
```
while (my ($key1, $inner_hash) = each %foo) {
while (my ($key2, $inner_inner_hash) = each %$inner_hash) {
while (my ($key3, $value) = each %$inner_inner_hash) {
print $value;
}
}
}
```
This approach uses less memory than `foreach key... | You're looking for something like this:
```
for my $key1 ( keys %foo )
{
my $subhash = $foo{$key1};
for my $key2 ( keys %$subhash )
{
my $subsubhash = $subhash->{$key2};
for my $key3 ( keys %$subsubhash )
``` | 6,565 |
74,259,497 | ```
n: 8
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63
```
How to print a number table like this in python with n that can be any number?
I am using a very stupid way to pr... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74259497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20376552/"
] | If you have more than one reference to a list, then `.clear()` clears the list and preserves the references, but the assignment creates a new list and does not affect the original list.
```
a = [1,2,3]
b = a # make an additional reference
b.clear()
print(a, b)
# [] []
a = [1,2,3]
b = a # make an additional reference
b... | When you do `array.clear()`, that tells that existing object to clear itself. When you do `array = []`, that creates a brand-new object and replaces the one it had before. The new `array` object is unrelated to the one you stored in `self.array`. | 6,570 |
33,617,551 | I'm dealing with large raster stacks and I need to re-sample and clip them.
I read list of Tiff files and create stack:
```
files <- list.files(path=".", pattern="tif", all.files=FALSE, full.names=TRUE)
s <- stack(files)
r <- raster("raster.tif")
s_re <- resample(s, r,method='bilinear')
e <- extent(-180, 180, -60, 9... | 2015/11/09 | [
"https://Stackoverflow.com/questions/33617551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2124725/"
] | I second @JoshO'Brien's suggestion to use GDAL directly, and `gdalUtils` makes this straightforward.
Here's an example using double precision grids of the same dimensions as yours. For 10 files, it takes ~55 sec on my system. It scales linearly, so you'd be looking at about 33 minutes for 365 files.
```
library(gdalU... | For comparison, this is what I get:
```
library(raster)
r <- raster(nrow=3000, ncol=7200, ymn=-60, ymx=90)
s <- raster(nrow=2160, ncol=4320)
values(s) <- 1:ncell(s)
s <- writeRaster(s, 'test.tif')
x <- system.time(resample(s, r, method='bilinear'))
# user system elapsed
# 15.26 2.56 17.83
```
10 files ... | 6,571 |
71,344,145 | So I'm making a very simple battle mechanic in python where the player will be able to attack, defend
or inspect the enemy :
```
print("------Welcome To The Game------")
player_hp=5
player_attack=3
enemy_hp=10
enemy_attack=2
while player_hp !=0 and enemy_hp !=0:
Choice=input("""What will you do:
A.Attack... | 2022/03/03 | [
"https://Stackoverflow.com/questions/71344145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18367808/"
] | You should not rely on sets to provide random arrangements of values.
In this case you should use `random.randint` function.
Example:
```
import random
if Choice== "B":
player_hp -= random.randint(1, 5)
```
Also as Shayan pointed out you are not modifying `player_hp` by doing `player_hp - ...` you should use `p... | >
> how can I make it that everytime you press the defend option the value is different
>
>
>
You should look at using the `random` module
Ignoring the game logic, here's a simple example
```
import random
dice_values = list(range(1, 7)) # example for six-sided die
alive = True
while alive:
value = random.c... | 6,572 |
48,515,581 | I have seen two ways of visualizing transposed convolutions from credible sources, and as far as I can see they conflict.
My question boils down to, for each application of the kernel, do we go from many (e.g. `3x3`) elements with input padding to one, or do we go from one element to many (e.g. `3x3`)?
*Related quest... | 2018/01/30 | [
"https://Stackoverflow.com/questions/48515581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747801/"
] | Strided convolutions, deconvolutions, transposed convolutions all mean the same thing. Both papers are correct and you don't need to be doubtful as both of them are [cited](https://scholar.google.com/) a lot. But the distil image is from a different perspective as its trying to show the artifacts problem.
The first v... | Good explanation from Justin Johnson (part of the Stanford cs231n mooc):
<https://youtu.be/ByjaPdWXKJ4?t=1221> (starts at 20:21)
He reviews strided conv and then he explains transposed convolutions.
 | 6,578 |
12,760,271 | I have a fasta file as shown below. I would like to convert the [three letter codes](https://en.wikipedia.org/wiki/Amino_acid#Table_of_standard_amino_acid_abbreviations_and_properties) to one letter code. How can I do this with python or R?
```
>2ppo
ARGHISLEULEULYS
>3oot
METHISARGARGMET
```
desired output
```
>2pp... | 2012/10/06 | [
"https://Stackoverflow.com/questions/12760271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725152/"
] | Here is a way to do it in R:
```
# Variables:
foo <- c("ARGHISLEULEULYS","METHISARGARGMET")
# Code maps:
code3 <- c("Ala", "Arg", "Asn", "Asp", "Cys", "Glu", "Gln", "Gly", "His",
"Ile", "Leu", "Lys", "Met", "Phe", "Pro", "Ser", "Thr", "Trp",
"Tyr", "Val")
code1 <- c("A", "R", "N", "D", "C", "E", "Q", "G", "H", "I",... | Python 3 solutions.
In my work, the annoyed part is that the amino acid codes can refer to the modified ones which often appear in the PDB/mmCIF files, like
>
> 'Tih'-->'A'.
>
>
>
So the mapping can be more than 22 pairs. The 3rd party tools in Python like
>
> Bio.SeqUtils.IUPACData.protein\_letters\_3to1
> ... | 6,580 |
27,451,561 | I'm new to stack so this might be a very silly mistake.
I'm trying to setup a one node swift configuration for a simple proof of concept. I did follow the [instructions](http://docs.openstack.org/juno/install-guide/install/apt/content/ch_swift.html). However, something is missing. I keep getting this error:
```
root@l... | 2014/12/12 | [
"https://Stackoverflow.com/questions/27451561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/224982/"
] | `JSON.parse(data)` will turn the data you showing into a JavaScript object, and there are a TON of ways to use the data from there. Example:
```
var parsedData = JSON.parse(data),
obj = {};
for(var key in parsedData['model']){
obj[key] = parsedData['model'][key]['id'];
}
```
Which would give you a resulting... | You want to use JSON.parse(), but it returns the parsed object, so use it thusly:
```
var parsed = JSON.parse(data);
```
then work with parsed. | 6,590 |
10,775,007 | I want to create a python script which could be used to execute Android adb commands.
I had a look at <https://github.com/rbrady/python-adb> but can't seem to make it work perfectly.
Any suggestions? | 2012/05/27 | [
"https://Stackoverflow.com/questions/10775007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1391277/"
] | This tool should do the work.
<https://pypi.python.org/pypi/pyadb/0.1.1>
I had to modify a few functions to have it operate on Python 2.7 and use subprocess instead. Here the modified code in my version:
```
def __build_command__(self,cmd):
if self.__devices is not None and len(self.__devices) > 1 and self.__targ... | Use a `monkeyrunner` tool for that. From it's [documentation](https://developer.android.com/studio/test/monkeyrunner/index.html):
>
> Besides using the monkeyrunner API itself, you can use the standard Python os and subprocess modules to call Android tools such as Android Debug Bridge.
>
>
> | 6,591 |
13,561,220 | Think about this code:
```
#!/usr/bin/env python
from threading import Thread
count = 0
def test():
global count
for i in range(10):
count = count + 1
if __name__ == '__main__':
for i in range(1000):
Thread(target = test).start()
print count
```
I use multiple threads, but the res... | 2012/11/26 | [
"https://Stackoverflow.com/questions/13561220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802585/"
] | You do need one. Although multithreading works differently in Python, due to the [Global Interpreter Lock](http://wiki.python.org/moin/GlobalInterpreterLock), operations that are not atomic in Python-bytecode will still need locking.
In you case, you can inspect the bytecode for your function `test` (`dis.dis(test)`):... | Definitely you should use Lock. You have got a correct answer in such simple case. Try to make it for range(100000) in **main**. You will see the problem. In my machine the result is 999960, but it is random result. Errors will arise depending on system load and so on. | 6,594 |
72,852,359 | I would like to know if someone can answer why I cant seem to get a python gstreamer pipline to work without sudo in linux. I have a very small gstreamer pipline and it fails to open the gstreamer if I dont run with sudo infront of python.
I have soon depleted my options, any help would be appriciated. (Using Jetson Or... | 2022/07/04 | [
"https://Stackoverflow.com/questions/72852359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8610564/"
] | accessToken is correct just don't forget use:
```
use Laravel\Passport\HasApiTokens;
```
instead of:
```
use Laravel\Sanctum\HasApiTokens;
```
This is correct: `$token = $user->createToken('Laravel Password Grant Client')->accessToken;` | you have to log in user first after the login token is created.
$data['email'] = request email
$data['password'] = request password
```
Auth::attempt($data);
$loginUser = Auth::user();
$token = $loginUser->createToken('Laravel Password Grant Client')->accessToken;
$loginUser->accessToken = $token;
``` | 6,597 |
64,472,414 | I'm using `isbnlib.meta` which pulls metadata (book title, author, year publisher, etc.) when you enter in an isbn. I have a dataframe with 482,000 isbns (column title: isbn13). When I run the function, I'll get an error like `NotValidISBNError` which stops the code in it's tracks. What I want to happen is if there is ... | 2020/10/21 | [
"https://Stackoverflow.com/questions/64472414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12020223/"
] | * The current implementation for extracting isbn meta data, is incredibly slow and inefficient.
+ As stated, there are 482,000 unique isbn values, for which the data is being downloaded multiple times (e.g. once for each column, as the code is currently written)
* It will be better to download all the meta data at onc... | Hard to answer without seeing the code, but [try/except](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) should really be able to handle this.
I am not an expert here, but look at this code:
```
l = [0, 1, "a", 2, 3]
for item in l:
try:
print(item + 1)
except TypeError as e:
... | 6,599 |
53,480,409 | I have installed the bloomberg Python API and set the `BLPAPI_ROOT` to the VC++ folder.
However, when I import `blpapi`, I got the following error.
How to get rid of these errors?
Thank you very much.
```
import blpapi
Traceback (most recent call last):
File "C:\Users\user\AppData\Roaming\Python\Python36\site-pa... | 2018/11/26 | [
"https://Stackoverflow.com/questions/53480409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9087866/"
] | I did 2 things to solve an issue similar to that:
1- I installed Microsoft Visual Studio with the following components
* C++/CLI Support
* VC++ 2015.3 v14.00 (v140) toolset for desktop
* Visual C++ MFC for x86 and x64
* Visual C++ ATL for x86 and x64
2- I manually copied the .dll files in C++API\lib (blpapi3\_32.dll... | Please set BLPAPI\_ROOT environment variable to the location where the blpapi C++ SDK is located. | 6,600 |
1,440,233 | I want to intercept and transform some automated emails into a more readable format. I believe this is possible using VBA, but I would prefer to manipulate the text with Python. Can I create an ironpython client-side script to pre-process certain emails?
EDIT:
I believe this can be done with outlook rules. In Outlook ... | 2009/09/17 | [
"https://Stackoverflow.com/questions/1440233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20712/"
] | I can only offer you a pointer. Years ago, I used a Bayesian spam filter with Outlook. It was written in Python, and provided an Outlook plug-in that would filter incoming mail. The name of the software was [*SpamBayes*](http://spambayes.sourceforge.net/), and the project is still online. As it is open source, you will... | There is an answer here: [how to trigger a python script in outlook using rules?](https://stackoverflow.com/questions/13265861/how-to-trigger-a-python-script-in-outlook-using-rules) that may help you. You can make a simple VBA script to trigger the python script. | 6,602 |
63,896,043 | I am creating my first django app in django 3.1.1. There are video tutorials for old django versions and they don't always work... I want to create HTML pages for both home and about sections. I have already written some HTML files, but the
```
def home(request):
return render(request, 'home.html')
```
doesn't w... | 2020/09/15 | [
"https://Stackoverflow.com/questions/63896043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14224948/"
] | Alright, found it myself with your inspiration :)
Thank you, @Selcuk and @m.arthur. Thanks for contributing @Mahmoud Ishag too :)
The answer lies in there I mustn't have created this app as a project and there was a short string missing in templates:
```
TEMPLATES = [
{
'BACKEND': 'django.template.backend... | Django look for the template in folder called `templates` you need to create that folder inside your app folder and put `home.html` inside it. | 6,605 |
43,413,914 | I recently found out that scrapy is a great library for scraping so i tried to install scrapy on my machine, but when i tried to do `pip install scrapy` it installed for a while and threw me this error..
```
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub... | 2017/04/14 | [
"https://Stackoverflow.com/questions/43413914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7618421/"
] | Scrapy docs now recommend using [Conda](https://conda.io/miniconda) for Windows installation:
<https://doc.scrapy.org/en/latest/intro/install.html#windows> | This error comes up when you don't have Windows SDK installed.
When you used Build Tools or Visual Studio to compile, often you need both the C++ compiler and Windows SDK. In the Build Tools, there is a "Custom" installation option which enables you to select to install both C++ and Windows SDK. In Visual Studio, you ... | 6,606 |
43,989,929 | I'm trying to use `pytesseract` for the first time. I'm also not so confortable with python. I've created a new folder called `python_test` on my desktop. I'm on Mac. In this folder I have a `test.png` file and a py script :
```
from pytesseract import image_to_string
from PIL import Image
print image_to_string(Image... | 2017/05/15 | [
"https://Stackoverflow.com/questions/43989929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6273496/"
] | I got the same error as you, installing the `tesseract` package fixed it (or `tesseract-ocr` on debian/ubuntu). It contains the native code library used under the hood by `pytesseract`.
An image load error seems like an odd way for the library to fail if the underlying native library is not installed, but there you go... | I also had the error when I used first time `image_to_string`.
You have to change the the following line in the `pytesseract.py` file.
```
tesseract_cmd = 'C:\\Tesseract-OCR\\tesseract'
```
*Note: I'm using windows.* | 6,607 |
4,942,305 | The Windows console has been Unicode aware for at least a decade and perhaps as far back as Windows NT. However for some reason the major cross-platform scripting languages including Perl and Python only ever output various 8-bit encodings, requiring much trouble to work around. Perl gives a "wide character in print" w... | 2011/02/09 | [
"https://Stackoverflow.com/questions/4942305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/527702/"
] | Michael Kaplan has series of blog posts about the `cmd` console and Unicode that may be informative (while not really answering your question):
* [Conventional wisdom is retarded, aka What the @#%&\* is \_O\_U16TEXT?](https://web.archive.org/web/20130101094000/http://www.siao2.com/2008/03/18/8306597.aspx)
* [Anyone wh... | Are you sure your script would output Unicode on some other platform correctly? "wide character in print" warning makes me very suspicious.
I recommend to look over this [overview](http://en.wikibooks.org/wiki/Perl_Programming/Unicode_UTF-8) | 6,608 |
10,474,942 | I try my very best to never use php and as thus i am not well versed in it I am having a issue that I don't understand at all here I have tried a number of things including not including the table reference in /config changing to from localhost as mysql host ect.
It will probably be something exceedingly obvious but i... | 2012/05/06 | [
"https://Stackoverflow.com/questions/10474942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1231175/"
] | Access denied means you're using the wrong username/password, and/or the account you're accessing has not be properly created in MySQL.
What does a `show grants for username@10.1.1.43` show?
if you created the account as `username@machinename` and MySQL is unable to do a reverse DNS lookup to change your IP back to m... | Check the following:
1) You entered the right database hostname (this is not always localhost), username and password?
2) The user has permissions on database.
Let me know if you don't know how to check. | 6,618 |
38,570,698 | This is my first time using raw sockets (yes, I need to use them as I must modify a field inside a network header) and all the documentation or tutorials I read describe a solution to sniff packets but that is not exactly what I need. I need to create a script which intercepts the packet, process it and sends it furthe... | 2016/07/25 | [
"https://Stackoverflow.com/questions/38570698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6104632/"
] | Your description seems to be different from what your title suggest. My understanding is that you want to receive, modify and possibly drop incoming network packets. And this is to be done on Linux. In that case I suggest you use a netfilter prerouting hook, which will make things a lot simpler (and likely more stable)... | I suppose that your Linux box is configured as a router (not a bridge). The packet will pass through your Linux because you have enabled **IP Forwarding**. So there are two solution:
***Solution 1:***
Disable **IP Forwarding** and then receive the packet from one interface and do the appropriate task (forwarding to ... | 6,619 |
35,393,672 | python 2.7: Count how many numbers are entered by the user.
I can't figure out how to count the raw\_input... here's what I have so far:
```
while True:
datum = raw_input('enter a number: ')
if datum == 'done': break
count = 0
for line in datum: ... | 2016/02/14 | [
"https://Stackoverflow.com/questions/35393672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5925494/"
] | The reason for the endless loop is dead simple.
You are *never* updating the value of `$terms` inside the loop body, which is being used in loop condition.
So the loop body is executed either zero times or infinitely.
---
The fix seems to replace the `while` with the `if`, because you handle the parent via a recur... | The misunderstanding lies in the scope of the `$terms` variable. This variable has scope that is local to the function call it exists in. The loop
```
while ($terms > 0) {
//do some logic
$parent_id = $terms->parent;
$this->parent_category_has_fiance($parent_id);
}
```
is referencing the `$terms` variabl... | 6,620 |
55,758,883 | When i tried to install openCV using pip3 install opencv-python i got this error
Could not find a version that satisfies the requirement opencv-python (from versions: )
No matching distribution found for opencv-python
i have tried upgrading pip using
```
pip install --upgrade pip
```
and
```
curl https://bootst... | 2019/04/19 | [
"https://Stackoverflow.com/questions/55758883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8923850/"
] | Here is the code corrected, there are. Which are to be deleted
I also added `math.round` to get rounded result:
```html
<html>
<head>
<script>
function calcAmount() {
let userAmount = document.getElementById("amount").value;
let level1 = 351;
if (userAmount <= level1) {
document... | Three things:
* You had `.` in your ID selectors, these shouldn't be there (they should be `#` but only in a `querySelector` method).
* You were calculating `calcLevel1` straightaway, which meant it was `0 * 7 / 100` which is `0`.
* You needed to calculate `calcLevel1` with `amount.value`, which means you can remove `... | 6,621 |
47,041,267 | I'm currently trying to program and learn python, while making a project with the raspberry pi zero w. So far I'm just trying to get it to start recording video using picamera in python, as well as stream that video so I can monitor what the output is on my phone. However as it currently stands it only starts recording... | 2017/10/31 | [
"https://Stackoverflow.com/questions/47041267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8863714/"
] | >
> However as it currently stands it only starts recording video once I connect to it via some sort of streaming program. What I'd like for it to do is start recording the video at the start of the program and be able to connect to it whenever I'd like to monitor it.
>
>
>
This is due to the following line of cod... | KillerXtreme, This should be the code you were looking for 5 years ago (namely, you can connect and reconnect to this over and over with no hiccups)!
Hope this helps somebody!
```
import socket
import picamera
from threading import Thread
def stop_recording(cam):
try:
cam.stop_recording()
except Excep... | 6,622 |
42,630,281 | I have a python script which is supposed to loop through all files in a directory and set the date of each file to the current time. It seems to have no effect, i.e. the Date column in the file explorer shows no change. I see the code looping through all files, it just appears that the call to `utime` has no effect.
T... | 2017/03/06 | [
"https://Stackoverflow.com/questions/42630281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1978617/"
] | You've got three issues:
1. You're using the file name, not the full path, when `touch`ing, so all the `touch`ing occurs in the working directory
2. You're stripping the file extension too, so the touched files lack extensions
3. You're touching files to which you have an open file handle, and on Windows, on Python 2.... | os.utime does work on Windows but probably you are looking at the wrong date in explorer. os.utime does not modify the creation date (which it looks like is what is used in the date field in explorer). It does update the "Date modified" field. You can see this if you right click on the category bar and check the "date ... | 6,623 |
46,742,947 | I have a folder full of files that need to be modified in order to extract the true file in it's real format.
I need to remove a certain number of bytes from BOTH the beginning and end of the file in order to extract the data I am looking for.
How can I do this in python?
* I need this to work recursively on an e... | 2017/10/14 | [
"https://Stackoverflow.com/questions/46742947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7838844/"
] | 1. Recursive iteration over files [os.walk](https://docs.python.org/3/library/os.html#os.walk)
2. Change position in file: [f.seek](https://docs.python.org/3/tutorial/inputoutput.html?highlight=seek)
3. Get file size: [os.stat](https://docs.python.org/3/library/os.html#os.stat)
4. Remove data from current position to e... | Your question is pretty badly constructed, but as this is somewhat advanced stuff I'll provide you with a code.
You can now use os.walk() to recursively traverse directory you want and apply my slicefile() function.
This code does the following:
1. After checking validity of start and end arguments it creates a memo... | 6,624 |
14,416,914 | I am new to bash and shell but I am running a debian install and I am trying to make a script which can find a date in the past without having to install any additional packages. From tutorials I have got to this stage:
```
#!/bin/sh
#
# BACKUP DB TO S3
#
# VARIABLES
TYPE="DATABASE"
DAYS="30"
# GET CURRENT DATETIME
... | 2013/01/19 | [
"https://Stackoverflow.com/questions/14416914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738522/"
] | Try
```
date -d '30 days ago'
```
should do on debian. | You could modify the python script instead -- that way you would not depend on particular implementation of `date` | 6,625 |
35,642,131 | I am training a problem such that my output (y) could be more than one class. For example, the SVM could say, this input vector is class 1, but it could also say, this input vector is classes 1 AND 5. This is not the same as a multiclass SVM problem, where the output could be ONE of multiple classes. My output could be... | 2016/02/26 | [
"https://Stackoverflow.com/questions/35642131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5983697/"
] | Yes, use a for loop using the `length` method.
You can get the letter at a given position using [CharSequence#charAt](https://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html#charAt-int-).
`String` implements `CharSequence` so you can do `a.charAt(i);` | I like the `charAtSequence()` suggested by pyb, my own first instinct however would be char array. I think they both will work the same though. I didint want to write the whole code for you, but I hope this helps...
```
char [] _a = a.toCharArray(); // note 1
//do the same for the b string here...
else if (a.... | 6,630 |
73,739,734 | I am currently able to use quick fix to auto import python functions from external typings such as `from typing import List`.
[Python module quick fix import](https://i.stack.imgur.com/q3m7F.png)
However, I am unable to detect local functions/classes for import. For example: If I have the data class `SampleDataClass`... | 2022/09/16 | [
"https://Stackoverflow.com/questions/73739734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20008915/"
] | Turns out the latest versions for Pylance broke quick-fix imports and any extra path settings for VSCode. When I rolled back the version to `v2022.8.50` it now works again.
I filed an issue here: <https://github.com/microsoft/pylance-release/issues/3353>. | According to an [issue](https://github.com/microsoft/pylance-release/issues/3324) I raised in github earlier, the developer gave a reply.
Custom code will **not** be added to the autocomplete list at this time (unless it has already been imported). This is done to prevent users from having too many custom modules, whi... | 6,635 |
72,631,459 | I am trying to test an API that sends long-running jobs to a queue processed by Celery workers.. I am using RabbitMQ running in a Docker container as the message queue. However, when sending a message to the queue I get the following error: `Error: [Errno 111] Connection refused`
Steps to reproduce:
* Start RabbitMQ ... | 2022/06/15 | [
"https://Stackoverflow.com/questions/72631459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6131554/"
] | You can't connect to rabbitmq on `localhost`; it's not running in the same container as your Python app. Since you've exposed rabbit on your host, you can connect to it using the address of your host. One way of doing that is starting the app container like this:
```
docker run -it -p 8000:8000 --add-host host.docker.... | Update **tasks.py**
```
import time
celery = Celery('tasks', broker='amqp://user:pass@host:port//')
@celery.task(name='update_db')
def update_db(num: int) -> None:
time.sleep(30)
return
``` | 6,636 |
6,999,522 | I'm looking to generate, from a large Python codebase, a summary of heap usage or memory allocations over the course of a function's run.
I'm familiar with [heapy](http://guppy-pe.sourceforge.net/), and it's served me well for taking "snapshots" of the heap at particular points in my code, but I've found it difficult ... | 2011/08/09 | [
"https://Stackoverflow.com/questions/6999522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/104200/"
] | I would use [`sys.settrace`](http://docs.python.org/library/sys.html#sys.settrace) at program startup to register a custom tracer function. The custom\_trace\_function will be called for each line of code. Then you can use that function to store information gathered by heapy or [meliae](https://launchpad.net/meliae) in... | You might be interested by [memory\_profiler](https://pypi.org/project/memory-profiler/). | 6,637 |
35,667,105 | I am an amateur python programer with 2 months of experience. I am trying to write a GUI to-do list through tkinter. The actual placement of the buttons are not important. I can play around with those after. I need some help with displaying the appended item to the list. In the program, it updates well on the digit, bu... | 2016/02/27 | [
"https://Stackoverflow.com/questions/35667105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5989438/"
] | Just replace the package name with your package name / applicationId
You do not need to publish the app first, just keep the same applicationId when you eventually upload the app.
For example
<https://play.google.com/store/apps/details?id=com.instagram.android>
market://details?id=com.instagram.android
app/build.g... | No need to update the app. First you can do it with a temp link with dynamic process. After your app publish, you can replace that link with playstore link. | 6,638 |
67,883,300 | I want to print all Thursdays between these date ranges
```
from datetime import date, timedelta
sdate = date(2015, 1, 7) # start date
edate = date(2015, 12, 31) # end date
```
What is the best pythonic way to do that? | 2021/06/08 | [
"https://Stackoverflow.com/questions/67883300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/778942/"
] | using your `sdate.weekday() # returns int between 0 (mon) and 6 (sun)`:
```
sdate = ...
while sdate < edate:
if sdate.weekday() != 3: # not thursday
sdate += timedelta(days=1)
continue
# It is thursday
print(sdate)
sdate += timedelta(days=7) # next week
``` | ```py
import datetime
import calendar
def weekday_count(start, end, day):
start_date = datetime.datetime.strptime(start, '%d/%m/%Y')
end_date = datetime.datetime.strptime(end, '%d/%m/%Y')
day_count = []
for i in range((end_date - start_date).days):
if calendar.day_name[(start_date + dateti... | 6,641 |
64,867,992 | I am using beautiful soup (BS4) with python to scrape data from the yellowpages through the waybackmachine/webarchive. I am able to return the Business name and phone number easily but when I attempt to retrieve the website url for the business, I only return the entire div tag.
```
#Import Dependencies
from splinter ... | 2020/11/17 | [
"https://Stackoverflow.com/questions/64867992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10930010/"
] | Simple and very neat solution: *(added my comments so you can understand what I did)*
```
start = int(input('enter the starting range: '))
end = int(input('enter the ending range: '))
#create an empty list
numbers = []
for d in range(start,end):
if d % 2 != 0:
#if number is odd, add it to the list
num... | Print the message before the loop then the numbers during the loop:
```py
start = int(input('enter the starting range:'))
end = int(input('enter the ending range:'))
# use end='' to avoid printing a newline at the end
print(f'The odd numbers between {start} & {end} is: ', end='')
should_print_comma = False
for d in ra... | 6,650 |
43,247,031 | I have a file named phone.py which give me output as(in terminal):
```
+911234567890
+910123321423
```
There can be more number of outputs.
Another file named email.py which produces(in terminal):
```
and@abc.com
bcd@cdc.com
```
or more.
And I have a JSON File whose structure is as follows:
```
{"One":"Some d... | 2017/04/06 | [
"https://Stackoverflow.com/questions/43247031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6541394/"
] | You can obtain the stdout from `subprocess.run` simply by `resp.stdout`, where `resp` is the returned object. | As already mentioned by Rishav, you need to assign the output to a variable & then use it to get the related attributes.
[Sample usage](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess) -
```
>>> import subprocess
>>> out = subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)... | 6,654 |
47,227,445 | Im trying to make a while loop in python, but the loop keeps looping infinitely.
Here's what I have so far:
```
def pvalue(num):
ans = ''
while num > 0:
if 1 <= num <= 9:
ans += 'B'
num -= 1
if num >= 10:
ans += 'A'
num -= 10
return ans
```
... | 2017/11/10 | [
"https://Stackoverflow.com/questions/47227445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5016648/"
] | You may want to learn about the [break statement](https://docs.python.org/3/reference/simple_stmts.html#break).
As for your code:
```
def pvalue(num):
ans = ''
while num > 0:
if num >= 10:
ans += 'A'
num -= 10
else:
ans += 'B'
num -= 1
return... | Use the break statement to get out of the loop.
```
def pvalue(num):
ans = ''
while num > 0:
if 1 <= num <= 9:
ans += 'B'
num -= 1
if num >= 10:
ans += 'A'
num -= 10
if num<=0:
break
return ans
``` | 6,655 |
68,262,836 | I'm trying to use an array of dictionaries in python as arguement to a custom dash component and use it as array of objects
in python :
```
audioList_py = [
{
"name": "random",
"singer": 'waveGAN\'s music',
"cover":
'link_1.jpg',
"musicSrc":
'link_1.mp3',
},... | 2021/07/05 | [
"https://Stackoverflow.com/questions/68262836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13652942/"
] | Make sure you run `npm run build` after you make a change to your custom React component. With those proptypes you shouldn't get that error. If I remove the `audios` proptype I can reproduce that error.
Besides that you pass a value to the `audios` property:
```
music_component.MusicComponent(audios=audioList_py)
``... | Issue fixed, I should run : `npm run build:backends` to generate the Python, R and Julia class files for the components, but instead I was executing `npm run build:js` and this command just generate the JavaScript bundle (which didn't know about the new props).
And set the audios property in the component to be like s... | 6,656 |
61,976,835 | I'm new to python and I've seen two different ways to initialize an empty list:
```
# way 1
empty_list = []
# way 2
other_empty_list = list()
```
Is there a "preferred" way to do it? Maybe one way is better for certain conditions than the other?
Thank you | 2020/05/23 | [
"https://Stackoverflow.com/questions/61976835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8947060/"
] | No there isn't much of a difference, you can neglect the difference and pick anyone of them
As most of the times it's a one or limited execution any difference in execution won't have much impact | Using parenthesis will create a tuple, which is immutable. A list uses brackets. | 6,657 |
66,062,702 | I am trying to install the jupyterlab plotly extension with this command (according to <https://plotly.com/python/getting-started/>):
**jupyter labextension install jupyterlab-plotly@4.14.3**
I get this error:
```
An error occured.
ValueError: Please install Node.js and npm before continuing installation. You may be... | 2021/02/05 | [
"https://Stackoverflow.com/questions/66062702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11904988/"
] | No, you have **not** installed node.js. You installed some kind of Python bindings for node ([python-nodejs](https://pypi.org/project/nodejs/), with its [repository](https://github.com/markfinger/python-nodejs) archived by the author) which itself require an actual nodejs. It is dangerous to install stuff from PyPI wit... | First install nodejs latest version
`conda install nodejs -c conda-forge --repodata-fn=repodata.json`
Then install jupyterlab extension:
`jupyter labextension install jupyterlab-plotly@4.14.3`
Then **RESTART JUPYTER LAB** | 6,660 |
36,227,688 | I have a python program that I usually run as a part of a package:
```
python -m mymod.client
```
in order to deal with relative imports inside "mymod/client.py." How do I run this with pdb - the python debugger. The following does not work:
```
python -m pdb mymod.client
```
It yields the error:
```
Error: mymo... | 2016/03/25 | [
"https://Stackoverflow.com/questions/36227688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3357587/"
] | I *think* I have a solution.
Run it like this:
```
python -m pdb path/mymod/client.py arg1 arg2
```
that will run it as a script, but will not treat it as a package.
At the top of client.py, the first line should be:
```
import mymod
```
That will get the package itself loaded.
I am still playing with this,... | This is not possible. Though unstated in documentation, Python will not parse two modules via the `-m` command line option. | 6,661 |
56,798,328 | I am just beginning to use python and could use some help! I was working on a rock, paper, scissors game and I wanted to add a restart option once either the human or computer reaches 3 wins.
I have looked all over for some answers but from all the other code I looked at seemed way out of my league or extremely diffe... | 2019/06/27 | [
"https://Stackoverflow.com/questions/56798328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11606900/"
] | You already have the loop to do this. So when you want to "restart" your game, you really just need to reset the scores.
Starting from your win/lose conditions:
```
#Win/lose restart point?
if player_score == 3:
print("-----You Win!-----")
replay = input("Would you like to play again?")
if replay.upper().... | You need to get user input in the `while` loop and set `keep_playing` accordingly.
```
while keep_playing == True:
cmove = random.choice(moves)
pmove = input("What is your move: Rock, Paper, or Scissors?")
print("The computer chose", cmove)
#Logic to game
if cmove == pmove:
print("It's ... | 6,662 |
57,420,171 | I am writing a batch file that lies somewhere in a folder structure alongside a .venv folder (python virtual environment)
```
KnownFolderName
|
+-- 1.0.0
| |
| +-- .venv
| |
| +-- folder
| |
| +-- folder
| |
| +-- batch.bat
|
+-- 1.0.1
|
+-- .venv
|
+-- folder
|
+-- ba... | 2019/08/08 | [
"https://Stackoverflow.com/questions/57420171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/869598/"
] | Got it. Of course as soon as I post the question the answer appears!
After trying all sorts of ways to extract the string from the cwd I found that just looping backwards is the way:
```
:loop
IF EXIST .venv (
cd .venv\Scripts
) ELSE (
cd ..
goto loop
)
```
Then you can return to the original location with the stan... | What about the following approach which makes use of string manipulation features:
```cmd
@echo off
set "BATCH=%~f0"
echo ABSOLUTE BATCH PATH: "%BATCH%"
set "RELATIVE=%BATCH:*\KnownFolderName\=%"
echo RELATIVE BATCH PATH: "%RELATIVE%"
set "TEST=%BATCH%|"
call set "ROOT=%%TEST:\%RELATIVE%|=%%"
echo ROOT DIRECTORY PATH:... | 6,663 |
68,708,540 | I want to generate random number between 0 and 1 in **python code** but only get 2 numbers after sign .
Example:
```
0.22
0.25
0.9
```
I have searched many sources but have not found the solution. Can you help me? | 2021/08/09 | [
"https://Stackoverflow.com/questions/68708540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16462598/"
] | Want this?
```
import random
round(random.random(), 2)
``` | Try this `print(round(random.random(), 2))` | 6,664 |
49,544,701 | I'm relatively new to python, and I am trying to build a program that can visit a website using a proxy from a list of proxies in a text file, and continue doing so with each proxy in the file until they're all used. I found some code online and tweaked it to my needs, but when I run the program, the proxies are succes... | 2018/03/28 | [
"https://Stackoverflow.com/questions/49544701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9566525/"
] | Your problem is with these nested loops, which don't appear to be doing what you want:
```
proxy = []
while count < 10:
proxy.append(proxylist[count].strip())
count += 1
for i in proxy:
Visiter(i)
```
The outer loop builds up the `proxy` list, adding one value each time un... | `while count < 10:
proxy.append(proxylist[count].strip())
count += 1
for i in proxy:
Visiter(i)`
The for loop within the while loop means that every time you hit proxy.append you'll call Visiter for *every* item already in proxy. That might explain why you're getting multiple hits per proxy.
As far as the out of ... | 6,666 |
4,778,679 | i have no way of upgrade to python 2.7 or 3.1 so i am stuck with python 2.6 on my ubuntu 10.04 machine.
will i still be able to find host that supports python 2.6?
is using python 2.6 still consider outdated or bad practice? | 2011/01/24 | [
"https://Stackoverflow.com/questions/4778679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62617/"
] | 2.6 will be around for a long time. There are many machines that still run even 2.4, so you're fine. | Python3.1 is in the repositories for 10.04
```
$ apt-cache show python3
Package: python3
Priority: optional
Section: python
Installed-Size: 76
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Original-Maintainer: Matthias Klose <doko@debian.org>
Architecture: all
Source: python3-defaults
Version: ... | 6,667 |
61,804,295 | I am using python to do some data cleaning and i've used the datetime module to split date time and tried to create another column with just the time.
My script works but it just takes the last value of the data frame.
Here is the code:
```
import datetime
i = 0
for index, row in df.iterrows():
date = dateti... | 2020/05/14 | [
"https://Stackoverflow.com/questions/61804295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13543531/"
] | `df['minutes'] = date.minute` reassigns the entire `'minutes'` column with the scalar value `date.minute` from the last iteration.
You don't need a loop, as 99% of the cases when using pandas.
You can use vectorized assignment, just replace `'source_column_name'` with the name of the column with the source data.
```... | Seems like you're trying to get the time column from the datetime which is in string format. That's what I understood from your post.
Could you give this a shot?
```
from datetime import datetime
import pandas as pd
def get_time(date_cell):
dt = datetime.strptime(date_cell, "%Y-%m-%dT%H:%M:%SZ")
return dateti... | 6,672 |
66,402,926 | I am new to python and I want to know how to create empty column with a specific number. Let's say I want to create 20 columns. What I tried:
```
import pandas as pd
num =20
for i in range(num):
df = df + pd.DataFrame(columns=['col'+str(i)])
```
But I got the unwanted result:
```
Empty DataFrame
Columns: [col... | 2021/02/27 | [
"https://Stackoverflow.com/questions/66402926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13230133/"
] | Assuming you wish to create an empty dataframe, the solution is to remove the for loop, and use a list comprehension for the column names:
```
import pandas as pd
num =20
df = pd.DataFrame(columns=['col'+str(i) for i in range(num)])
``` | Instead of adding dataframes together, let's just create a dictionary with the mappings you'd like, and create one dataframe:
```
data = {"col" + str(i): [] for i in range(20)}
df = pd.DataFrame(data)
#Empty DataFrame
#Columns: [col0, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, co... | 6,673 |
35,328,941 | In python / numpy - is there a way to build an expression containing factorials - but since in my scenario, many factorials will be duplicated or reduced, wait until I instruct the run time to compute it.
Let's say `F(x) := x!`
And I build an expression like `(F(6) + F(7)) / F(4)` - I can greatly accelerate this, eve... | 2016/02/11 | [
"https://Stackoverflow.com/questions/35328941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127257/"
] | As @Oleg has suggested, you can do this with sympy:
```
import numpy as np
import sympy as sp
# preparation
n = sp.symbols("n")
F = sp.factorial
# create the equation
f = (F(n) + F(n + 1)) / F(n - 2)
print(f) # => (factorial(n) + factorial(n + 1))/factorial(n - 2)
# reduce it
f = f.simplify()
print(f)... | Maybe you could look into increasing the efficiency using table lookups if space efficiency isn't a major concern. It would greatly reduce the number of repeated calculations. The following isn't terribly efficient, but it's the basic idea.
```
cache = {1:1}
def cached_factorial(n):
if (n in cache):
return... | 6,674 |
34,394,578 | I am using python 2.7.8. I have a website which contains text written with bullets list which is ordered list aka <**ol**> . I want to extract those text i.e
```
Coffee
Tea
Milk
```
My html code:
```
<!DOCTYPE html>
<html>
<body>
<ol type="I">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<ol type="a">
... | 2015/12/21 | [
"https://Stackoverflow.com/questions/34394578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3440716/"
] | You can see why it is that beautifulsoup function does not work for your variable 'ul" by inserting this line while commenting out the line you previously had.
```
print ul
"""print(ul.get_text(' ', strip=True))"""
```
What is happening is that your variable ul is storing the string:
1. C99 standard guarantees uniq... | I never used the BeautifulSoup, but I do this with regular expression:
```
import re
html = """<!DOCTYPE html>
<html>
<body>
<ol type="I">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<ol type="a">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<ol type="1">
<li>Coffee</li>
<li>Tea</li>
<li>... | 6,675 |
4,387,847 | Assuming i have a class that implements several methods. We want a user to chose to which methods to run among the exisiting methods or he can decide to add any method on\_the\_fly.
from example
```
class RemoveNoise():
pass
```
then methods are added as wanted
```
RemoveNoise.raw = Raw()
RemoveNoise.bais =... | 2010/12/08 | [
"https://Stackoverflow.com/questions/4387847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/535019/"
] | Functions can be added to a class at runtime.
```
class Foo(object):
pass
def bar(self):
print 42
Foo.bar = bar
Foo().bar()
``` | There is no solving needed, you just do it. Here is your code, with the small changes needed:
```
class RemoveNoise():
pass
RemoveNoise.raw = Raw
RemoveNoise.bias = Bias
def new(self):
pass
RemoveNoise.new=new
instance = RemoveNoise()
```
It's that simple. Python is wonderful.
Why on earth you would n... | 6,676 |
53,469,407 | I got into automating tasks on the web using python.
I have tried requests/urllib3/requests-html but they don't get me the right elements, because they get only the `html` (not the updated version with `javascript`).
Some recommended Selenium, but it opens a browser with the `webdriver`.
I need a way to get elements af... | 2018/11/25 | [
"https://Stackoverflow.com/questions/53469407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9534986/"
] | Don't overthink this.
It seems that everything you have in your object gets allocated there, so use smart pointers:
```
std::vector<std::unique_ptr<Object>> pointer_vector;
``` | Every object that you create with `new` will have to be `delete`ed at some point. It's your responsibility to do that. In your case the easiest solution is to add it in the destructor for your `Problem` class.
```
Problem::~Problem() {
for (auto ptr : pointer_vector)
delete ptr;
}
```
If you ever remove ... | 6,679 |
58,194,852 | I am trying to load a pkl file,
```
pkl_file = open(sys.argv[1], 'rb')
world = pickle.load(pkl_file)
```
but I get an error from these lines
```
Traceback (most recent call last):
File "E:/python/test.py", line 186, in <module>
world = pickle.load(pkl_file)
ModuleNotFoundError: No module named 'numpy.core.multiarra... | 2019/10/02 | [
"https://Stackoverflow.com/questions/58194852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7548018/"
] | I think there are two problems here.
First, your pickle is or contains a [NumPy](https://numpy.org/) object, which is not part of the standard library. Therefore you must ensure that NumPy is installed into your current Python environment and imported **before** you try to load the pickled object. Depending on your se... | Ok, I just had to figure this out for myself, and I solved it. All you have to do is change all the "\r\n" to "\n". You can do this in multiple ways. You can go into Notepad++ and change line endings from CR LF to just LF. Or programmatically you can do
```
open(newfile, 'w', newline = '\n').write(open(oldfile, 'r').r... | 6,680 |
31,575,359 | I recently downloaded some software that requires one to change to the directory with python files, and run `python setup.py install --user` in the Terminal.
One then checks whether the code is running correctly by trying `from [x] import [y]`
This works on my Terminal. However, when I then try `from [x] import [y]`... | 2015/07/22 | [
"https://Stackoverflow.com/questions/31575359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4596596/"
] | What about using the following selector:
`input[id^='something_stuff_'][id$='_work']`
It will get inputs with id starting with "something\_stuff\_" and finishing with "\_work". | An approach to this problem would be to use classes instead of ids and have things that are styled the same to be classed the same. for example:
```
<input id="something_stuff_01_work" class="input_class">
<input id="something_stuff_02_work" class="input_class">
<input id="something_stuff_03_work" class="input_class">... | 6,681 |
43,994,599 | Thanks to [Python Library](https://docs.python.org/2/library/telnetlib.html "Library") i was able to use their example to telnet to Cisco switches, I am using this for learning purposes, specifically learning python.
However, although all the code seem generally easy to read, I am a bit confused as to the following:
... | 2017/05/16 | [
"https://Stackoverflow.com/questions/43994599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736707/"
] | It looks like `PyCrypto` is [not being maintained currently](https://github.com/dlitz/pycrypto/issues/168). So, it's better you switch to [PyCryptodome](https://pypi.python.org/pypi/pycryptodome).
```
pip install pycryptodome
```
If you still want to use PyCrypto you could still try,
>
> <https://packaging.python.... | If doing `python -m Cryptodome.SelfTest` is giving you an error, you can do:
```
pip uninstall pycryptodome
```
and then:
```
easy_install pycryptodome
```
Even after this, running `python -m Cryptodome.SelfTest` was giving me an error, but when I re-ran the file, it worked. | 6,686 |
18,615,524 | I'm trying to get the valid python list from the response of a server like you can see below:
>
> window.\_\_search.list=[{"order":"1","base":"LAW","n":"148904","access":{"css":"avail\_yes","title":"\u042
> 2\u0435\u043a\u0441\u0442\u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0434\u043e\u0441\u0442\u0443\... | 2013/09/04 | [
"https://Stackoverflow.com/questions/18615524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1621838/"
] | Probably, your regular expression has found char ';' somewhere in the middle of a response, and because of this you get an error, because, using your regular expression, you might have received an incomplete, cropped response, and that's why you could not convert it into JSON.
Yes, I agree with user RickyA that someti... | What about:
```
response = response.strip() #get rid of whitespaces
response = response[response.find("["):] #trim everything before the first '['
if response[-1:] == ";": #if last char == ";"
response = response[:-1] #trim it
```
Seems like a big overkill to do this with regex. | 6,687 |
21,067,730 | I have this piece of code in my views.py for a django app:
```
for i in range(0,10):
row = cursor.fetchone()
tablestring = tablestring + "<tr><td>" + row[0] + "</td><td>" + + str(row[3]) + "</td></tr>"
```
This works fine when I load the page but if I change the range to (0,20) or anything higher, I just get... | 2014/01/11 | [
"https://Stackoverflow.com/questions/21067730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/754604/"
] | you should really use [django orm](https://docs.djangoproject.com/en/dev/topics/db/queries/) and write those table markups in a [template](https://docs.djangoproject.com/en/dev/topics/templates/), follow this [tutorial](https://docs.djangoproject.com/en/dev/intro/tutorial01/) to get the basic concepts | My first guess would be that there are less than 20 rows, so once you run out of them `row` will be None and your attempt to index it will throw an exception.
As for improving the code:
Like Yossi suggested, you should probably go with an ORM. An ORM (Object Relational Mapper) lets you access a database in a more obj... | 6,688 |
29,386,310 | I am downloading a compressed file from the internet:
```
with lzma.open(urllib.request.urlopen(url)) as file:
for line in file:
...
```
After having downloaded and processed a a large part of the file, I eventually get the error:
>
> File "/usr/lib/python3.4/lzma.py", line 225, in \_fill\_buffer raise... | 2015/04/01 | [
"https://Stackoverflow.com/questions/29386310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424589/"
] | from the [urllib.urlopen docs:](https://docs.python.org/2/library/urllib.html)
>
> One caveat: the read() method, if the size argument is omitted or
> negative, may not read until the end of the data stream; there is no
> good way to determine that the entire stream from a socket has been
> read in the general cas... | Assuming you need to download a big file, it is better to use the "write and binary" mode when writing content to a file in python.
You may also try to use the [python requests](http://docs.python-requests.org/en/master/) module more than the urllib module:
Please see below a working code:
```
import requests
url="h... | 6,689 |
21,310,125 | I would like to know what are the advantages and disadvantages of using AWS OpsWorks vs AWS Beanstalk and AWS CloudFormation?
I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that ca... | 2014/01/23 | [
"https://Stackoverflow.com/questions/21310125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1112656/"
] | **AWS Beanstalk:**
It is Deploy and manage applications in the AWS cloud without worrying about the infrastructure that runs yor web applications with Elastic Beanstalk.
No need to worry about EC2 or else installations.
**AWS OpsWorks**
AWS OpsWorks is nothing but an application management service that makes it easy f... | You should use OpsWorks in place of CloudFormation if you need to deploy an application that requires updates to its EC2 instances. If your application uses a lot of AWS resources and services, including EC2, use a combination of CloudFormation and OpsWorks
If your application will need other AWS resources, such as da... | 6,692 |
46,044,003 | I'm trying to write a function that guesses a type of a variable represented as a string.
So if I've got a variable of some type then in order to find out what type of a variable it is I can use python's `type()` function like this `type(var)`. But how do I concisely and pythonicaly convert the output of this function ... | 2017/09/04 | [
"https://Stackoverflow.com/questions/46044003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8243859/"
] | ```
>>> type(0).__name__
'int'
>>> type('').__name__
'str'
>>> type({}).__name__
'dict'
``` | What are you actually trying to do? If you just want to get the name of the class of the object you could use:
```
type(var).__name__
```
This will give you the name of the class of the object `var`. | 6,702 |
7,389,567 | I have a webpage generated from python that works as it should, using:
```
print 'Content-type: text/html\n\n'
print "" # blank line, end of headers
print '<link href="default.css" rel="stylesheet" type="text/css" />'
print "<html><head>"
```
I want to add images to this webpage, but... | 2011/09/12 | [
"https://Stackoverflow.com/questions/7389567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/828573/"
] | You can use this code to directly embed the image in your HTML:
Python 3
```
import base64
data_uri = base64.b64encode(open('Graph.png', 'rb').read()).decode('utf-8')
img_tag = '<img src="data:image/png;base64,{0}">'.format(data_uri)
print(img_tag)
```
Python 2.7
```
data_uri = open('11.png', 'rb').read().encode('b... | Images in web pages are typically a second request to the server. The HTML page itself has no images in it, simply references to images like `<img src='the_url_to_the_image'>`. Then the browser makes a second request to the server, and gets the image data.
The only option you have to serve images and HTML together is ... | 6,703 |
19,330,790 | I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window.
I'm trying to use :!python % but I get the following error message:
E499: Empty file name for '%' or '#', only works with ":p:h"
Any... | 2013/10/12 | [
"https://Stackoverflow.com/questions/19330790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use splits to have both vim and a bash prompt in the same terminal window.
I would highly recommend switching from the default `Terminal` app to [`iTerm2`](http://www.iterm2.com/). It's a terminal with [many nice features](http://www.iterm2.com/#/section/features), including 256 colours, tmux integration, and ... | You can execute command line arguments inside vim by starting the argument with a "!" from the command mode. Also, in command mode, "%" means the current file. Thus, you can execute the current file that you are editing like this:
```
:!python %
```
I should probably also add, as another option, that you can split t... | 6,706 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.