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 |
|---|---|---|---|---|---|---|
2,575,219 | Python language has a well known feature named [interactive mode](http://docs.python.org/tutorial/interpreter.html#interactive-mode) where the interpreter can read commands directly from tty.
I typically use this mode to test if a given module is in the classpath or to play around and test some snippets.
Do you kno... | 2010/04/04 | [
"https://Stackoverflow.com/questions/2575219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130929/"
] | [Perl](http://www.perl.org/) - interesting that there are so many answers before this | You can do almost-interactive C# and VB.NET using [LINQPad](http://www.linqpad.net/) | 4,927 |
59,023,371 | I am tryin to have a form submit to a python script using flask. the form is in my index.html -
```
<form action="{{ url_for('/predict') }}" method="POST">
<p>Enter Mileage</p>
<input type="text" name="mileage">
<p>Enter Year</p>
<input type="text" name="year">
<input type="submit" value="Predict"... | 2019/11/24 | [
"https://Stackoverflow.com/questions/59023371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671619/"
] | Instead of `url_for('/predict')`, drop the leading slash and use `url_for('predict')`.
`url_for(...)` takes the method name and not the route name. | I was not importing url\_for.
```
from flask import Flask, request, render_template, url_for
``` | 4,937 |
62,075,847 | I tried to create a polygon shapefile in QGIS and read it in python by shapely. An example code looks like this:
```
import fiona
from shapely.geometry import shape
multipolys = fiona.open(somepath)
multi = multipolys[0]
coord = shape(multi['geometry'])
```
The EOSGeom\_createLinearRing\_r returned a NULL pointer
I... | 2020/05/28 | [
"https://Stackoverflow.com/questions/62075847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13242482/"
] | I had a similar problem but with the shapely.geometry.LineString. The error I got was
```
ValueError: GEOSGeom_createLineString_r returned a NULL pointer
```
I don't know the reason behind this message, but there are two ways, how to avoid it:
1. Do the following:
```
...
from shapely import speedups
...
speedups... | Face the same issue and this work for me
`import shapely`
`shapely.speedups.disable()` | 4,938 |
62,479,608 | What's the difference? [docs](https://docs.python.org/3.7/library/types.html#types.FunctionType) show nothing on this, and their `help()` is identical. Is there an object for which `isinstance` will fail with one but not other? | 2020/06/19 | [
"https://Stackoverflow.com/questions/62479608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10133797/"
] | Back in 1994 I wasn't sure that we would always be using the same implementation type for lambda and def. That's all there is to it. It would be a pain to remove it, so we're just leaving it (it's only one line). If you want to add a note to the docs, feel free to submit a PR. | See [`cpython/Lib/types.py`](https://github.com/python/cpython/blob/a041e116db5f1e78222cbf2c22aae96457372680/Lib/types.py#L11-L13):
```
def _f(): pass
FunctionType = type(_f)
LambdaType = type(lambda: None) # Same as FunctionType
``` | 4,940 |
34,247,930 | I have installed python 3.5 on my Windows 7 machine. When I installed it, I marked the check box to install `pip`. After the installation, I wanted to check whether pip was working, so I typed `pip` on the command line and hit enter, but did not respond. The cursor blinks but it does not display anything.
Please help.... | 2015/12/13 | [
"https://Stackoverflow.com/questions/34247930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4542278/"
] | 1. go the windows cmd prompt
2. go to the python directory
3. then type python -m pip install package-name | I had the same problem with Version 3.5.2.
Have you tried `py.exe -m install package-name`? This worked for me. | 4,941 |
66,873,774 | I'm really new to python and pandas so would you please help me answer this seemingly simple question? I already have an excel file containing my data, now I want to create an array containing those data in python. For example, I have data in excel that look like this:
[ or a condition to check if `userIconData` is null before rendering image, and manually show a loading indica... | 4,951 |
54,392,016 | I have a python script were I was experimenting with minmax AI. And so tried to make a tic tac toe game.
I had a self calling function to calculate the values and it used a variable called alist(not the one below) which would be given to it by the function before. it would then save it as new list and modify it.
This... | 2019/01/27 | [
"https://Stackoverflow.com/questions/54392016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10976004/"
] | `newlist = alist` does not make a copy of the list. You just have two variable names for the same list.
There are several ways to actually copy a list. I usually do this:
```
newlist = alist[:]
```
On the other hand, that will make a new list with the same elements. To make a deep copy of the list:
```
import copy... | You probably want to `deepcopy` your list, as it contains other lists:
```
from copy import deepcopy
```
And then change:
```
newlist = alist
```
to:
```
newlist = deepcopy(alist)
``` | 4,952 |
70,163,997 | I have a folder of python scripts, I want to call each of them and pass in a DB object, this is easily doable, but I would like to do it dynamically, that is if I don't know the name of the script beforehand, is this possible?
Let's say all scripts are in the "scripts" subfolder.
My caller file:
```
#!/usr/bin/pytho... | 2021/11/30 | [
"https://Stackoverflow.com/questions/70163997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/468384/"
] | If we work backwards, you'll need your DataFrame to have the addenda information in a single row before using `.to_dict` operation:
| id\_number | name | amount | addenda |
| --- | --- | --- | --- |
| 1234 | ABCD | $100 | [{payment\_related\_info: Car-wash-$30, payment\_related\_info: Maintenance-$70}] |
To get here,... | Just apply a groupby and aggregate by creating a dataframe inside like this:
```py
data = {
"id_number": [1234, 1234],
"name": ["ABCD", "ABCD"],
"amount": ["$100", "$100"],
"addenda": ["Car-wash-$30", "Maintenance-$70"]
}
df = pd.DataFrame(data=data)
df.groupby(by=["id_number", "name", "amount"]) \
... | 4,953 |
25,598,838 | I'm really new to python so this is probably a really stupid problem but I honestly have no idea what I'm doing and I have spent hours trying to get this to work.
I need to have the user input a date (in string form) and then use this date to return some data (The function get\_data\_for\_date has already previously b... | 2014/09/01 | [
"https://Stackoverflow.com/questions/25598838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3995938/"
] | Try this sequence :
```
MYApplication.getInstance().clearApplicationData();
android.os.Process.killProcess(android.os.Process.myPid());
Intent intent1 = new Intent(Intent.ACTION_MAIN);
intent1.addCategory(Intent.CATEGORY_HOME);
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(int... | Avoid `killProcess`
Try this code :
```
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(startMain);
System.exit(-1);
``` | 4,954 |
63,570,453 | I plan on uninstalling and reinstalling Python to fix pip. I, however, have a lot of python files which I worked hard on and I really don't want to lose them. Would my Python files be okay if I uninstalled Python? | 2020/08/25 | [
"https://Stackoverflow.com/questions/63570453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13931651/"
] | If you are using Linux and a distribution like Ubuntu, you will definitely break the OS. Don't do it.
Moreover, there is no evidence that your installation is broken because of Python, and you may probably not solve your problem. | There's no harm I can see in overwriting a pip installation. So, just follow the [instructions](https://pip.pypa.io/en/stable/installing/) and let us know if you have further problems:
1. Download [get-pip.py](https://bootstrap.pypa.io/get-pip.py).
2. Run python get-pip.py and get on with the rest of your stuff. | 4,956 |
14,068,042 | Resently I'm installed Opencv in my machine. Its working in python well(I just checked it by some eg programs). But due to the lack of tutorials in python I decided to move to c. I just run an Hello world program from <http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/>
My program is
```
#include <stdlib.h>
#... | 2012/12/28 | [
"https://Stackoverflow.com/questions/14068042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1894272/"
] | First check if highgui.h exists on your machine:
```
sudo find /usr/include -name "highgui.h"
```
If you find it on path lets say "/usr/include/opencv/highgui.h"
then use:
```
#include <opencv/highgui.h> in your c file.
```
or
while compiling you could add
```
-I/usr/include/opencv in gcc line
```
but then... | I have the following headers in my project:
```
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/features2d/features2d.hpp>
```
The version of OpenCV 2.4.2 | 4,964 |
64,983,755 | As of until now, my understanding is that python imports module by the path relative to the directory, despite the source file being anywhere else.
for example:
```
bar
|-foo.py
|-foo1.py
```
so if we want to access `fo01.py` through
`foo.py` from `bar`, I would think I need to do
`from bar import foo1`. But the ... | 2020/11/24 | [
"https://Stackoverflow.com/questions/64983755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9817556/"
] | before explaining why and how to make things work.
let me put some right code.
here is the dir tree(which followed yours)
```
.
├── bar
│ ├── foo1.py
│ └── foo.py
└── examples
└── getfoo.py
```
and there is a variable named `var` in foo1.py and foo.py
Question I:
>
> so if we want to access fo01.py throu... | Try importing foo1.py in getfoo1.py using its path.
```
import ../bar/foo1.py
```
Or
copy paste foo1.py in examples and then call
```
import foo1.py
```
Please check syntax for "import ../bar/foo1.py" | 4,965 |
67,045,619 | I have a python script and I used on Kubernetes.
After process ended on python script Kubernetes restart pod. And I don't want to this.
I tried to add a line of code from python script like that:
```
text = input("please a key for exiting")
```
And I get EOF error, so its depends on container has no EOF config on m... | 2021/04/11 | [
"https://Stackoverflow.com/questions/67045619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13338897/"
] | You get `unknown field \"restartPolicy\" in io.k8s.api.core.v1.PodTemplateSpec;` because you most probably messed up some indentation.
Here is an example deploymeny with **incorrect indentation** of `restartPolicy` field:
```
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: n... | A PodSpec has a restartPolicy field with possible values Always, OnFailure, and Never. The default value is Always.
could you please try OnFailure you have only one container it should work. | 4,966 |
67,025,052 | As I am teaching myself Bash programming, I came across an interesting use case, where **I want to take a list of variables that exist in the environment, and put them into an array. Then, I want to output a list of the variable names and their values, and store that output in an array, one entry per variable.**
I'm o... | 2021/04/09 | [
"https://Stackoverflow.com/questions/67025052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12854372/"
] | OP starts with:
```
VAR_ONE="LIGHT RED"
VAR_TWO="DARK GREEN"
VAR_THREE="BLUE"
VARIABLE_ARRAY=(VAR_ONE VAR_TWO VAR_THREE)
```
OP has provided an answer with 4 sets of code:
```
# first 3 sets of code generate:
$ typeset -p outputValues
declare -a outputValues=([0]="VAR_ONE: LIGHT RED" [1]="VAR_TWO: DARK GREEN" [2]=... | I've come up with a handful of possible solutions in the last couple days, each one with their own pro's and con's. I won't mark this as the answer for awhile though, since I'm interested in hearing unbiased recommendations.
---
My brainstorming solutions thus far:
OPTION #1 - FOR-LOOP:
```
alias PrintCommandValues... | 4,968 |
1,894,099 | I am trying to run the script [csv2json.py](http://www.djangosnippets.org/snippets/1680/) in the Command Prompt, but I get this error:
```
C:\Users\A\Documents\PROJECTS\Django\sw2>csv2json.py csvtest1.csv wkw1.Lawyer
Converting C:\Users\A\Documents\PROJECTS\Django\sw2csvtest1.csv from CSV to JSON as C:\Users\A\Docume... | 2009/12/12 | [
"https://Stackoverflow.com/questions/1894099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215094/"
] | ```
from os import path
in_file = path.join(dirname(__file__), input_file_name )
out_file = path.join(dirname(__file__), input_file_name + ".json" )
[...]
``` | You should be using `os.path.join` rather than just concatenating `dirname()` and filenames.
```
import os.path
in_file = os.path.join(dirname(__file__), input_file_name)
out_file = os.path.join(dirname(__file__), input_file_name + ".json")
```
will fix your problem, though depending on what exactly you're doing, th... | 4,969 |
33,545,813 | I am creating a Python class but it seems I can't get the constructor class to work properly. Here is my class:
```
class IQM_Prep(SBconcat):
def __init__(self,project_dir):
self.project_dir=project_dir #path to parent project dir
self.models_path=self.__get_models_path__() #path to parent models ... | 2015/11/05 | [
"https://Stackoverflow.com/questions/33545813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3059024/"
] | Based on the traceback, it seems that either:
```
def __get_models_path__(self):
for i in os.listdir(self.project_dir): # 1. this never loops; or
if i=='models': # 2. this never evaluates True
models_path=os.path.join(self.project_dir,i) # hence this never happens
return models_path # a... | `models_path` is initialized only when:
* `self.project_dir` has some files/dirs and
* one of this file/dir has name `models`
If one of this condition is not fullfiled, then `models_path` is not initialized. | 4,972 |
21,319,261 | I am trying to execute some code on a Beaglebone Black running ubuntu. The script has two primary functions:
1: count digital pulse
2: store the counted pulses in mySQL every 10s or so
These two functions need to run idefinitely.
My question is how to do get these two functions to run in parallel? Here is my latest c... | 2014/01/23 | [
"https://Stackoverflow.com/questions/21319261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2133624/"
] | This is a perfect problem for a `Queue`!
```
#!/usr/bin/python
import Adafruit_BBIO.GPIO as GPIO
import MySQLdb
import time
import thread
import Queue
from threading import Thread
now = time.strftime('%Y-%m-%d %H:%M:%S')
total1 = 0
total2 = 0
pulse_objects = Queue.Queue()
def insertDB_10sec(pulse_objects):
whi... | Why do you need two threads? Move the insert to `countPulse`. That being said:
You should not call `insertDB_10sec` here:
```
t2 = Thread(target = insertDB_10sec(now, total1, total2))
```
Provide the arguments as actual arguments:
```
t2 = Thread(target = insertDB_10sec, args=(now, total1, total2))
```
This will... | 4,973 |
3,023,136 | Is it somehow possible to extract .cab files in python? | 2010/06/11 | [
"https://Stackoverflow.com/questions/3023136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/341963/"
] | Not strictly answering what you asked, but if you are running on a windows platform you could spawn a process to do it for you.
Taken from Wikipedia:
>
> Microsoft Windows provides two
> command-line tools for creation and
> extraction of CAB files. They are
> MAKECAB.EXE (included within Windows
> packages suc... | Oddly, the [msilib](http://docs.python.org/library/msilib.html) can only create or append to .CAB files, but not extract them. :(
However, the [hachoir](https://hachoir.readthedocs.io/en/latest/parser.html) parser module can apparently read & edit Cabinets. (I have not used it, though, so I couldn't tell you how fitti... | 4,974 |
66,283,314 | I am writing a script to automate data collection and was having trouble clicking a link. The website is behind a login, but I navigated that successfully. I ran into problems when trying to navigate to the download page. This is in python using chrome webdriver.
I have tried using:
```
find_element_by_partial_link_t... | 2021/02/19 | [
"https://Stackoverflow.com/questions/66283314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14024634/"
] | This is caused by a typo. `Download` is case-sensitive, make sure you capitalize the `D`! | To click on the element with text as **Download** you can use either of the following [Locator Strategies](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):
* Using `css_selector`:
```
driver.find_element(By.CSS_SELECTOR, "a[title='Download'][href='/itron-m... | 4,976 |
27,572,688 | I have written the following code using Python 2.7 to search the list 'dem\_nums' for the first three characters from each element in the list 'dems', and if they are not present to append them. When I run the code the list 'dem\_nums' is returned as empty. I've tried using this article to help ([check if a number alre... | 2014/12/19 | [
"https://Stackoverflow.com/questions/27572688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4289336/"
] | I am not sure I understand your requirement. Why write such a complicated stylesheet when the end result should simply be a total amount of numbers? Also, it seems you are already familiar with the relevant EXSLT functions and with converting strings into numbers.
**Stylesheet**
```
<?xml version="1.0" encoding="UTF-... | While I tend to go with the suggestion made by Mathias Müller, I wanted to show how you can do this using a recursive named template:
**XSLT 1.0**
```
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" version="1.0" encoding="utf-8" ind... | 4,977 |
2,051,526 | As we all know (or should), you can use Django's template system to render email bodies:
```
def email(email, subject, template, context):
from django.core.mail import send_mail
from django.template import loader, Context
send_mail(subject, loader.get_template(template).render(Context(context)), 'from@dom... | 2010/01/12 | [
"https://Stackoverflow.com/questions/2051526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
] | This is my third working iteration. It assuming you have an email template like so:
```
{% block subject %}{% endblock %}
{% block plain %}{% endblock %}
{% block html %}{% endblock %}
```
I've refactored to iterate the email sending over a list by default and there are utility methods for sending to a single email ... | Just use two templates: one for the body and one for the subject. | 4,978 |
62,191,724 | Trying to make use of this package: <https://github.com/microsoft/Simplify-Docx>
Can someone pls tell me the proper sequence of actions needed to install and use the package?
What I've tried (as a separate commands from vscode terminal):
```
pip install python-docx
Git clone <git link>
python setup.py install
```
... | 2020/06/04 | [
"https://Stackoverflow.com/questions/62191724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9130563/"
] | The problem is that your system doesn't have "docx" module.
to install docx module you will have to install docx.
steps to install:
1) open CMD prompt.
2) type "pip install docx"
if your installation is fresh it may need "simplify" module too. | Like any python package that doesn't come with python, you need to install it before using it. In your terminal window you can install if from the Python package index like this:
```bash
pip install simplify-docx
```
or you can install it directly from GitHub like this:
```bash
pip install git+git://github.com/micr... | 4,980 |
19,085,887 | I searched and tried following stuff but could not found any solution, please let me know if this is possible:
I am trying to develop a python module as wrapper where I call another 3rd party module with its .main() and provide the required parameter which I need to get from command line in my module. I need few param... | 2013/09/30 | [
"https://Stackoverflow.com/questions/19085887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/948673/"
] | Does this scenario fit?
Module B:
```
import argparse
parser = argparse....
def main(args):
....
if __name__ == '__main__':
args = parser.parse_args()
main(args)
```
Module A
```
import argparse
import B
parser = argparse....
# define arguments that A needs to use
if _name__=='__main__':
args,rest... | Provided that you are calling third-party modules, a possible solution is to
change **sys.argv** and **sys.argc** at runtime to reflect the correct parameters for
the module you're calling, once you're done with your own parameters. | 4,982 |
51,876,794 | I have a text file named `file.txt` with some numbers like the following :
```
1 79 8.106E-08 2.052E-08 3.837E-08
1 80 -4.766E-09 9.003E-08 4.812E-07
1 90 4.914E-08 1.563E-07 5.193E-07
2 2 9.254E-07 5.166E-06 9.723E-06
2 3 1.366E-06 -5.184E-06 7.580E-06
2 4 2.966E-06 5.979E-07 9.702E-08
2 5 5.254E... | 2018/08/16 | [
"https://Stackoverflow.com/questions/51876794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8869818/"
] | You can use a `defaultdict`.
```
from collections import defaultdict
data = defaultdict(list)
with open("file.txt", "r") as f:
for line in f:
line = line.split()
data[line[0]].extend(line[2:])
``` | Try this:
```
from collections import defaultdict
diction = defaultdict(list)
with open("file.txt") as f:
for line in f:
key, _, *values = line.strip().split()
diction[key].extend(values)
print(diction)
```
This is a solution for Python 3, because the statement `a, *b = tuple1` is invalid in P... | 4,984 |
59,745,214 | I have 2 files to copy from a folder to another folder and these are my codes:
```
import shutil
src = '/Users/cadellteng/Desktop/Program Booklet/'
dst = '/Users/cadellteng/Desktop/Python/'
file = ['AI+Product+Manager+Nanodegree+Program+Syllabus.pdf','Artificial+Intelligence+with+Python+Nanodegree+Syllabus+9-5.pdf']
... | 2020/01/15 | [
"https://Stackoverflow.com/questions/59745214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3910616/"
] | Just use the below code since `i` doesn't need an extra indexing `file[...]`, because it is not an index:
```
for i in file:
shutil.copyfile(src + i, dst + i)
```
If you want to use `range`, use it this way with `len`:
```
for i in range(len(file)):
shutil.copyfile(src+file[i], dst+file[i])
```
But of cou... | Try the code below, and read [for Statement in python](https://docs.python.org/3/tutorial/controlflow.html#for-statements)
```
import shutil
src = '/Users/cadellteng/Desktop/Program Booklet/'
dst = '/Users/cadellteng/Desktop/Python/'
file = ['AI+Product+Manager+Nanodegree+Program+Syllabus.pdf','Artificial+Intelligenc... | 4,989 |
64,578,491 | The other version of this question wasn't ever answered, the original poster didn't give a full example of their code...
I have a function that's meant to import a spreadsheet for formatting purposes. Now, the spreadsheet can come in two forms:
1. As a filename string (excel, .csv, etc) to be imported as a DataFrame
... | 2020/10/28 | [
"https://Stackoverflow.com/questions/64578491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954167/"
] | So, one way is to just compare with a string and reading the dataframe in the else condition.
The other way would be to use `isinstance`
```py
In [21]: dict1
Out[21]: {'a': [1, 2, 3, 4], 'b': [2, 4, 6, 7], 'c': [2, 3, 4, 5]}
In [24]: df = pd.DataFrame(dict1)
In [28]: isinstance(df, pd.DataFrame)
Out[28]: True
In [3... | This line is the problem:
```
if type(spreadsheet) == pd.DataFrame:
```
The type of a dataframe is `pandas.core.frame.DataFrame`. [pandas.DataFrame is a class](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) which returns a dataframe when you call it.
Either of these would work:
... | 4,990 |
16,710,374 | I am implementing a huge directed graph consisting of 100,000+ nodes. I am just beginning python so I only know of these two search algorithms. Which one would be more efficient if I wanted to find the shortest distance between any two nodes? Are there any other methods I'm not aware of that would be even better?
Than... | 2013/05/23 | [
"https://Stackoverflow.com/questions/16710374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2155605/"
] | There are indeed several other alternatives to BFS and DFS.
One that is quite adequate to computing shortest path is: <http://en.wikipedia.org/wiki/Dijkstra>'s\_algorithm
Dijsktra's Algorithm is basically an adaptation of a BFS algorithm, and it's much more efficient than searching the entire graph, if your graph is ... | Take a look at the following two algorithms:
1. [Dijkstra's algorithm](http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm) - Single source shortest path
2. [Floyd-Warshall algorithm](http://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm) - All pairs shortest path | 4,991 |
44,408,625 | I am writing a python wrapper for calling programs of the AMOS package (specifically for merging genome assemblies from different sources using good ol' minimus2 from AMOS).
The scripts should be called like this when using the shell directly:
```
toAmos -s myinput.fasta -o testoutput.afg
minimus2 testoutput -D REFCO... | 2017/06/07 | [
"https://Stackoverflow.com/questions/44408625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4685799/"
] | ### answer
Either do:
```
call("toAmos -s " + inputfile +" -o " + output_basename + ".afg") # single string
```
or do:
```
call(["toAmos", "-s", inputfile, "-o", output_basename + ".afg"]) # list of arguments
```
### discussion
In the case of your:
```
call(["toAmos", "-s " + inputfile, "-o " + output_basename... | `-s` and following input file name should be separate arguments to `call`, as they are in the command line:
```
call(["toAmos", "-s", inputfile, "-o", output_basename + ".afg"])
``` | 4,996 |
46,460,218 | im new in python and world of programming. get to the point. when i run this code and put input let say chicken, it will reply as two leg animal. but i cant get reply for two words things that has space in between like space monkey(althought it appear in my dictionary) so how do i solve it???
my dictionary: example.py... | 2017/09/28 | [
"https://Stackoverflow.com/questions/46460218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8681243/"
] | Try this in your code .
```
@Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
@Override
protected void onPostExecute(String s) {
// edited here
try {
JSONObject jsonObje... | You need to Debug this issue why your toast is not showing:
You have correctly put show Toast code in onPostExecute
Now to debug , first put a Log to know the value of s , whether it is ever null or empty.
If yes and still toast is not showing, move the dialog dismiss dialog before Toast and check.
If Toast still d... | 4,997 |
50,388,396 | I try to compile this code but I get this errror :
```
NameError: name 'dtype' is not defined
```
Here is the python code :
```
# -*- coding: utf-8 -*-
from __future__ import division
import pandas as pd
import numpy as np
import re
import missingno as msno
from functools import partial
import seaborn as sns
sns.... | 2018/05/17 | [
"https://Stackoverflow.com/questions/50388396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9360453/"
] | As written by Amr Keleg,
>
> If `data` is a pandas dataframe then you can check the type of a
> column as follows:
> `df['colname'].dtype` or `df.colname.dtype`
>
>
>
In that case you need e.g.
```
df['colname'].dtype == np.dtype('datetime64')
```
or
```
df.colname.dtype == np.dtype('datetime64')
``` | You should use `type` instead of `dtype`.
`type` is a built-in function of python -
<https://docs.python.org/3/library/functions.html#type>
On the other hand, If `data` is a pandas dataframe then you can check the type of a column as follows:
`df['colname'].dtype` or `df.colname.dtype` | 4,998 |
52,607,623 | I have 3 variables in python (age, gender, race) and I want to create a unique categorical binary code out of them. Firstly, the age is an integer and I want to threshold it for each decade 10-20, 20-30, 30-40 etc., gender 2 values and the race contains 4 values. How can I return a complete categorical code out of the ... | 2018/10/02 | [
"https://Stackoverflow.com/questions/52607623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1194864/"
] | Here is a method returning a 7 bit code with first 4 bits for age bracket, next 2 for race, and 1 for gender.
4 bits for age imposes the constraint that there can be a total of 16 age brackets only, which is reasonable as it covers the age range 0-159.
The 4 bit age code is simply the 4 bit representation of the inte... | You can have a `n+1+4` dimensional vector encoding. Given binary code you require, this would be one way of doing it.
You first `n` entries would encode decade. `1` if it belongs to that decade, `0` else. Next `(n+1)th` entry could be `1` if male and `0` if female. Similarly for race, `1` if it belongs to that categor... | 5,001 |
30,296,531 | So here is my first test for S3 buckets using boto:
```
import boto
user_name, access_key, secret_key = "testing-user", "xxxxxxxxxxxxx", "xxxxxxxx/xxxxxxxxxxxx/xxxxxxxxxx(xxxxx)"
conn = boto.connect_s3(access_key, secret_key)
buckets = conn.get_all_buckets()
```
I get the following error:
```
Traceback (most recen... | 2015/05/18 | [
"https://Stackoverflow.com/questions/30296531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221660/"
] | Had the same issue. In my case, my generated security key had a special character '+' in between. So I deleted my key and regenerated a new key and it worked with the new key with no '+'.
[Source](https://stackoverflow.com/a/12262106) | Today, I saw an error response with `SignatureDoesNotMatch` while playing around an S3 API locally and replacing **localhost** with **127.0.0.1** fixed the problem in my case. | 5,003 |
43,837,305 | I have a GitHub repository containing a AWS Lambda function. I am currently using Travis CI to build, test and then deploy this function to Lambda if all the tests succeed using
```
deploy:
provider: lambda
(other settings here)
```
My function has the following dependencies specified in its `requirements.tx... | 2017/05/07 | [
"https://Stackoverflow.com/questions/43837305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3474089/"
] | After quite a bit of tinkering I think I've found something that works. I thought I'd post it here in case others have the same problem.
I decided to use [Wercker](http://www.wercker.com/) as they have quite a generous free tier and allow you to customize the docker image for your builds.
Turns out there is a docker ... | Although I appreciate you may not want to add further complications to your project, you could potentially use a Python-focused Lambda management tool for setting up your builds and deployments, say something like [Gordon](https://github.com/jorgebastida/gordon). You could also just use this tool to do your deployment ... | 5,004 |
53,268,375 | I have a use case which often requires to copy a blob (file) from one Azure region to another. The file size spans from 25 to 45GB. Needless to say, this sometimes goes very slowly, with inconsistent performance. This might take up to two hours, sometimes more. Distance plays a role, but it differs. Even within the sam... | 2018/11/12 | [
"https://Stackoverflow.com/questions/53268375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/794967/"
] | Data model is wrong. Should be something like this:
```
SQL> create table customer
2 (customer_id number primary key,
3 first_name varchar2(20),
4 last_name varchar2(20),
5 phone varchar2(20));
Table created.
SQL> create table items
2 (item_id number primary key,
3 item... | There is no relation between the two tables which you wish to combine data from. Kindly create a foreign key relation between the two tables which would help you get a common value based on which you could extract data.
For e.g. - The column Customer\_id from customers table could be the foreign key in table orders wh... | 5,005 |
55,574,215 | I'm logging some Unicode characters to a file using "logging" in Python 3. The code works in the terminal, but fails with a UnicodeEncodeError in PyCharm.
I load my logging configuration using `logging.config.fileConfig`. In the configuration, I specify a file handler with `encoding = utf-8`. Logging to console works ... | 2019/04/08 | [
"https://Stackoverflow.com/questions/55574215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1654411/"
] | on different os need different solutions:
on Windows:
1. download the libfile, <http://www.rarlab.com/rar/UnRARDLL.exe>, install it;
2. you'd better choose the default path, C:\Program Files (x86)\UnrarDLL\
3. the most important is add the environment path, the varname enter UNRAR\_LIB\_PATH, pay attention, it must be... | Additionally, after you do the things as mentioned by Tom.chen.kang and balandongiv, if you're using a 32bit DLL with 64bit Python, or vice-versa, then you'll probably get an error like this when you try to import unrar:-
>
> OSError: [WinError 193] %1 is not a valid Win32 application
>
>
>
In that case do this:
... | 5,008 |
58,799,259 | I am using Windows 10, PostgreSQL 12, Python 3.7.5 . I create username `odoo`, password `odoo`, create database `mydb`.
Source code is <https://github.com/odoo/odoo/tree/aa0554d224337e1d966479a351a3ed059d297765>
I run command
```
python odoo-bin -r odoo -w odoo --addons-path=addons --db-filter=mydb$
```
Error
```... | 2019/11/11 | [
"https://Stackoverflow.com/questions/58799259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3728901/"
] | I think you need to configure the DB to trust your IP address:
make the following chages in `pg_hba.conf`:
```
# IPv4 local connections:
host all all 127.0.0.1/32 trust
host all all MY_IP/24 trust
```
see also [this](https://www.odoo.com/documentation/13.0/setup/install.html#id3) | odoo 13 a default user name odoo that user with postgress it use a recently db created.
you can pass a database configuration on your config file
odoo 13 /debian/odoo.conf
```
[options]
; This is the password that allows database operations:
; admin_passwd = admin
db_host = False
db_port = False
db_user = odoo
db_p... | 5,010 |
54,525,141 | I have a python environment (it could be conda, virtualenv, venv or global python) - I have a python script - hello.py - that I want to execute within that environment.
If I get the path to the python binary within the environment, for example, in windows with a conda environment called myenv, `/path/to/myenv/Scripts... | 2019/02/04 | [
"https://Stackoverflow.com/questions/54525141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456735/"
] | Yes, you're right! Furthermore you can evaluate the used executable by using the following snippet:
```
import sys
print(sys.executable)
```
Then you will see the absolute path, e.g. `/opt/miniconda/envs/epm/bin/python`.
If you're using a Unix system, you can run:
```
$ echo "import sys; print(sys.version); print... | I suspect not. There are a few environment variables (e.g. `PATH`) which are changed when you activate a virtualenv. You can open up `myenv/bin/activate` in a text editor to see what it does.
Is there a particular reason you want to call the executable directly, rather than use the environment as designed? (e.g. `. ./... | 5,012 |
36,911,060 | I have a JSON file containing various objects each containing elements. With my python script, I only keep the objects I want, and then put the elements I want in a list. But the element has a prefix, which I'd like to suppress form the list.
The post-script JSON looks like that:
```
{
"ip_prefix": "184.72.128... | 2016/04/28 | [
"https://Stackoverflow.com/questions/36911060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5532788/"
] | You can also add this variable by using a preprocess hook. The following code will add the `is_front` variable so it can be used in the `html.html.twig` template:
```
// Adds the is_front variable to html.html.twig template.
function mytheme_preprocess_html(&$variables) {
$variables['is_front'] = \Drupal::service('p... | If you want to show a node within the front page and it should look just like the actual node page, you can create a new display for the node, like "On Frontpage". For that display you create a new node template (be careful to use the right naming convention for the twig file, otherwise it won't work). Then you tell th... | 5,013 |
31,573,399 | I have a largish pandas dataframe (1.5gig .csv on disk). I can load it into memory and query it. I want to create a new column that is combined value of two other columns, and I tried this:
```
def combined(row):
row['combined'] = row['col1'].join(str(row['col2']))
return row
df = df.apply(combined, axis=1)
```
... | 2015/07/22 | [
"https://Stackoverflow.com/questions/31573399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3137396/"
] | I would try using list comprehension + [`itertools`](https://docs.python.org/2/library/itertools.html):
```
df = pd.DataFrame({
'a': ['ab'] * 200,
'b': ['ffff'] * 200
})
import itertools
[a.join(b) for (a, b) in itertools.izip(df.a, df.b)]
```
It might be "unpandas", but pandas doesn't seem to have a `.str... | One nice way to create a new column in [`pandas`](http://pandas.pydata.org) or [`dask.dataframe`](http://dask.pydata.org/en/latest/dataframe.html) is with the [`.assign`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html) method.
```
In [1]: import pandas as pd
In [2]: df = pd.DataFra... | 5,014 |
48,125,575 | I am trying to read the following code for back propagation in python
```
probs = exp_scores /np.sum(exp_scores, axis=1, keepdims=True)
#Backpropagation
delta3 = probs
delta3[range(num_examples), y] -= 1
dW2 = (a1.T).dot(delta3)
....
```
but I cannot understand the following line of the code:
```
delta3[range(num... | 2018/01/06 | [
"https://Stackoverflow.com/questions/48125575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7962244/"
] | There are two things here. First it is using numpy slicing to select only a fraction of `delta3`. Secondly it is removing 1 to every element of this fraction of the matrix.
More precisely, `delta3[range(num_example), y]` is selecting lines of the matrix `delta3` ranging from 0 to `num_examples` but only selecting colu... | If you're interested, *why* it's computed this way, it's the backpropagation through cross-entropy loss:
* `probs` is the vector of class probabilities (computed in a forward pass via softmax).
* `delta3` is the error signal from the loss function.
* `y` holds the ground truth classes for the mini-batch.
Everything e... | 5,015 |
49,958,177 | I am a beginner to python and am working on python 3.6.5 , I was trying to create a Chatbot but I don't understand how to use a comma to separate the two strings(red and Red) because the shell says that it is an invalid syntax(the comma is highlighted but nothing else). What have I done wrong?:
```
colour=input("What ... | 2018/04/21 | [
"https://Stackoverflow.com/questions/49958177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9679321/"
] | Use `in`
```
colour= input("What is your favourite colour? ")
if colour in ("red", "Red"):
print("Red is my favourite colour as well")
``` | You could you use if colour in ['red', 'Red', 'RED', 'ReD'] as mentionned earlier, or you could just sanitize the input:
```
colour= input("What is your favourite colour? ")
if colour.lower() == "red":
print("Red is my favourite colour as well")
``` | 5,016 |
20,322,969 | I am not sure if there is a solution for this on stack overflow; so apologies if this is a duplicate.
There are number of ways of converting the string:
```
s = '[1, 2, 3]'
```
to a list
```
t = [1, 2, 3]
```
but I am looking for the most straightforward pythonic way of doing this. Also, performance matters. | 2013/12/02 | [
"https://Stackoverflow.com/questions/20322969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778980/"
] | One should use [ast.literal\_eval](http://docs.python.org/2/library/ast.html#ast.literal_eval):
```
>>> import ast
>>> ast.literal_eval('[1,2,3]')
[1, 2, 3]
``` | Why never use json library.
```
import json
# convert str to list
t = json.loads(s)
# back to string
s2 = json.dumps(t)
``` | 5,017 |
49,949,398 | I am facing an issue while importing java code which uses some external jar say selenium\_standalone\_server jar.
I tried with normal code with no jars used in java, in this case i am able to import and run the code, but when i uses some jars in java code and then try to import that class to jython it gives error.
He... | 2018/04/20 | [
"https://Stackoverflow.com/questions/49949398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3814582/"
] | **1)** We group by Name (assuming `rollapply` should be done separately for each `Name`) and then use `width = list(-seq(4))` with `rollapply` which uses offsets -1, -2, -3, -4 for each application of `mean`. (Offset 0 would be the current point but we want the 4 prior here.)
Not clear what you are referring to regard... | An option is to use `zoo::rollapply` along with `dplyr::lag` as:
```
library(dplyr)
library(lubridate)
library(zoo)
df %>% mutate(DATE = mdy(DATE)) %>% #Convert to Date
arrange(Name, DATE) %>% #Order on Name and DATE
mutate(Avg = rollapply(Values, 4, mean, fill= NA, align = "right")) %>%
mutate(Av... | 5,018 |
53,846,322 | I am exporting LOG\_INTERVAL value as 5. How can I add this env value in python as `time.sleep`?
```
import os
import time
print("Goodbye, World!")
time.sleep(os.environ.get('LOG_INTERVAL'))
```
```
error:- Goodbye, World!
Traceback (most recent call last):
File "test.py", line 4, in
time.sleep(os.environ.get... | 2018/12/19 | [
"https://Stackoverflow.com/questions/53846322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10809642/"
] | The value you get from the environment is a string. You have to convert it to a number in order for it to be an acceptable value for `time.sleep()`
```
time.sleep(float(os.environ.get('LOG_INTERVAL'))
``` | I think `LOG_INTERVAL` will be returned as a string.
Check it's type with `type(os.environ.get('LOG_INTERVAL'))`
If it is an int or a string containing nothing but numbers or fullstops `time.sleep(float(os.environ.get('LOG_INTERVAL')))` should convert it to a float and do the trick. | 5,019 |
5,559,810 | **Question**
It seems that PyWin32 is comfortable with giving null-terminated unicode strings as return values. I would like to deal with these strings the 'right' way.
Let's say I'm getting a string like: `u'C:\\Users\\Guest\\MyFile.asy\x00\x00sy'`. This appears to be a C-style null-terminated string hanging out in ... | 2011/04/05 | [
"https://Stackoverflow.com/questions/5559810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/182642/"
] | I'd say it's a bug. The right way to deal with it would probably be fixing pywin32, but in case you aren't feeling adventurous enough, just trim it.
You can get everything before the first `'\x00'` with `filename.split('\x00', 1)[0]`. | This doesn't happen on the version of PyWin32/Windows/Python I tested; I don't get any nulls in the returned string even if it's very short. You might investigate if a newer version of one of the above fixes the bug. | 5,022 |
49,737,459 | Forgive me the possibly trivial question, but: *How do I run the script published by pybuilder?*
---
I'm trying to follow the official [Pybuilder Tutorial](http://pybuilder.github.io/documentation/tutorial.html#.WsqupUuYNhE).
I've walked through the steps and successfully generated a project that
* runs unit tests... | 2018/04/09 | [
"https://Stackoverflow.com/questions/49737459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2707792/"
] | Apparently the following workflow:
* pyb publish
* pip install .tar.gz
* runMyScript.py
* uninstall
is exactly what is proposed by the creator of PyBuilder [in this talk](http://www.youtube.com/watch?v=iQU18hAjux4&t=14m42s).
**Note that the linked video is from 2014. If someone can propose a more streamlined recentl... | Create task in build.py
```
@task
def run(project):
path.append("src/main/python")
from test_pack import test_app
test_app.main()
```
Try:
`pyb run` | 5,025 |
16,650,680 | The following was ported from the pseudo-code from the Wikipedia article on [Newton's method](http://en.wikipedia.org/wiki/Newton%27s_method):
```
#! /usr/bin/env python3
# https://en.wikipedia.org/wiki/Newton's_method
import sys
x0 = 1
f = lambda x: x ** 2 - 2
fprime = lambda x: 2 * x
tolerance = 1e-10
epsilon = sys... | 2013/05/20 | [
"https://Stackoverflow.com/questions/16650680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216356/"
] | A common way of approximating the derivative of `f` at `x` is using a finite difference:
```
f'(x) = (f(x+h) - f(x))/h Forward difference
f'(x) = (f(x+h) - f(x-h))/2h Symmetric
```
The best choice of `h` depends on `x` and `f`: mathematically the difference approaches the derivative ... | You can approximate `fprime` any number of ways. One of the simplest would be something like:
```
lambda fprime x,dx=0.1: (f(x+dx) - f(x-dx))/(2*dx)
```
the idea here is to sample `f` around the point `x`. The sampling region (determined by `dx`) should be small enough that the variation in `f` over that region is a... | 5,026 |
21,397,757 | Personally I think it's better to distribute .py files as these will then be compiled by the end-user's own python, which may be more patched.
What are the pros and cons of distributing .pyc files versus .py files for a commercial, closed-source python module?
In other words, are there any compelling reasons to distr... | 2014/01/28 | [
"https://Stackoverflow.com/questions/21397757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/906984/"
] | Close the unused file descriptors it will work fine
In the inner most child
```
close(f1[1]);
```
In the parent process
```
close(f1[0]);
```
And also syntax error in the line write is called change it to
```
write(f1[1], M1, sizeof(M1)) < 0)
``` | change your `if` statement to
```
if (write(f1[1], M1, sizeof(M1)) < 0)
```
instead of
```
if(write(f1[1], M1, sizeof(M1) < 0))
``` | 5,028 |
2,177,250 | I have a folder with 100k text files. I want to put files with over 20 lines in another folder. How do I do this in python? I used os.listdir, but of course, there isn't enough memory for even loading the filenames into memory. Is there a way to get maybe 100 filenames at a time?
Here's my code:
```
import os
import ... | 2010/02/01 | [
"https://Stackoverflow.com/questions/2177250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183487/"
] | A couple thoughts. First, you might use the [`glob`](http://docs.python.org/library/glob.html) module to get smaller groups of files. Second, sorting by line count is going to be very time consuming, as you have to open every file and count lines. If you can partition by byte count, you can avoid opening the files by u... | ```
import os,shutil
os.chdir("/mydir/")
numlines=20
destination = os.path.join("/destination","dir1")
for file in os.listdir("."):
if os.path.isfile(file):
flag=0
for n,line in enumerate(open(file)):
if n > numlines:
flag=1
break
if flag:
... | 5,029 |
50,916,340 | I'm looking for some general advice on how to either re-write application code to be non-naive, or whether to abandon neo4j for another data storage model. This is not *only* "subjective", as it relates significantly to specific, correct usage of the neo4j driver in Python and why it performs the way it does with my co... | 2018/06/18 | [
"https://Stackoverflow.com/questions/50916340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1507854/"
] | You could use a capturing group or to not have `DataHelper.ExecuteProc` in matching result put it in lookbehind:
```
(?<=DataHelper\.ExecuteProc\(")[^\\"]*(?:\\.[^\\"]*)*
```
See live [demo here](https://regex101.com/r/i3AgFx/1)
Breakdown:
* `(?<=` Start of positive lookbehind
+ `DataHelper\.ExecuteProc\("` Match... | You can do it like this:
```
var pattern = "\bDataHelper\..+?\(\"(?<procedure>[^\"]*?)\"";
var result = Regex.Match(input, pattern).Cast<Match>().Select(x=> x.Groups["procedure"].Value).ToList();
``` | 5,038 |
41,053,784 | I am new to python and trying to implement graph data structure in Python.
I have written this code, but i am not getting the desired result i want.
Code:
```
class NODE:
def __init__(self):
self.distance=0
self.colournode="White"
adjlist={}
def addno(A,B):
global adjlist
adjlist[A]=B
S... | 2016/12/09 | [
"https://Stackoverflow.com/questions/41053784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4825150/"
] | You node needs to have a label to print. You can't use just the variable name. The node has no way knowing name of your variable.
```
class NODE:
def __init__(self, name):
self.name=name
def __repr__(self):
return self.name
adjlist={}
def addno(A,B):
global adjlist
adjlist[A]=B
S=NODE... | You get that output because `Node` is an instance of a class ( you get that hint form the output of your program itself see this: `<main.NODE instance at 0x00000000029E6888>` ).
i think you are trying to implement `adjacency list` for some graph algorithm. in those cases you will mostly need the `color` and ``distance... | 5,039 |
64,024,941 | I am doing object detection using TensorFlow Object Detection API in Google colab. This is my directory structure.
```
object_detection/
training/
exported_model/
pipeline.config
model_main_tf2.py
exporter_main_v2.py
```
I run bellow for training.
```
!python model_main_tf2.py --model_dir=training --pipel... | 2020/09/23 | [
"https://Stackoverflow.com/questions/64024941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7907965/"
] | I found that while I run training even though it didn't produce any error It also not successful. Because It didn't generate files which should be generated after successful training like checkpoints. The `training/` directory was blank.
[this](https://github.com/tensorflow/models/blob/master/research/object_detection... | i follow the [struction](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/running_on_mobile_tf2.md) using export\_tflite\_graph\_tf2.py | 5,040 |
45,934,942 | I have just started using Tkinter and trying to create a simple pop-up box in python. I have copy pasted a simple code from a website:
```
from Tkinter import *
master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0,... | 2017/08/29 | [
"https://Stackoverflow.com/questions/45934942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8368577/"
] | ```
from Tkinter import *
def printData(firstName, lastName):
print(firstName)
print(lastName)
root.destroy()
def get_input():
firstName = entry1.get()
lastName = entry2.get()
printData(firstName, lastName)
root = Tk()
#Label 1
label1 = Label(root,text = 'First Name')
label1.pack()
label1.co... | You can create a popup information window as follow:
`showinfo("Window", "Hello World!")`
If you want to create a real popup window with input mask, you will need to generate a new TopLevel mask and open a second window.
```
win = tk.Toplevel()
win.wm_title("Window")
label = tk.Label(win, text="User input")
label.... | 5,041 |
60,985,999 | This code works correctly in python 2.X version. I am trying to use the similar code in python version 3.
The problem is that I do not want to use requests module. I need to make it work using "urllib3".
```
import requests
import urllib
event = {'url':'http://google.com', 'email':'abc@gmail.com', 'title':'test'}
u... | 2020/04/02 | [
"https://Stackoverflow.com/questions/60985999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139150/"
] | You can do something like this:
```
Where x.RoleId == 2 && (loc == null || s.LocationId == loc)
``` | Simply extract your managers and filter them if needed. That way you can as well easily apply more filters and code readability isn't hurt.
```
var managers = CSDB.Managers.AsQueryable();
if(loc > 0)
managers = managers.Where(man => man.LocationId == loc);
var myResult = from allocation in CSDB.Allocations
... | 5,046 |
32,829,504 | in python is a mathematical operator classed as an interger.
for example why isnt this code working
```
import random
score = 0
randomnumberforq = (random.randint(1,10))
randomoperator = (random.randint(0,2))
operator = ['*','+','-']
answer = (randomnumberforq ,operator[randomoperator], randomnumberforq)
useranswer =... | 2015/09/28 | [
"https://Stackoverflow.com/questions/32829504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5080233/"
] | You can't just concatenate an operator to a couple of numbers and expect it to be evaluated. You could use `eval` to evaluate the final string.
```
answer = eval(str(randomnumberforq)
+ operator[randomoperator]
+ str(randomnumberforq))
```
A better way to accomplish what you're attemptin... | You try to convert a string to an integer, but which isn't a number:
```
int(operator[randomoperator])
```
Your operatators in the array "operator" are strings, which don't represent numbers and can't be converted to integer values. On the other hand the input() function desires string as parameter value. So write:
... | 5,049 |
26,453,920 | My problem is that I'm trying to pass a `list` as a variable to a function, and I'd like to mutlti-thread the function processing. I can't seem to use `pool.map` because it only accepts iterables. I can't seem to use `pool.apply` because it seems to block the pool while it works, so I don't really understand how it all... | 2014/10/19 | [
"https://Stackoverflow.com/questions/26453920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3972123/"
] | You can use `pool.map`:
```
p = Pool(4)
p.map(distance, all_x)
```
as per the first example in the [doc](https://docs.python.org/2/library/multiprocessing.html). It will do the iteration for you! | Another way to Approach it is to pack your variables inside a tuble and unpack inside the function.
example:
```
def Add(z):
x,y = z
return x + y
a = [ 0 , 1, 2, 3]
b = [ 5, 6, 7, 8]
ab = (a,b)
Add(ab)
``` | 5,052 |
27,830,428 | I have been trying to compact my code for a primality test in python so that it makes use of list comprehensions, but for some reason it doesn't return the correct results:
```
def isPrime(n):
if n > 1:
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
re... | 2015/01/07 | [
"https://Stackoverflow.com/questions/27830428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4430875/"
] | As you want `False` if **any** lesser number is a divisor, code it directly that way:
```
def isPrime(n):
return n<=1 or not any(i for i in range(2, int(n ** 0.5) + 1) if n % i == 0)
```
Note that this uses a **genexp**, not a **listcomp**, because that allows `any` to terminate the whole operation as soon as it... | you can use `all`:
```
>>> def prime_check(n):
... if n > 1:
... return all(False for i in range(2, int(n ** 0.5) + 1) if n % i == 0)
...
>>> prime_check(6)
False
>>> prime_check(23)
True
>>> prime_check(108)
False
>>> prime_check(111)
False
>>> prime_check(101)
True
``` | 5,053 |
32,622,825 | I need to get some numbers from this website
<http://www.preciodolar.com/>
But the data I need, takes a little time to load and shows a message of 'wait' until it completely loads.
I used find all and some regular expressions to get the data I need, but when I execute, `python` gives me the 'wait' message that app... | 2015/09/17 | [
"https://Stackoverflow.com/questions/32622825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435341/"
] | As you are using the ASP.NET you can use the following two options in Page Load.
Option : 1
`Request.ServerVariables["HTTP_REFERER"]`
Although note on the above it is possible for browsers to block the value (empty value).
Option : 2
You can check the `Request.UrlReferrer` of the current `HttpRequest`: it will usuall... | Session\_Start event is not suitable for these kind of things. Session\_start runs when a user first enters in your applications, think it like the first page load.
You can use a query string parameter to determine where the user redirected from.
For example, if user redirected from sso.aspx to default.aspx, use url ... | 5,055 |
48,996,494 | I have two network interfaces (wifi and ethernet) both with internet access. Let's say my interfaces are `eth` (ethernet) and `wlp2` (wifi). I need specific requests to go through `eth` interface and others through `wpl2`.
Something like:
```
// Through "eth"
request.post(url="http://myapi.com/store_ip", iface="eth")... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48996494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4585081/"
] | I found a way using `pycurl`. This works like a charm.
```
import pycurl
from io import BytesIO
import json
def curl_post(url, data, iface=None):
c = pycurl.Curl()
buffer = BytesIO()
c.setopt(pycurl.URL, url)
c.setopt(pycurl.POST, True)
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json'... | Try changing the internal IP (192.168.0.200) to the corresponding iface in the code below.
```
import requests
from requests_toolbelt.adapters import source
def check_ip(inet_addr):
s = requests.Session()
iface = source.SourceAddressAdapter(inet_addr)
s.mount('http://', iface)
s.mount('https://', ifac... | 5,056 |
17,477,394 | I'm trying to install the M2Crypto on Python26 in Windows, but I am getting the below error.
>
> **error**: command 'swig.exe' failed: No such file or directory
>
>
>
This error occurs both using the "Easy Install" or "PIP Install" command. Follows the Log:
>
> running build
>
>
> running build\_py
>
>
> ru... | 2013/07/04 | [
"https://Stackoverflow.com/questions/17477394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1347355/"
] | This worked for me: (using winpython2.7)
```
pip install M2CryptoWin32
```
reference:
<https://github.com/dsoprea/M2CryptoWin32> | Putting this in answer format:
You could try to install a binary build from <http://chandlerproject.org/Projects/MeTooCrypto>
from mata's comment that resolved OP's issue | 5,061 |
48,888,239 | Here is my image:

I want to find the center of mass in this image. I can find the approximate location of the center of mass by drawing two perpendicular lines as shown in this image:
 will do what you want. Here's an example:
```
import imageio as iio
from skimage import filters
from skimage.color import rgb2gray # only needed for incorrectly saved images
from skimage.measure impo... | You need to know about **[Image Moments](https://en.wikipedia.org/wiki/Image_moment)**.
[Here](https://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html) there's a tutorial of how use it with opencv and python | 5,062 |
70,152,772 | I'm using an AWS Lambda function (in Python) to connect to an Oracle database (RDS) using cx\_Oracle library. But it is giving me the below error - "DPI-1047: Cannot locate a 64-bit Oracle Client library: "libclntsh.so: cannot open shared object file: No such file or directory".
Steps I've followed -
1. Created a pyt... | 2021/11/29 | [
"https://Stackoverflow.com/questions/70152772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17394264/"
] | Set the environment variable `DPI_DEBUG_LEVEL` to the value `64` and then rerun your code. The debugging output should help you figure out what is being searched. Note that you need to have the 64-bit instant client installed as well! | The reason I faced this issue was that I just downloaded cx\_Oracle library. In order to connect to the Oracle database from the Lambda function, we need to download the Oracle client and libaio libraries as well and club them with cx\_Oracle to create a Lambda Layer. Once I followed these steps, I was able to connect ... | 5,065 |
33,337,302 | this is a follow-up from [https://stackoverflow.com/questions/33336963/use-a-python-dictionary-to-insert-into-mysql/33337128#33337128](https://stackoverflow.com/questions/33336963/use-a-python-dictionary-to-insert-into-mysql/33337128#33337128/).
```
import pymysql
conn = pymysql.connect(server, user , password, "db"... | 2015/10/26 | [
"https://Stackoverflow.com/questions/33337302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751241/"
] | Think I figured it out.
I will add the info here in case someone else comes across this question:
I need to add `conn.commit()` to the script | You can use
```
try:
cur.execute(sql)
except Exception, e:
print e
```
If your code is wrong, the exception can tell you.
And it has another question.
the cols and vals are not match.
The values should be
```
vals = [dict[col] for col in cols]
``` | 5,066 |
5,948,110 | I have been using python for a while now and Im happy using it in most forms but I am wondering which form is more pythonic. Is it right to emulate objects and types or is it better to subclass or inherit from these types. I can see advantages for both and also the disadvantages. Whats the correct method to be doing th... | 2011/05/10 | [
"https://Stackoverflow.com/questions/5948110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462604/"
] | Key question you have to ask yourself here is:
>
> "How should my class change if the 'parent' class changes?"
>
>
>
Imagine new methods are added to `dict` which you don't override in your `UniqueDict`. If you want to express that **`UniqueDict` is simply a small derivation** in behaviour from `dict`'s behavio... | Subclassing is better as you won't have to implement a proxy for every single dict method. | 5,067 |
71,297,371 | Ok so I am trying to mass format a large text document to convert
```
#{'000','001','002','003','004','005','006','007','008','009'}
```
into
```
#{'000':'001','002':'003','004':'005','006':'007','008':'009'}
```
using python and have my function working, however it will only work if I run it line by line.
and w... | 2022/02/28 | [
"https://Stackoverflow.com/questions/71297371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18335232/"
] | Here is a possible solution:
```
result = [(str(dt.timetuple()[:6])[1:-1], s.split('_')[0]) for dt, s in OUTPUT]
``` | >
> Eventually I hope to pass the new list of tuples to a pandas dataframe.
>
>
>
You can use `.read_sql_query()` to pull the information directly into a DataFrame:
```py
import pandas as pd
import sqlalchemy as sa
connection_url = sa.engine.URL.create(
"mssql+pyodbc",
username="scott",
password="tig... | 5,070 |
20,054,030 | I have been getting the below error while using pxssh to get into remote servers to run unix commands ( like uptime )
```
Traceback (most recent call last):
```
File "./ssh\_pxssh.py", line 33, in
login\_remote(hostname, username, password)
File "./ssh\_pxssh.py", line 12, in login\_remote
if not s.login(hostnam... | 2013/11/18 | [
"https://Stackoverflow.com/questions/20054030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3005660/"
] | I have solved it by adding **sync\_multiplier** argument to the login function.
```
s.login(hostname, username, password, sync_multiplier=5 auto_prompt_reset=False)
```
note that **sync\_multiplier** is a communication timeout argument to perform successful synchronization. it tries to read prompt for at least **syn... | I had the same problem when pxssh tried to login on a very slow connection.
The pexpect lib apparently was fooled by the remote motd prompt.
This remote motd prompt contained a uname -svr prompt, which itself contained a # character inside.
Apparently, pexpect saw it like a prompt. From that point, the lib was not in ... | 5,071 |
28,329,596 | please help me.
I have the string (json request) :
```
{"jsonrpc":"2.0","result":[{"hostid":"10158"}],"id":1}
```
i try to parsing it with command :
```
reference_id2=`echo "$reference_id" | python -c 'import json, sys; print json.load(sys.stdin)["result"]'`
```
and still have `[{u'hostid': u'10158'}]`
How i c... | 2015/02/04 | [
"https://Stackoverflow.com/questions/28329596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3731374/"
] | You keep two complete copies of the file in memory at the same time, `@lines` and `$lines`. You might consider instead:
```
open (my $FH, "<", $file) or die "Can't open $file for read: $!";
$FH->input_record_separator(undef); # slurp entire file
my $lines = <$FH>;
close $FH or die "Cannot close $file: $!";
```
On su... | Working with XML using regexes is error prone and inefficient, as code which slurps the whole file as a string shows. To deal with XML you should be using an XML parser. In particular, you want a SAX parser which will work on the XML a piece at a time as opposed to a DOM parser which much read the whole file.
I'm goin... | 5,072 |
62,585,876 | Our python Dataflow pipeline works locally but not when deployed using the Dataflow managed service on Google Cloud Platform. It doesn't show signs that it is connected to the PubSub subscription. We have tried subscribing to both subscription and topic, neither of them worked. The messages accumulate in the PubSub sub... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62585876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6019494/"
] | Very late answer, it may still help someone else. I had the same problem, solved it like this:
1. Thanks to user Paramnesia1 who wrote [this](https://www.reddit.com/r/googlecloud/comments/srh28m/dataflow_pipeline_not_consuming_messages_from/) answer, I figured out that I was not observing all the logs on Logs Explorer... | I think for Pulling from subscription we need to pass with\_attributes parameter as True.
with\_attributes – True - output elements will be PubsubMessage objects. False -
output elements will be of type bytes (message data only).
Found similar one here:
[When using Beam IO ReadFromPubSub module, can you pull messages... | 5,078 |
22,488,763 | I have been trying to insert data into the database using the following code in python:
```
import sqlite3 as db
conn = db.connect('insertlinks.db')
cursor = conn.cursor()
db.autocommit(True)
a="asd"
b="adasd"
cursor.execute("Insert into links (link,id) values (?,?)",(a,b))
conn.close()
```
The code runs without any... | 2014/03/18 | [
"https://Stackoverflow.com/questions/22488763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2923505/"
] | You do have to commit after inserting:
```
cursor.execute("Insert into links (link,id) values (?,?)",(a,b))
conn.commit()
```
or use the [connection as a context manager](http://docs.python.org/2/library/sqlite3.html#using-the-connection-as-a-context-manager):
```
with conn:
cursor.execute("Insert into links (l... | It can be a bit late but set the `autocommit = true` save my time! especially if you have a script to run some bulk action as `update/insert/delete`...
**Reference:** <https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.isolation_level>
it is the way I usually have in my scripts:
```
def get_connection... | 5,079 |
51,696,395 | I'm trying to install gogle-assistant-sdk on Windows 10, and I'm getting a weird error which I can't understand.
After installing python for all users and setting ENV variables when i run this command -
```
py -m pip install google-assistant-sdk[samples]
```
I got following error -
```
Command ""C:\Program Files... | 2018/08/05 | [
"https://Stackoverflow.com/questions/51696395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6007248/"
] | Try this one
In the platforms/android/cordova-safe/starter-conceal.gradle change this
compile('com.facebook.conceal:conceal:1.0.0@aar')
to this
compile('com.facebook.conceal:conceal:2.0.1@aar')
This has worked for me. | Open `platforms/android/cordova-safe/starter-conceal.gradle`, then update the version of **com.facebook.conceal:conceal** from **1.0.0** to **1.1.3**, so the code should now be
```
dependencies {
compile('com.facebook.conceal:conceal:1.1.3@aar') {
transitive = true
}
}
``` | 5,080 |
48,644,767 | I'm looking at [\_math.c](https://github.com/python/cpython/blob/master/Modules/_math.c) in git (line 25):
```
#if !defined(HAVE_ACOSH) || !defined(HAVE_ASINH)
static const double ln2 = 6.93147180559945286227E-01;
static const double two_pow_p28 = 268435456.0; /* 2**28 */
```
and I noticed that ln2 value is differen... | 2018/02/06 | [
"https://Stackoverflow.com/questions/48644767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4828285/"
] | As user2357112 noted, this code came from FDLIBM. That was carefully written for IEEE-754 machines, where C doubles have 53 bits of precision. It doesn't really care what the actual log of 2 is, but cares a whole lot about the best 53-bit approximation to `log(2)`.
To reproduce the intended 53-bit-precise value, [17 d... | Python seems wrong, although I'm not sure it is an oversight or it has a deeper meaning. The explanation of BlackJack seems reasonable, but I don't understand, why they would give additional digits that are wrong.
You can check this yourself by using the formula under [More efficient series](https://en.wikipedia.org/w... | 5,081 |
73,348,659 | I've recently had to implement a simple bruteforce software in python, and I was getting terrible execution times (even for a O(n^2) time complexity), topping the 10 minutes of runtime for a total of 3700 \* 11125 \* 2 = 82325000 access operations on numpy arrays (intel i5 4300U).
I'm talking about access operations b... | 2022/08/14 | [
"https://Stackoverflow.com/questions/73348659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17474667/"
] | Let's do some simple list and array comparisons.
Make a list of 0s (as you do):
```
In [108]: timeit [0]*1000
2.83 µs ± 0.399 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
```
Make an array from that list - a lot more time:
```
In [109]: timeit np.array([0]*1000)
84.9 µs ± 103 ns per loop (mean ± st... | These are the 4 main advantages of an ndarray as far as i know :
1. It uses less storage for the pointers (1 byte instead of 8) because its a raw python object and not an array. It also only allows homogeneous numeric data types which also lead to a increase in performance.
2. Slicing doesnt copy the array (which is a... | 5,083 |
22,425,567 | I'm using [Loggly](https://www.loggly.com/) in order to have a centralized logs aggregator for my app running on AWS (Elastic beanstalk). However I'm not able to save my application logs using the Python logging library and the django logging configuration. In my Loggly control panel I can see a lot of logs coming from... | 2014/03/15 | [
"https://Stackoverflow.com/questions/22425567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267719/"
] | The problem is either in the local rsyslog service *receiving* the logs or in *sending* them. Your `LOGGING` setting is solid, but since you are taking control of everything (like the Django loggers) you should set `'disable_existing_loggers': True`. (Minor point: you can drop 'format' from the `loggly` loggers; the sy... | Googled around and saw your post on loggly's support. Did you see their reply and did it help you?
<http://community.loggly.com/customer/portal/questions/5898190-django-loggly-app-logs-not-saved> | 5,084 |
24,148,039 | I'm trying to use in python a shared\_ptr of a fundamental type (for instance int or double), but I don't know how to export it to python:
I have the following class:
```
class Holder
{
public:
Holder(int v) : value(new int(v)) {};
boost::shared_ptr<int> value;
};
```
The class is being exported in this way... | 2014/06/10 | [
"https://Stackoverflow.com/questions/24148039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/697884/"
] | One can use [`boost::python::class_`](http://www.boost.org/doc/libs/release/libs/python/doc/v2/class.html#class_-spec) to export `boost::shared_ptr<int>` to Python in the same manner as other types:
```cpp
boost::python::class_<boost::shared_ptr<int> >(...);
```
However, be careful in the semantics introduced when e... | Do you need to? Python has its own reference counting
mechanism, and it might be simpler just to use that. (But a lot
depends on what is going on on the C++ side.)
Otherwise: you probably need to define a Python object to
contain the shared pointer. This is relatively straightforward:
just define something like:
```... | 5,085 |
51,201,658 | I am trying to learn to code using python on my own but I ran into a problem.
I am using python's subprocess module to execute a .bat file, but the process seems to get stuck at the bat file. The python code currently looks like this:
```
import getpass
username = getpass.getuser()
from subprocess import Popen
p = P... | 2018/07/06 | [
"https://Stackoverflow.com/questions/51201658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10039856/"
] | You need to use `subprocess.PIPE` for `stdout` and `stderr`, or else they can't be fetched through `Popen.communicate`, and is the reason why your process is stuck.
```
from subprocess import Popen, PIPE
import getpass
username = getpass.getuser()
p = Popen("hidefolder.bat", cwd=r"C:\Users\%s\Desktop" % username, std... | I am a new programmer but i could solve my problem writting below code.
```
import subprocess
subprocess.call([r'ProcurementSoftwareRun.bat'])
print ('Software run successful')
```
My bat file was like:
```
@ECHO OFF
cmd /c start "" "C:\Program Files (x86)\UserName\ERPModule\PROCUREMENT.exe
exit
``` | 5,086 |
45,010,682 | I wanted to convert an object of type bytes to binary representation in python 3.x.
For example, I want to convert the bytes object `b'\x11'` to the binary representation `00010001` in binary (or 17 in decimal).
I tried this:
```
print(struct.unpack("h","\x11"))
```
But I'm getting:
```
error struct.error: unpack... | 2017/07/10 | [
"https://Stackoverflow.com/questions/45010682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987575/"
] | Starting from Python 3.2, you can use [`int.from_bytes`](https://docs.python.org/3/library/stdtypes.html#int.from_bytes).
Second argument, `byteorder`, specifies [endianness](https://en.wikipedia.org/wiki/Endianness) of your bytestring. It can be either `'big'` or `'little'`. You can also use `sys.byteorder` to get yo... | Iterating over a bytes object gives you 8 bit ints which you can easily format to output in binary representation:
```py
import numpy as np
>>> my_bytes = np.random.bytes(10)
>>> my_bytes
b'_\xd9\xe97\xed\x06\xa82\xe7\xbf'
>>> type(my_bytes)
bytes
>>> my_bytes[0]
95
>>> type(my_bytes[0])
int
>>> for my_byte in my... | 5,087 |
72,703,006 | I am trying to have this repo on docker: <https://github.com/facebookresearch/detectron2/tree/main/docker>
but when I want to docker compose it, I receive this error:
```
ERROR: Package 'detectron2' requires a different Python: 3.6.9 not in '>=3.7'
```
The default version of the python I am using is 3.10 but I don'... | 2022/06/21 | [
"https://Stackoverflow.com/questions/72703006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13334873/"
] | This is an [open issue with facebookresearch/detectron2](https://github.com/facebookresearch/detectron2/issues/4335). The developers updated the base Python requirement from 3.6+ to 3.7+ with [commit 5934a14](https://github.com/facebookresearch/detectron2/commit/5934a1452801e669bbf9479ae222ce1a8a51f52e) last week but d... | You can use pyenv: <https://github.com/pyenv/pyenv>
Just google `docker pyenv container`, will give you some entries like: <https://gist.github.com/jprjr/7667947>
If you follow the gist you can see how it has been updated, very easy to update to latest python that pyenv support. anything since 2.2 to 3.11
Only drawb... | 5,088 |
46,830,144 | There seem to be two kinds of generator-based coroutine:
1. From [a
reply](https://stackoverflow.com/a/46203922/156458)
by Jim Fasarakis Hilliard:
>
> **Generator-based coroutine**: A generator (`def` + `yield`) that is wrapped by [`types.coroutine`](https://docs.python.org/3/library/types.html#types.coroutine) . Yo... | 2017/10/19 | [
"https://Stackoverflow.com/questions/46830144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156458/"
] | They're the same kind of coroutine. `types.coroutine` and `asyncio.coroutine` are just two separate ways to create them.
`asyncio.coroutine` is older, predating the introduction of `async` coroutines, and its functionality has shifted somewhat from its original behavior now that `async` coroutines exist.
`asyncio.cor... | As far as I’m concerned, `async def` is the **proper** way to define a coroutine. `yield` and `yield from` have their purpose in generators, and they are also used to implement “futures”, which are the low-level mechanism that handles switching between different coroutine contexts.
I did [this diagram](https://default... | 5,089 |
49,922,073 | I just installed termcolor for python 2.7 on windows8.1. When I try to print colored text, I get the strange output.
```
from termcolor import colored
print colored('Hello world','red')
```
Here is the result:
```
[31mHello world[0m
```
Help to get out from this problem.Thanks,In advance | 2018/04/19 | [
"https://Stackoverflow.com/questions/49922073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9467325/"
] | See this [stackOverflow](https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python) post.
It basically says that in order to get the escape sequences working in Windows, you need to run os.system('color') first.
For example:
```
import termcolor
import os
os.system('color')
print(te... | `termcolor` or `colored` works perfectly fine under python 2.7 and I can't replicate your error on my Mac/Linux.
If you looks into the source code of `colored`, it basically print the string in the format as
```
\033[%dm%s\033[0m' % (COLORS[color], text)
```
Somehow your terminal environment does not recognise th... | 5,090 |
3,079,684 | As you know, Windows has a "Add/Remove Programs" system in the Control Panel.
Let's say I am preparing an installer and I want to register my program to list of installed programs and want it to be uninstallable from "Add/Remove Programs"?
Which protocols should I use. Any tutorials or docs about registering programs... | 2010/06/20 | [
"https://Stackoverflow.com/questions/3079684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54929/"
] | As stated on IRC:
"Windows keeps its uninstall information in the registry"
Its in HLLM\Software\Microsoft\Windows\CurrentVersion\uninstall\ keys.
You need a few things from the Win32 API, but I belive there's a fair amount of Python support for the win32 API.
Basically, a key in ...\Uninstall\ with a unique name ... | Inno Setup is open source so perhaps you can get some ideas from that. | 5,091 |
53,119,083 | In the [`xonsh`](https://github.com/xonsh/xonsh/) shell how can I receive from a pipe to a python expression? Example with a `find` command as pipe provider:
```
find $WORKON_HOME -name pyvenv.cfg -print | for p in <stdin>: $(ls -dl @(p))
```
The `for p in <stdin>:` is obviously pseudo code. What do I have to replac... | 2018/11/02 | [
"https://Stackoverflow.com/questions/53119083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/65889/"
] | The easiest way to pipe input into a Python expression is to use a function that is a [callable alias](https://xon.sh/tutorial.html#callable-aliases), which happens to accept a stdin file-like object. For example,
```
def func(args, stdin=None):
for line in stdin:
ls -dl @(line.strip())
find $WORKON_HOME... | Drawing on the answer from [Anthony Scopatz](https://stackoverflow.com/users/2312428/anthony-scopatz) you can do this on one line with a [callable alias](https://xon.sh/tutorial.html#callable-aliases) as a lambda. The function takes the third form, `def mycmd2(args, stdin=None)`. I discarded `args` with `_` because I d... | 5,094 |
62,032,878 | I am new in ebpf & xdp topic and want to do learn it. My question is how to use ebpf filter to filter the packet on specific payload matching? for example, if the data(payload) of the packet is 1234 its passes to the network stack otherwise it blocks the packet. I reached payload length. For example, if I want to match... | 2020/05/26 | [
"https://Stackoverflow.com/questions/62032878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13623550/"
] | What did you try? You should probably read a bit more about eBPF to try to understand how to process packets, the basic example you give does not sound too complicated.
Basically you would have to parse the headers to see where your payload begins. [Simple BPF parsing examples](https://git.kernel.org/pub/scm/linux/ker... | Your edit is pretty much a new question, so here an updated answer. Please consider opening a new question instead in the future.
There are a number of things that are wrong in your program. In particular:
```c
1| payload_offset = sizeof(struct udphdr);
2| payload_size = ntohs(udp->len) - sizeof(struct udphdr);... | 5,095 |
54,468,348 | From the cmd window I have to do this every time I run a script:
```
C:\>cd C:\Users\my name\AppData\Local\Programs\Python\Python37
C:\Users\my name\AppData\Local\Programs\Python\Python37>python "C:\\Users\\my name\\AppData\\Local\\Programs\\Python\\Python37\\scripts\\helloWorld.py"
hello world
```
How can I get aw... | 2019/01/31 | [
"https://Stackoverflow.com/questions/54468348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3524158/"
] | You need to pay attention to the current working directory of your python interpreter. It basically means the directory you are currently in where you execute the python interpreter, and it relies on that path to look for your script passed in. If you're inside the script already, you can easily check with `os.getcwd()... | There is a designated directory where you can put your .py scripts if you want to invoke them without specifying the full path.
Setting this up correctly will allow you to run the script simply by invoking the script name (if the .py extension is registered to the interpreter and not an editor).
Windows
=======
If y... | 5,096 |
63,841,244 | I have been trying to scrape data from [this site](http://www.indianbluebook.com/). I need to fill **Get the precise price of your car** form ie. the year, make, model etc.. I have written the following code till now:
```
import requests
import time
from selenium import webdriver
from selenium.webdriver.common.by impo... | 2020/09/11 | [
"https://Stackoverflow.com/questions/63841244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9952858/"
] | You can use the below approach to achieve the same.
```
#Set link according to data need
driver.get('http://www.indianbluebook.com/')
#Wait webpage to fully load necessary tables
def ajaxwait():
for i in range(1, 30):
x = driver.execute_script("return (window.jQuery != null) && jQuery.active")
tim... | To click on **BANGALORE** and then select **2020** from the dropdown, you need to induce [WebDriverWait](https://stackoverflow.com/questions/49775502/webdriverwait-not-working-as-expected/49775808#49775808) for the `element_to_be_clickable()` and you can use the following [Locator Strategies](https://stackoverflow.com/... | 5,097 |
59,410,323 | so I have a csv file which is of the form -
```
No. Name Money
1 Tom Cat 100
2 Dan Man 200
3 Marie Claw300
4 Catherine K. 400
```
I need to detect if the some part of my second column data is in my third column. Is there a wa... | 2019/12/19 | [
"https://Stackoverflow.com/questions/59410323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12021224/"
] | Unfortunately you cannot use blade syntax within Vue unless you are writing the Vue code directly in the blade template, which would not be best practice. One thing I have found helpful is to write out all my Laravel API routes in a google docs so they are easier to refer to when referencing them in Vue. I hope that he... | You can only use blade syntax, if you're in a `.blade` file.
You have to statically set this route or others when calling a API
NOT RECOMMENDED:
Or you can define a js variable in your "master" blade file, which you're then using in the `Register.vue` file. | 5,098 |
55,975,930 | I'm locally running a standard app engine environment through dev\_appserver and cannot get rid of the following error:
>
> ImportError: No module named google.auth
>
>
>
Full traceback (replaced personal details with `...`):
```
Traceback (most recent call last):
File "/Users/.../google-cloud-sdk/platform/goo... | 2019/05/03 | [
"https://Stackoverflow.com/questions/55975930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3793914/"
] | Your `google.auth` is installed in the system's Python site packages, not in your app:
>
> Location: /Users/.../Library/Python/2.7/lib/python/site-packages
>
>
>
You need to install your app's python dependencies inside your app instead - note the `-t lib/` pip option in the [Copying a third-party library](https:... | After much trial and error, I found the bug: A python runtime version issue.
In my app.yaml file I had specified:
```
service: default
runtime: python27
api_version: 1
threadsafe: false
```
There I changed runtime to:
```
runtime: python37
```
Thanks to @AlassaneNdiaye for pointing me in this direction in the co... | 5,100 |
56,317,630 | I am new in python and I am working with CSV file with over 10000 rows. In my CSV file, there are many rows with the same id which I would like to merge them in one and also combine their information as well.
For instance, the data.csv look like (id and info is the name of columns):
```
id| info
1112| storage is fu... | 2019/05/26 | [
"https://Stackoverflow.com/questions/56317630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8921989/"
] | I think about some simplier way:
```
some_dict = {}
for idt, txt in line: #~ For line use your id, info reader.
some_dict[idt] = some_dict.get(idt, "") + txt
```
It should create your dream structure without imports, and i hope most efficient way.
Just to understand, `get` have secound argument, what must retur... | Just make a dictionary where id's are keys:
```
from collections import defaultdict
by_id = defaultdict(list)
for id, info in your_list:
by_id[id].append(info)
for key, value in by_id.items():
print(key, value)
``` | 5,101 |
25,012,031 | I've migrated a Liferay 6.2-CE-GA2 server from Liferay 6.1.1-ce-ga2.
I made a few changes in custom hooks and themes to addapt to the new version.
On locale I have never had a problem with memory nor with the 6.1 version, but once in production, server runs out of memory in a few hours.
I tried to adjust heap parame... | 2014/07/29 | [
"https://Stackoverflow.com/questions/25012031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3837065/"
] | As it seems the `open`-method doesn't update the `position` of the `infowindow`, you'll need to do it on your own(e.g. by binding the position of the infowindow to the position of the marker):
```
infowindow.unbind('position');
if(infowindow.getPosition() != this.getPosition()) {
infowindow.bindTo('pos... | I am not sure about `infowindow.getPosition()` . But you can try this code if you want to check whether the infowindow is open or not.
JS:
```
function check(infoWindow) {
var map = infoWindow.getMap();
return (map !== null && typeof map !== "undefined");
}
```
pass `infowindow` into the function and it wil... | 5,102 |
17,066,347 | I have this issue with Titanium Studio. I can't compile my project for Android. I try to Run or Debug to project, but I've got this message:
```
Titanium Command-Line Interface, CLI version 3.1.0, Titanium SDK version 3.1.0.GA
Copyright (c) 2012-2013, Appcelerator, Inc. All Rights Reserved.
[INFO] : Running emulato... | 2013/06/12 | [
"https://Stackoverflow.com/questions/17066347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486286/"
] | If this happens with the Kitchen Sink demo, the fix is to go into the Android SDK Manager and install "Android 3.0 (API 11)". Make sure the app uses emulator "Google APIs (Android 2.3.3)" and "WVGA854". I assume there's a Titanium bug because you have to install a higher API level (3.0) than is actually used (2.3.3). U... | Did you read [System Requirements](http://docs.appcelerator.com/titanium/latest/#!/guide/Quick_Start-section-29004949_QuickStart-SystemRequirements)?
From Documentation:
>
> For Windows, the 32-bit version of Java JDK is required regardless of
> whether Titanium is running on a 32-bit or 64-bit system.
>
>
>
Try... | 5,104 |
49,870,594 | I am trying to install few of the python packages from within a python script and I am using `pip.main(install)` for that. Below is code snippet
```
try:
import requests
except:
import pip
pip.main(['install', '-q', 'requests==2.0.1','PyYAML==3.11'])
import requests
```
I have tried using importing m... | 2018/04/17 | [
"https://Stackoverflow.com/questions/49870594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4943621/"
] | I had the same issue and just running the below command solved it for me:
```
easy_install pip
``` | The short answer is don't do this. Use `setup.py` or a straight import statement.
[Here is why this doesn't work with pip and how to get around it if necessary.](https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program)
`pip` affects the whole environment. Depending on who is running this and why, they ... | 5,107 |
3,215,455 | Is it possible to use multiple languages along side with ruby. For example, I have my application code in Ruby on Rails. I would like to calculate the recommendations and I would like to use python for that. So essentially, python code would get the data and calculate all the stuff and probably get the data from DB, ca... | 2010/07/09 | [
"https://Stackoverflow.com/questions/3215455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88898/"
] | If you are offloading work to an exterior process, you may want to make this a webservice (ajax, perhaps) of some sort so that you have some sort of consistent interface.
Otherwise, you could always execute the python script in a subshell through ruby, using stdin/stdout/argv, but this can get ugly quick. | I would use the system command
as such
```
system("python myscript.py")
``` | 5,116 |
48,160,819 | I want to write a python program to process csv sheets, the total numbers of rows and cols are different each time.
One of things I want to do is to delete columns containing a specific string.
```
import csv
input = open("1.csv","rb")
reader = csv.reader(input)
output = open("2.csv","wb")
writer = csv.writer(output)... | 2018/01/09 | [
"https://Stackoverflow.com/questions/48160819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9190725/"
] | You can find the column index with this code and can delete it. I test it ok
import csv
```
with open("SampleCSVFile_2kb.csv","rb") as source:
rdr= csv.reader( source )
with open("result","wb") as result:
wtr= csv.writer( result )
index = -1
for r in rdr:
for item in r:
... | Assume csv looks like
```
name,color,price
apple,red,10
banana,yellow,5
```
```
import csv
with open(file_path, "r") as f:
file = csv.reader(f)
for line in file:
print(line[0], line[1], line[2])
```
print out would be
```
name color price
apple red 10
banana yellow 5
``` | 5,120 |
48,892,348 | I have a for loop in python and at the end of each step I want the output to be added as a new column in a csv file. The output I have is a 40x1 array. So if the for loop consists of 100 steps, I want to have a csv file with 100 columns and 40 rows at the end. What I have now, at the end of each time step is the follow... | 2018/02/20 | [
"https://Stackoverflow.com/questions/48892348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6756920/"
] | The insight would be that when `serverUrl` is truthy, you don't need the `switch` at all - you always return the same value that was switched upon. So don't do the test in every switch `case`, but do it once before that:
```
function checkField(str: string) : string {
if (serverUrl === 'abc')
return str.to... | Borrowing a bit from @Bergi's answer, I would create a mapping object to make it a little cleaner. E.g.:
```
function checkField(str: string) : string {
//create a mapping
var myMapping = {
'code' : 'CODE',
'webid' : 'Webid',
'pkid' : 'PkId',
'barcode': 'Barcode',
... | 5,121 |
28,334,966 | I am trying to open an Excel file (.xls) using xlrd. This is a summary of the code I am using:
```
import xlrd
workbook = xlrd.open_workbook('thefile.xls')
```
This works for most files, but fails for files I get from a specific organization. The error I get when I try to open Excel files from this organization foll... | 2015/02/05 | [
"https://Stackoverflow.com/questions/28334966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/382374/"
] | What are they using to generate that file ?
They are using some Java Excel API (see below, [link here](http://jexcelapi.sourceforge.net/)), probably on an IBM mainframe or similar.
From the stack trace the writeaccess information can't decoding into Unicode because the @ character.
For more information on the write... | This worked for me.
```
import xlrd
my_xls = xlrd.open_workbook('//myshareddrive/something/test.xls',encoding_override="gb2312")
``` | 5,123 |
21,867,596 | I'm a little new to web parsing in python. I am using beautiful soup. I would like to create a list by parsing strings from a webpage. I've looked around and can't seem to find the right answer. Doe anyone know how to create a list of strings from a web page? Any help is appreciated.
My code is something like this:
`... | 2014/02/18 | [
"https://Stackoverflow.com/questions/21867596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2278570/"
] | Having difficulty understanding what you are trying to achieve... If you want all values of `page_data.string` in `page_List`, then your code should look like this:
```
page_List = []
for page_data in page_find:
page_List.append(page_data.string)
```
Or using a list comprehension:
```
page_List = [page_data.str... | Here it is modified to call the web page as a string
```
import requests
the_web_page_as_a_string = requests.get(some_path).content
from lxml import html
myTree = html.fromstring(the_web_page_as_a_string)
td_list = [ e for e in myTree.iter() if e.tag == 'td']
text_list = []
for td_e in td_list:
text = td_e.text_c... | 5,124 |
16,815,170 | So this is probably a very basic question about output formatting in python using '.format' and since I'm a beginner, I can't figure this out for the life of me. I've tried to be as detailed as possible, just to make sure that there's no confusion.
Let me give you an example so that you can better understand my dilem... | 2013/05/29 | [
"https://Stackoverflow.com/questions/16815170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2396553/"
] | Look at the *for loop*:
```
for students in students:
# ^^^^^^^^
```
So, `students`(inside loop) does not actually refers to **list of list**. And `students[0]` refers to **first element** from **element** from **list of lists**, as expected.
I suggest replace `students` from function argument, say, with `all_stu... | Try renaming the variable `list` into something that's not a reserved word or built-in function or type.
What's confusing to beginners - and it happens to everyone sooner or later - is what happens if you redefine or use in unintended ways a reserved word or a builtin.
If you do
```
list = [1, 2, 3, 4]
```
you re-... | 5,127 |
15,433,372 | How to perform **stepwise regression** in **python**? There are methods for OLS in SCIPY but I am not able to do stepwise. Any help in this regard would be a great help. Thanks.
Edit: I am trying to build a linear regression model. I have 5 independent variables and using forward stepwise regression, I aim to select v... | 2013/03/15 | [
"https://Stackoverflow.com/questions/15433372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2174063/"
] | You may try mlxtend which got various selection methods.
```
from mlxtend.feature_selection import SequentialFeatureSelector as sfs
clf = LinearRegression()
# Build step forward feature selection
sfs1 = sfs(clf,k_features = 10,forward=True,floating=False, scoring='r2',cv=5)
# Perform SFFS
sfs1 = sfs1.fit(X_train, ... | You can make forward-backward selection based on `statsmodels.api.OLS` model, as shown [in this answer](https://datascience.stackexchange.com/a/24447/24162).
However, [this answer](https://stats.stackexchange.com/questions/20836/algorithms-for-automatic-model-selection/20856#20856) describes why you should not use ste... | 5,128 |
17,332,350 | For some reason I can't log into the same account on my home computer as my work computer.
I was able to get Bo10's code to work, but not abernert's and I would really like to understand why.
Here is my updates to abernert's code:
```
import csv
import sys
import json
import urllib2
j = urllib... | 2013/06/26 | [
"https://Stackoverflow.com/questions/17332350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1887261/"
] | The problem is that you're not using the `csv` module, you're using the `pickle` module, and this is what `pickle` output looks like.
To fix it:
```
csvfile = open('output.csv', 'w')
csv.writer(csvfile).writerows(stationList)
csvfile.close()
```
---
Note that you're going out of your way to build a transposed tabl... | As abarnert mentions, you're not actually using the `csv` module that you've imported.
Also, your logic for storing the columns might actually be transposed. I think you might want to do this instead (*edited to fix the tuple/list confusion*):
```
import csv
import json
import urllib2
j = urllib2.urlopen('https://ci... | 5,138 |
42,418,713 | I need to perform an integration with python but with one of the limits being a variable, and not a number (from 0 to z).
I tried the following:
```
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad
def I(z,y,a): #function I want to integrate
I = (a*(y*(1... | 2017/02/23 | [
"https://Stackoverflow.com/questions/42418713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7569812/"
] | **Edit:** In your code you should only your `args` argument as `agrs=(y, a)`, z should not be included. Then you can access the result of integration by indexing the first element of the returned tuple.
Actually `quad` returns a tuple. The first element in the tuple is the reuslt you want. Since I cannot get your code... | I don't think `quad` accepts vector valued integration boundaries. So in this case you'll actually have to either loop over `z` or use `np.vectorize`. | 5,139 |
62,908,688 | Recently I went on to clean my python code. I felt tiresome to remove all print statements in the code ony by one.
Is there any shortcut in editor or RE for removing or commenting print statements in a python program in one go? | 2020/07/15 | [
"https://Stackoverflow.com/questions/62908688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8721742/"
] | Find / Replace
--------------
* Find Replace `print(` with `# print(` will comment them out
* Probably works in most editors
Using [Notepad++](https://notepad-plus-plus.org/downloads/) with regex
----------------------------------------------------------------------
* Free to download
* Recognizes many programming l... | You should avoid working with print statements. Use the python logging module instead:
```
import logging
logging.debug('debug message')
```
Once you finished your development and dont need debugging information, you can increase the log level:
```
logging.basicConfig(format='%(levelname)s:%(message)s', level=loggi... | 5,144 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.