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 |
|---|---|---|---|---|---|---|
35,494,331 | How can I get generics to work in Python.NET with CPython. I get an error when using the subscript syntax from [Python.NET Using Generics](http://pythonnet.sourceforge.net/readme.html#generics)
```
TypeError: unsubscriptable object
```
With Python 2.7.11 + pythonnet==2.1.0.dev1
```
>python.exe
Python 2.7.11 (v2.7.1... | 2016/02/18 | [
"https://Stackoverflow.com/questions/35494331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742745/"
] | You can get the generic class object explicitly:
```
EventHandler = getattr(System, 'EventHandler`1')
```
The number indicates the number of generic arguments. | That doesn't work because there are both generic and non-generic versions of the `EventHandler` class that exist in the `System` namespace. The name is overloaded. You need to indicate that you want the generic version.
I'm not sure how exactly Python.NET handles overloaded classes/functions but it seems like it has a... | 10,738 |
30,189,013 | is the code he wants me to enter that fails
```
from sys import argv
script, user_name = argv
prompt = '> '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
```
is the code I modified after seeing e... | 2015/05/12 | [
"https://Stackoverflow.com/questions/30189013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4891078/"
] | Here is one method:
```
select v.*
from vusearch as v
where v.JobId = (select max(v2.JobId)
from vusearch as v2
where v2.AddressId = v.AddressId
);
``` | Managed to get it fixed - I probably hadn't provided enough information as I was trying to keep my explanation simple.
Many thanks for your help Gordon
((vuSearch.PDID) IN ( (SELECT Max(v2.PDID) FROM vuSearch AS v2 GROUP BY v2.PAID))) | 10,739 |
51,947,819 | I have a pandas dataframe with 5 years daily time series data. I want to make a monthly plot from whole datasets so that the plot should shows variation (std or something else) within monthly data. Simillar figure I tried to create but did not found a way to do that:
[? If you do, this may help you:
```
df['month'] = df.index.strftime("%m-%d")
df['year'] = df.index.year
df.set_index(['month']).drop(['year'],1).plot()
``` | 10,740 |
67,010,037 | I am not an expert in python. When I run this code, I get an error stating that the source is empty. It occurs in the statement that converts bgr to rgb from a live video feed. I also attached some of the error code below. I did try to resolve it changing some of it, but it did not work out. So, if you have any ideas, ... | 2021/04/08 | [
"https://Stackoverflow.com/questions/67010037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14020038/"
] | You can use `Series.isin`:
```
In [1998]: res = df1[df1.id_number.isin(df2.id_number) & df1.accuracy.ge(85)]
In [1999]: res
Out[1999]:
Name Contact_number id_number accuracy
0 Eric 9786543628 AZ256hy 90
1 Jack 9786543628 AZ98kds 85
```
**EDIT:** If you want only certain columns:
... | Edit:
I made changes to the conditions. This should work
```
df = pd.read_excel(open(r'input.xlsx', 'rb'), sheet_name='sheet1')
df2 = pd.read_excel(open(r'input.xlsx', 'rb'), sheet_name='sheet2')
df.loc[(df['id_number'] == df2['id_number']) & (df['accuracy']>= 85),['Name','Contact_number', 'id_number']]
``` | 10,741 |
28,458,785 | How can I pass a `sed` command to `popen` without using a raw string?
When I pass an sed command to `popen` in the list form I get an error: `unterminated address regex` (see first example)
```python
>>> COMMAND = ['sed', '-i', '-e', "\$amystring", '/home/map/myfile']
>>> subprocess.Popen(COMMAND).communicate(input=N... | 2015/02/11 | [
"https://Stackoverflow.com/questions/28458785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1659599/"
] | The difference between the two forms is that with `shell=True` as an argument, the string gets passed as is to the shell, which then interprets it. This results in (with bash):
```
sed -i -e \$amystring /home/map/myfile
```
being run.
With the list args and the default `shell=False`, python calls the executable dir... | There is not such thing as a raw string. There are only raw string *literals*.
A literal -- it is something that you type in the Python source code.
`r'\$amystring'` and `'\\$amystring'` are the same *strings objects* despite being represented using different string *string literals*.
As [@Jonathan Villemaire-Krajde... | 10,742 |
65,354,710 | I was trying to Connect and Fetch data from BigQuery Dataset to Local Pycharm Using Pyspark.
I ran this below Script in Pycharm:
```
from pyspark.sql import SparkSession
spark = SparkSession.builder\
.config('spark.jars', "C:/Users/PycharmProjects/pythonProject/spark-bigquery-latest.jar")\
.getOrCreate()
co... | 2020/12/18 | [
"https://Stackoverflow.com/questions/65354710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10030455/"
] | Start your file system references with `file:///c:/...` | You need to replace `/` with `\` for the path to work | 10,743 |
29,580,828 | I'm starting with Docker. I have started with a Hello World script in Python 3. This is my Dockerfile:
```
FROM ubuntu:latest
RUN apt-get update
RUN apt-get install python3
COPY . hello.py
CMD python3 hello.py
```
In the same directory, I have this python script:
```
if __name__ == "__main__":
print("Hello W... | 2015/04/11 | [
"https://Stackoverflow.com/questions/29580828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3026283/"
] | Thanks to Gerrat, I solved it this way:
```
COPY hello.py hello.py
```
instead of
```
COPY . hello.py
``` | You need to install python this way and confirm it with the -y.
RUN apt-get update && apt-get install python3-dev -y | 10,744 |
25,561,020 | Below are the snippets of my code regarding file upload.
Here is my HTML code where I will choose and upload the file:
```html
<form ng-click="addImportFile()" enctype="multipart/form-data">
<label for="importfile">Import Time Events File:</label><br><br>
<label for="select_import_file">SELECT FILE:</label><b... | 2014/08/29 | [
"https://Stackoverflow.com/questions/25561020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3988760/"
] | Hi I can finally upload the file, I change the angular part, I change it by this:
```
$scope.addImportFile = function() {
var f = document.getElementById('file').files[0]; console.log(f);
var formData = new FormData();
formData.append('file', f);
$http({method: 'POST', url: '... | The first thing is about the post request. Without ng-click="addImportFile()", the browser will usually take care of serializing form data and sending it to the server. So if you try:
```
<form method="put" enctype="multipart/form-data" action="http://127.0.0.1:5000/api/v1.0/upload_file">
<label for="importfile">I... | 10,745 |
62,497,777 | Can't start server using Apache + Django
OS: MacOS Catalina
Apache: 2.4.43
Python: 3.8
Django: 3.0.7
Used by Apache from Brew.
mod\_wsgi installed via pip.
The application is created through the standard command
```
django-admin startproject project_temp
```
The application starts when the command... | 2020/06/21 | [
"https://Stackoverflow.com/questions/62497777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7060063/"
] | `&str` is an immutable slice, it somewhat similar to [`std::string_view`](https://en.cppreference.com/w/cpp/string/basic_string_view), so you cannot modify it. Instead, you may use iterator and collect a new [`String`](https://doc.rust-lang.org/std/string/struct.String.html):
```rust
let removed: String = foo
.cha... | Kitsu's solution w/o lambda
```
fn remove(start: usize, stop: usize, s: &str) -> String {
let mut rslt = "".to_string();
for (i, c) in s.chars().enumerate() {
if start > i || stop < i + 1 {
rslt.push(c);
}
}
rslt
}
```
…as fast as `replace_range` but can handle unicode cha... | 10,746 |
9,511,825 | I have a pythonscript run.py that I currently run in the command line. However, I want a start.py script either in python (preferably) or .bat, php, or some other means that allows me to make it such that once run.py finishes running, the start.py script will reexecute the run.py script indefinitely, but ONLY after the... | 2012/03/01 | [
"https://Stackoverflow.com/questions/9511825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | Your problem is that you're using -INFINITY and +INFINITY as win/loss scores. You should have scores for win/loss that are higher/lower than any other positional evaluation score, but not equal to your infinity values. This will guarantee that a move will be chosen even in positions that are hopelessly lost. | It's been a long time since i implemented minimax so I might be wrong, but it seems to me that your code, if you encounter a winning or losing move, does not update the best variable (this happens in the (board.checkEnd()) statement at the top of your method).
Also, if you want your algorithm to try to win with as muc... | 10,747 |
6,539,267 | I started coding an RPG engine in python and I want it to be very scripted(buffs, events). I am experimenting with events and hooking. I would appreciate if you could tell me some matured opensource projects(so i can inspect the code) to learn from. Not necessarily python, but it would be ideal.
Thanks in advance. | 2011/06/30 | [
"https://Stackoverflow.com/questions/6539267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492162/"
] | As Daenyth suggested, [pygame](http://pygame.org/) is a great place to start. There are plenty of projects linked to on their page.
The other library that is quite lovely for this type of thing is [Panda3D.](http://www.panda3d.org/) Though I haven't yet used it, the library comes with samples, and it looks like there ... | You might have a look at `pygame`, it's pretty common for this sort of thing. | 10,750 |
63,129,698 | I'm using subprocess to spawn a `conda create` command and capture the resulting `stdout` for later use. I also immediately print the `stdout` to the console so the user can still see the progress of the subprocess:
```
p = subprocess.Popen('conda create -n env1 python', stdout=subprocess.PIPE, stderr=subprocess.STDOU... | 2020/07/28 | [
"https://Stackoverflow.com/questions/63129698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1963945/"
] | Although I'm sure pexpect would have worked in this case, I decided it would be overkill. Instead I used MisterMiyagi's insight and replaced `readline` with `read`.
The final code is as so:
```
p = subprocess.Popen('conda create -n env1 python', stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while p.poll() is None... | For this use case I recommend using [pexpect](https://pypi.org/project/pexpect/). *stdin != stdout*
Example use case where it conditionally sends to *stdin* on prompts on *stdout*
```
def expectgit(alog):
TMPLOG = "/tmp/pexpect.log"
cmd = f'''
ssh -T git@github.com ;\
echo "alldone" ;
'''
with open(TMPLOG... | 10,751 |
49,830,562 | Let the two lists be
```
x = [0,1,2,2,5,2,1,0,1,2]
y = [0,1,3,2,1,4,1,3,1,2]
```
How to find the similar elements in these two lists in python and print them.
What I am doing-
```
for i, j in x, y:
if x[i] == y[j]:
print(x[i], y[j])
```
I want to find elements like x[0], y[0] and x[1], y[1] etc.
This doe... | 2018/04/14 | [
"https://Stackoverflow.com/questions/49830562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9645192/"
] | Two problems:
First, you should initiate `smallest` with the last element if you want to search from the end of array:
```
int result = findMinAux(arr,arr.length-1,arr[arr.length - 1]);
```
Secondly, you should reassign `smallest`:
```
if(startIndex>=0) {
smallest = findMinAux(arr,startIndex,smallest);
}
``` | See this code. In every iteration, elements are compared with current element and index in increased on the basis of comparison. This is tail recursive as well. So it can be used in large arrays as well.
```
public class Q1 {
public static void main(String[] args) {
int[] testArr = {12, 32, 45, 435, -1, 3... | 10,752 |
73,818,926 | I am trying to send 2 params to the backend through a get request that returns some query based on the params I send to the backend. I am using React.js front end and flask python backend.
My get request looks like this:
```
async function getStatsData() {
const req = axios.get('http://127.0.0.1:5000/stat/', {
... | 2022/09/22 | [
"https://Stackoverflow.com/questions/73818926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19603491/"
] | In your backend route you are expecting the values in url as dynamic segment, but from axios you are sending it as [query sring](https://en.wikipedia.org/wiki/Query_string).
**Solution:**
You can modify the axios request like this to send the values as dynamic segment:
```
const user = 0;
const flashcard_id = 1;... | Send the parameters like this:
```
const req = axios.get(`http://127.0.0.1:5000/stat/${user}/${flashcard_id}`)
```
and in Flask you receive the parameters like this:
```
@app.route('/stat/<user>/<flashcard_id>', methods=['GET', 'POST', 'OPTIONS'])
def stats(user, flashcard_id):
``` | 10,761 |
52,154,682 | After installing python 3.7 from python.org, running the Install Certificate.command resulted in the below error. Please, can you provide some guidance? Why does Install Certificate.command result in error?
[Some background]
Tried to install python via anaconda, brew and python.org, even installing version 3.6.6, hopi... | 2018/09/03 | [
"https://Stackoverflow.com/questions/52154682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10297557/"
] | wanted to answer my own question as I seem to have fixed most of the issues. The solution:
1. Created a pip directory and then a pip.conf file in $HOME/Library/Application Support
2. To the pip.conf added code
[global]
trusted-host = pypi.python.org
pypi.org
files.pythonhosted.org
3. Started installing using
$ pi... | You don't need to run Install Certificate.command.
You should reinstall Xcode command line tools that contains Python.
```sh
pip3 uninstall -y -r <(pip requests certifi)
brew uninstall --ignore-dependencies python3
sudo rm -rf /Library/Developer/CommandLineTools
xcode-select --install
sudo xcode-select -r
python3 -m... | 10,762 |
39,739,195 | I have a JSON object that I'd like to transform using jq from one form to another (of course, I could use javascript or python and iterate, but jq would be preferable). The issue is that the input contains long arrays that needs to be broken into multiple smaller arrays whenever data stops repeating within the first ar... | 2016/09/28 | [
"https://Stackoverflow.com/questions/39739195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3160967/"
] | Is it doable? Of course!
First you'll want to group the data by rows then columns. Then with the groups, build your values/sources arrays.
```
.headers as $headers | .data
# make the data easier to access
| map({ row: .[0], col: .[1], val: .[2], src: .[3] })
# keep it sorted so they are in expected order ... | Since the primary data source here can be thought of as a
two-dimensional matrix, it may be worth considering a
matrix-oriented approach to the problem, especially if it is
intended that empty rows in the input matrix are not simply omitted, or if
the number of columns in the matrix is not initially known.
To spice th... | 10,763 |
50,967,329 | I am trying to create a script that will
* look at each word in a text document and store in a list (WordList)
* Look at a second text document and store each word in a list (RandomText)
* Print out the words that appear in both lists
I have come up with the below which stores the text in a file, however I can't seem... | 2018/06/21 | [
"https://Stackoverflow.com/questions/50967329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7276704/"
] | Add `tools:replace="android:label"` to your `<application>` tag in AndroidManifest.xml as suggested in error logs.
This error might have occurred because AndroidManifest.xml of some jar file or library might also be having the `android:label` attribute defined in its `<application>` tag which is causing merger conflic... | add uses-SDK tools in the Manifest file
```
<uses-sdk tools:replace="android:label" />
``` | 10,765 |
5,217,513 | i am looking to start learning. people have told me it is juts as capable. though i haven't really seen any good looking games available. some decent ones on pygame, but none really stand out.
i would like to know if python really is as capable as other languages.
EDIT: thanks guys, is python good for game developmen... | 2011/03/07 | [
"https://Stackoverflow.com/questions/5217513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647813/"
] | Short answer: Yes, it is.
But this heavily depends on your problem :) | This [article](http://www.python.org/doc/essays/comparisons.html) has very good comparison of Python with other languages like C++, Java etc. | 10,766 |
28,865,785 | I am using python to take a very large string (DNA sequences) and try to make a suffix tree out of it. My program gave a memory error after a long while of making nested objects, so I thought in order to increase performance, it might be useful to create buffers from the string instead of actually slicing the string. B... | 2015/03/04 | [
"https://Stackoverflow.com/questions/28865785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The result makes sense. The check inside your ifs is truey in both cases (probably because both BL1, BN1 exist).
What you need to do in your code is retrieve the selected index and then use it.
Give an id to your dropdown list:
```
<select id="dropdownList">
....
```
And then use it in your code to retrieve the se... | 1st: You are defining the variable *price* multiple times.
2nd: Your code checks for 'value' and of cause, it always has a value.
I guess, what you really want to check is, whether an option is selected or not annd then use its value.
```js
function BookingFare() {
var price = 0;
var BN1 = document.getElementByI... | 10,771 |
49,883,623 | Am trying to solve project euler question :
>
> 2520 is the smallest number that can be divided by each of the numbers
> from 1 to 10 without any remainder. What is the smallest positive
> number that is evenly divisible by all of the numbers from 1 to 20?
>
>
>
I've come up with the python solution below, but ... | 2018/04/17 | [
"https://Stackoverflow.com/questions/49883623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5126615/"
] | You can use a generator expression and the all function:
```
def smallest_m():
start = 1
while True:
if all(start % i == 0 for i in range(2, 20+1)):
print(start)
break
else:
start+=1
smallest_m()
``` | Try this
```
n = 2520
result = True
for i in range(1, 11):
if (n % i != 0):
result = False
print(result)
``` | 10,773 |
21,735,023 | I am a python newb so please forgive me. I have searched on Google and SA but couldn't find anything. Anyway, I am using the python library [Wordpress XMLRPC](http://python-wordpress-xmlrpc.readthedocs.org/en/latest/overview.html).
`myblog`, `myusername`, and `mypassword` are just placeholders to hide my real website... | 2014/02/12 | [
"https://Stackoverflow.com/questions/21735023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3302735/"
] | Variant 3 is ok (but I'd rather use a loop instead of hard-coded options). Your mistake is that you compare 'option1', 'option2' and so one when your real values are '1', '2', '3'. Also as @ElefantPhace said, don't forget about spaces before **selected**, or you'll get invalid html instead. So it would be this:
```
<s... | Here is all three of your variants, tested and working as expected. They are all basically the same, you were just using the wrong variable names, and different ones from example to example
1)
```
<?php
$opt= array('1' => 'opt1', '2' => 'opt2', '3' => 'opt3') ;
echo '<select name="up_opt">';
foreach ($opt... | 10,776 |
15,260,558 | Here is my code to run the server:
```
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
#....
PORT = 8089
httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler)
httpd.allow_reuse_address = True
print "Serving forever at port", PORT
try:
httpd.serve_forever()
except:
print "Closin... | 2013/03/06 | [
"https://Stackoverflow.com/questions/15260558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] | It is because TCP [TIME\_WAIT](http://dev.fyicenter.com/Interview-Questions/Socket-4/Explain_the_TIME_WAIT_state_.html).
[Somebody discovered this exact problem.](http://brokenbad.com/2012/01/address-reuse-in-pythons-socketserver/)
>
> However, if I try to stop and start the server again to test any modifications, I... | It is because you have to set SO\_REUSEADDRESS *before* you bind the socket. As you are creating and binding the socket all in one step and then setting it, it is already too late. | 10,777 |
5,988,617 | According to the python doc, vertical bars literal are used as an 'or' operator. It matches A|B,where A and B can be arbitrary REs.
For example, if the regular expression is as following:
ABC|DEF,it matches strings like these:
"ABC", "DEF"
But what if I want to match strings as following:
"ABCF", "ADEF"
Perhaps wh... | 2011/05/13 | [
"https://Stackoverflow.com/questions/5988617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/166482/"
] | These will work:
```
A(BC|DE)F
A(?:BC|DE)F
```
The difference is the number of groups generated: 1 with the first, 0 with the second.
Yours will match either `ABC` or `DEF`, with 2 groups, one containing nothing and the other containing the matched fragment (`BC` or `DE`). | The only difference between parentheses in Python regexps (and perl-compatible regexps in general), and parentheses in formal regular expressions, is that in Python, parens store their result. Everything matched by a regular expression inside parentheses is stored as a "submatch" or "group" that you can access using th... | 10,783 |
8,340,372 | >
> **Note:** this question is tagged both **language-agnostic** and **python** as my primary concern is finding out the algorithm to implement the solution to the problem, but information on how to implement it *efficiently* (=executing fast!) in python are a plus.
>
>
>
**Rules of the game:**
* Imagine two team... | 2011/12/01 | [
"https://Stackoverflow.com/questions/8340372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] | If I understand correctly, the problem of finding an optimal strategy for A once you know the positions for B is the same as finding a [maximum matching](http://en.wikipedia.org/wiki/Matching_%28graph_theory%29) in a bipartite graph.
The first set of vertices represent the A agents, the second set of vertices represen... | This is not really a question of programming as much as it is a game theory question. What follows is a sketch of a game-theoretic analysis of the problem.
We have a game of two players (A and B). A two-player game is always a zero-sum game, i.e. the gain of one player is loss for the other. Even if game payoffs are n... | 10,784 |
53,557,240 | I have an input, which is a word.
if my input contains `python`, print `True`. if not, print `False`.
for example:
if the input is `puytrmhqoln` print `True`(because it contains python's letter, however, there is some letter between `python`)
if the input is `pythno` print `False` (because in types o after n) | 2018/11/30 | [
"https://Stackoverflow.com/questions/53557240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10688308/"
] | I found the answer.
```
import sys
inputs = sys.stdin.readline().strip()
word = "python"
for i in range(len(inputs)):
if word == "": break
if inputs[i] == word[0]:
word = word[1:]
if word == "":
print("YES")
else:
print("NO")
```
it works for words like `hello` with double letter, also `pyth... | Iterate over each character of your string. And see whether the current character is identical to the currently next one in your string you are looking for:
```
strg = "pythrno"
lookfor = "python"
longest_substr = ""
index = 0
max_index = len(lookfor)
for c in strg:
if c == lookfor[index] and index < max_index:
... | 10,790 |
52,911,232 | I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error:
```
KeyError: 'PROJ_LIB'
```
After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as ... | 2018/10/21 | [
"https://Stackoverflow.com/questions/52911232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10534668/"
] | Need to set the PROJ\_LIB environment variable either before starting your notebook or in python with `os.environ['PROJ_LIB'] = '<path_to_anaconda>/share/proj'`
Ref. [Basemap import error in PyCharm —— KeyError: 'PROJ\_LIB'](https://stackoverflow.com/questions/52295117/basemap-import-error-in-pycharm-keyerror-proj-lib... | The problem occurs as the file location of "epsg" and PROJ\_LIB has been changed for recent versions of python, but somehow they forgot to update the **init**.py for Basemap. If you have installed python using anaconda, this is a possible location for your espg file:
`C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\... | 10,792 |
67,439,037 | Code to extract sequences
```
from Bio import SeqIO
def get_cds_feature_with_qualifier_value(seq_record, name, value):
for feature in genome_record.features:
if feature.type == "CDS" and value in feature.qualifiers.get(name, []):
return feature
return None
genome_record = SeqIO.read("470.8... | 2021/05/07 | [
"https://Stackoverflow.com/questions/67439037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13965256/"
] | You can resolve the inline execution error by changing `scriptTag.innerHTML = scriptText;` to `scriptTag.src = chrome.runtime.getURL(filePath);`, no need to fetch the script. Manifest v3 seems to only allow injecting static scripts into the page context.
If you want to run dynamically sourced scripts I think this can ... | Download the script files and put it on your project to make it local. It solved my content security policy problem. | 10,801 |
20,564,010 | I am calling a python script from a ruby program as:
```
sku = ["VLJAI20225", "VJLS1234"]
qty = ["3", "7"]
system "python2 /home/nish/stuff/repos/Untitled/voylla_staging_changes/app/models/ReviseItem.py #{sku} #{qtys}"
```
But I'd like to access the array elements in the python script.
```
print sys.argv[1]
#... | 2013/12/13 | [
"https://Stackoverflow.com/questions/20564010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2388940/"
] | Not a python specialist, but a quick fix would be to use json:
```
system "python2 /home/nish/stuff/repos/Untitled/voylla_staging_changes/app/models/ReviseItem.py #{sku.to_json} #{qtys.to_json}"
```
Then parse in your python script. | ```
"python2 /home/nish/stuff/repos/Untitled/voylla_staging_changes/app/models/ReviseItem.py \'#{sku}\' \'#{qtys}\'"
```
Maybe something like this? | 10,802 |
66,297,277 | I'm trying to embed python code in a C++ application. Problem is that if I use OpenCV functions in the C++ code and also in python function I am embedding there is memory corruption. Simply commenting all the opencv functions from the code below solve the problem.
One thing is that my OpenCV for c++ is 4.5.0 (dinamical... | 2021/02/20 | [
"https://Stackoverflow.com/questions/66297277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4267439/"
] | It seems a linking problem.
Python uses "dlopen" to dynamically load libraries, try changing the [flags](https://manpages.debian.org/buster/manpages-dev/dlopen.3.en.html) that are passed to this function. For example, using RTLD\_DEEPBIND you can specify to prefer the symbols contained by the loaded objects (instead o... | I think your problem is that python uses binding for c++ functions, and as you mention you are using different opencv versions for opencv c++ and python. Refer to <https://docs.opencv.org/3.4/da/d49/tuy_bindings_basics.html> for more information about python bindings. One solution will be to use already bonded function... | 10,805 |
67,094,562 | My dataset is a .txt file separated by colons (:). One of the columns contains a date *AND* time, the date is separated by backslash (/) which is fine. However, the time is separated by colons (:) just like the rest of the data which throws off my method for cleaning the data.
Example of a couple of lines of the datas... | 2021/04/14 | [
"https://Stackoverflow.com/questions/67094562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12326879/"
] | You cannot assign to arrays. You should use [`strcpy()`](https://man7.org/linux/man-pages/man3/strcpy.3.html) to copy C-style strings.
```
strcpy(dstPath, getenv("APPDATA"));
strcat(dstPath, p.filename().string().c_str());
```
Or the concatination can be done in one line via [`snprintf()`](https://man7.org/linux/man... | You are trying to use strcat to concatenate two strings and store the result in another one, but it does not work that way. The call `strcat (str1, str2)` adds the content of `str2` at the end of `str1`. It also returns a pointer to `str1` but I don't normally use it.
What you are trying to do should be done in three ... | 10,806 |
65,974,443 | When I compile `graalpython -m ginstall install pandas` or `graalpython -m ginstall install bumpy`
I got the following error, please comment how to fix the error. Thank you.
```
line 54, in __init__
File "number.c", line 284, in array_power
File "ufunc_object.c", line 4688, in ufunc_generic_call
File "ufunc_obje... | 2021/01/31 | [
"https://Stackoverflow.com/questions/65974443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5329711/"
] | I'm seeing a couple steps missing.
1. You shouldn't be installing chromedriver from brew, you can use the "webdrivers" gem to handle that. The gem will install drivers in the `~/.webdrivers` directory by default.
2. When running integration tests, you'll need to set the proper driver for Capybara. <https://github.com/... | Very stupid and non-obvious issue - the gems need to be in the `test` group ♂️:
```
group :test do
gem 'capybara'
gem 'webdrivers'
end
``` | 10,808 |
41,175,862 | I'm using Connector/Python to insert many rows into a temp table in mysql. The rows are all in a list-of-lists. I perform the insertion like this:
```
cursor = connection.cursor();
batch = [[1, 'foo', 'bar'],[2, 'xyz', 'baz']]
cursor.executemany('INSERT INTO temp VALUES(?, ?, ?)', batch)
connection.commit()
```
I no... | 2016/12/16 | [
"https://Stackoverflow.com/questions/41175862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2627992/"
] | Answering so other people won't go through the debugging I had to!
I wrote the query modeling it on other queries in our code that used prepared statements and used '?' to indicate parameters. But you *can't do that* for executemany()! It *must* use '%s'. Changing to the following:
```
cursor.executemany('INSERT INTO... | Try turn this command on:
cursor.fast\_executemany = True
Otherwise executemany acts just like multiple execute | 10,809 |
35,162,989 | I am learning python and need some help with lists and printing of the same.
List would end up looking list this:
```
mylist = ["a", "d", "c", "g", "g", "g", "a", "b", "n", "g", "a", "s", "t", "z", "a"]
```
I've used Counter(i think lol)
```
class item_print(Counter):
def __str__(self):
return '\n'.... | 2016/02/02 | [
"https://Stackoverflow.com/questions/35162989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5699265/"
] | Three problems.
First this needs to be put in a directive so you are assured the element(s) exist(s) when the code is run
Next...the event is outside of angular context . Whenever code outside of angular updates scope you need to tell angular to update view
Last ... `angular.element` doesn't accept class selectors ... | You are updating scope variable angular, out of its context. Angular doesn't run the digest cycle for those kind of updation. In this case you are updating scope variables from custom events, which doesn't intimate Angular digest system something has udpated on UI, resultant the digest cycle doesn't get fired.
You ne... | 10,812 |
55,738,296 | A call to [`functools.reduce`](https://docs.python.org/3/library/functools.html#functools.reduce) returns only the final result:
```
>>> from functools import reduce
>>> a = [1, 2, 3, 4, 5]
>>> f = lambda x, y: x + y
>>> reduce(f, a)
15
```
Instead of writing a loop myself, does a function exist which returns the in... | 2019/04/18 | [
"https://Stackoverflow.com/questions/55738296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1621041/"
] | You can use [`itertools.accumulate()`](https://docs.python.org/3/library/itertools.html#itertools.accumulate):
```
>>> from itertools import accumulate
>>> list(accumulate([1, 2, 3, 4, 5], lambda x, y: x+y))[1:]
[3, 6, 10, 15]
```
Note that the order of parameters is switched relative to `functools.reduce()`.
Also,... | ```
import numpy as np
x=[1, 2, 3, 4, 5]
y=np.cumsum(x) # gets you the cumulative sum
y=list(y[1:]) # remove the first number
print(y)
#[3, 6, 10, 15]
``` | 10,813 |
53,129,790 | I'm using Django with Postgres.
On a page I can show a list of featured items, let's say 10.
1. If in the database I have more featured items than 10, I want to get them random/(better rotate).
2. If the number of featured item is lower than 10, get all featured item and add to the list until 10 non-featured items.
... | 2018/11/03 | [
"https://Stackoverflow.com/questions/53129790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3541631/"
] | you may use the `whereHas` keyword in laravel:
```
public function search(Request $request) {
return Product::with('categories')
->whereHas('categories', function ($query) use ($request){
$query->where('category_id', $request->category_id);
})->get();
}
```
Here is the [docs](https://laravel.... | You can search it in following way:
```
public function search(Request $request) {
return Product::with('categories')
->whereHas('categories', function ($q) use (request) {
$q->where('id', $request->category_id);
});
}
``` | 10,814 |
37,530,804 | I'm new to MPI, but I have been trying to use it on a cluster with OpenMPI. I'm having the following problem:
```
$ python -c "from mpi4py import MPI"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: libmpi.so.1: cannot open shared object file: No such file or directory
```
I've... | 2016/05/30 | [
"https://Stackoverflow.com/questions/37530804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6332838/"
] | Even adding to LD\_LIBRARY\_PATH did not work for me. I had to uninstall mpi4py, then install it manually with my mpicc path according to the instructions here - <https://mpi4py.readthedocs.io/en/stable/install.html> (using distutils section) | I solve this problem by
```bash
pip uninstall mpi4py
conda install mpi4py
``` | 10,815 |
44,132,619 | I used the `pyodbc` and `pypyodbc` python package to connect to SQL server.
Drivers used anyone of these `['SQL Server', 'SQL Server Native Client 10.0', 'ODBC Driver 11 for SQL Server', 'ODBC Driver 13 for SQL Server']`.
connection string :
```
connection = pyodbc.connect('DRIVER={SQL Server};'
'Server=aaa.database... | 2017/05/23 | [
"https://Stackoverflow.com/questions/44132619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5602871/"
] | The problem is not driver issue, you can see the error message is `DatabaseError: Login failed for user`, it means this problem occurs if the user tries to log in with credentials that cannot be validated. I suspect you are login with your windows Authentication, if so, use `Trusted_Connection=yes` instead:
```
connec... | I think problem because of driver definition in your connection string. You may try with below.
```
connection = pyodbc.connect('DRIVER={SQL Server Native Client 10.0}; Server=aaa.database.windows.net; DATABASE=DB_NAME; UID=User_name; PWD=password')
``` | 10,816 |
12,700,194 | I've installed git-core (+svn) on my Mac from MacPorts. This has given me:
```
git-core @1.7.12.2_0+credential_osxkeychain+doc+pcre+python27+svn
subversion @1.7.6_2
```
I'm attempting to call something like the following:
```
git svn clone http://my.svn.com/svn/area/subarea/project -s
```
The output looks someth... | 2012/10/03 | [
"https://Stackoverflow.com/questions/12700194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1637252/"
] | Add this setting to your `~/.subversion/servers` file:
```
[global]
http-bulk-updates=on
```
I had this issue on Linux, and saw the above workaround on [this thread](http://mail-archives.apache.org/mod_mbox/subversion-users/201307.mbox/%3C51D79BDD.5020106@wandisco.com%3E). I **think** I ran into this because I force... | <http://bugs.debian.org/534763> suggests it is a bug in libsvn-perl package, try upgrading that | 10,822 |
73,629,234 | Simplest way to explain will be I have this code,
```
Str = 'Floor_Live_Patterened_SpanPairs_1: [[-3, 0, 0, 5.5], [-3, 5.5, 0, 9.5]]Floor_Live_Patterened_SpanPairs_2: [[-3, 0, 0, 5.5], [-3, 9.5, 0, 13.5]]Floor_Live_Patterened_SpanPairs_3: [[-3, 5.5, 0, 9.5], [-3, 9.5, 0, 13.5]]'
from re import findall
findall ('[^\]\... | 2022/09/07 | [
"https://Stackoverflow.com/questions/73629234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16966180/"
] | You can simplify and start to make the code reusable by putting it into a function. Also, it's a good idea to make it pythonic and remove all the `;` that will only serve to confuse the reader as to what language they're looking at.
```
def login(name, age):
password = input('Enter your desired password: ')
pr... | I got this working.
```py
def login():
counter = 1;
x = 5;
for i in range(5):
print(' Login ');
login = input('Enter password: ');
if login == password:
counter -= 1
print(' Welcome ');
print('Account Information: ');
print('Name: ',n... | 10,825 |
53,810,242 | i have two functions in python
```
class JENKINS_JOB_INFO():
def __init__(self):
parser = argparse.ArgumentParser(description='xxxx. e.g., script.py -j jenkins_url -u user -a api')
parser.add_argument('-j', '--address', dest='address', default="", required=True, action="store")
parser.add_a... | 2018/12/17 | [
"https://Stackoverflow.com/questions/53810242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5871199/"
] | Just write `params.params` instead of `params`.
The way you do it is extremely confusing because in `get_jenkins_josn_data`, `self` will be the `params` and `params` will be the `base_url`. I would advise you no to do that in the future. If you want to send some parameters to the function, send the minimal amount of ... | So your solution is a bit confusing. You shouldn't pass the self to the `get_jenkins_json_data` method. The python will do that for you automatically. You should check out the data model for how [instance methods](https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy) work. I would refactor you... | 10,826 |
66,038,159 | To improve performance on project of mine, i've coded a function using tf.function to replace a function witch does not use tf. The result is that plain python code runs much (100x faster) than the tf.funtion when GPU is enabled. When running on CPU, TF is still slower, but only 10x slower. Am i missing something?
```... | 2021/02/04 | [
"https://Stackoverflow.com/questions/66038159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15140159/"
] | When you use some tf functions with GPU enabled, it does a callback and transfers data to the GPU. In some cases, this overhead is not worth it. When running on the CPU, this overhead decreases, but it's still slower than pure python code.
Tensorflow is faster when you do heavy calculations, and that's what Tensorflow... | The slow part (while loop) is still in python and simple functions like this are pretty fast. The linear overhead of switching from python to tf each time is certainly bigger than anything you could ever gain on such a small function. For more complex operations, this might be very different. In this case tf is simply ... | 10,828 |
13,216,520 | Walking through matplotlib's animation example on my Mac OSX machine - <http://matplotlib.org/examples/animation/simple_anim.html> - I am getting this error:-
```
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/animation.py", line 248, in _blit_clear
a.figure.canvas.r... | 2012/11/04 | [
"https://Stackoverflow.com/questions/13216520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/482506/"
] | You can avoid the problem by switching to a different backend:
```
import matplotlib
matplotlib.use('TkAgg')
``` | Looks like it's a known (and unresolved at this time of writing) issue - <https://github.com/matplotlib/matplotlib/issues/531> | 10,829 |
34,347,401 | I have a Pelican blog where I write the posts in Markdown. I want each article to link to the previous and next article in the sequence, and to one random article.
All the articles are generated with a python script, resulting in a folder of markdown files called /content/. Here the files are like:
* article-slug1.m... | 2015/12/18 | [
"https://Stackoverflow.com/questions/34347401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4108771/"
] | There is the [Pelican Neighbours](https://github.com/getpelican/pelican-plugins/tree/master/neighbors) plug-in that might do what you want. You'll have to active the plug-in and update your template to get it to work.
* Adding plug-ins: [Pelican-Plugins' Readme](https://github.com/getpelican/pelican-plugins/blob/maste... | I am not sure about the random article, but for next and previous, there is a Pelican plugin called [neighbor articles](https://github.com/getpelican/pelican-plugins/tree/master/neighbors). | 10,835 |
67,455,130 | I am new to python and trying to create a small atm like project using classes. I wanna have the user ability to input the amount they want to withdraw and if the amount exceeds the current balance, it prints out that you cannot have negative balance and asks for the input again.
```
class account:
def __init__(s... | 2021/05/09 | [
"https://Stackoverflow.com/questions/67455130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11606914/"
] | Via `np.select`
```
condlist = [
(df.Email_x.isna()) & (~df.Email_y.isna()), # 1st column NAN but 2nd is not
(df.Email_y.isna()) & (~df.Email_x.isna()), # 2nd column NAN but 1st is not
(~df.Email_x.isna()) & (~df.Email_y.isna()) # both is not NAN
]
choicelist = [
df.Email_y,
df.Email_x,
df.Em... | You can use [`.mask()`](https://pandas.pydata.org/docs/reference/api/pandas.Series.mask.html), as follows:
```
df['email'] = df['Email_x'].mask(df['Email_x'].isna(), df['Email_y'])
```
It will retain the value of `df['Email_x']` if the condition is false (i.e. not `NaN`) and replace with value of `df['Email_y']` if ... | 10,838 |
24,468,944 | I am trying to write a python program that asks the user to enter an existing text file's name and then display the first 5 lines of the text file or the complete file if it is 5 lines or less. This is what I have programmed so far:
```
def main():
# Ask user for the file name they wish to view
filename = inpu... | 2014/06/28 | [
"https://Stackoverflow.com/questions/24468944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3786320/"
] | Just `print()`, by itself, will only print a newline, nothing else. You need to pass the `line` variable to `print()`:
```
print(line)
```
The `line` string will have a newline at the end, you probably want to ask `print` not to add another:
```
print(line, end='')
```
or you can remove the newline:
```
print(li... | In order to print first 5 or less lines. You can try the following code:
```
filename = input('Enter the file name that you wish to view: ')
from itertools import islice
with open(filename) as myfile:
head = list(islice(myfile,5))
print head
```
Hope the above code will satisfy your query.
Thank you. | 10,840 |
12,231,733 | I have a python script that I want to only allow to be running once on a machine. I want it to print something like "Error, already running" if it is already running, whether its running in the background or in a different ssh session. How would I do this? Here is my script.
```
import urllib, urllib2, sys
num = sys.a... | 2012/09/01 | [
"https://Stackoverflow.com/questions/12231733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601509/"
] | 1. You can implement a lock on the file.
2. Create a temp file at the start of the execution and check if that file is present before running the script.
Refer to this post for answer- [Check to see if python script is running](https://stackoverflow.com/questions/788411/check-to-see-if-python-script-is-running) | You could lock an existing file using e.g. [flock](http://docs.python.org/library/fcntl.html#fcntl.flock) at start of your script. Then, if the same script is run twice, the latest started would block. See also [this question](https://stackoverflow.com/questions/3918385/flock-question). | 10,843 |
60,682,568 | I've been trying to write code which seperates the age (digits) from name (alphabets) and then compares it to a pre-defined list and if it doesn't match with the list then it sends out an error but instead of getting (for example) alex:error, i'm getting a:error l:error e:error x:error, that is it's splitting the words... | 2020/03/14 | [
"https://Stackoverflow.com/questions/60682568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12387627/"
] | You need to change your names2 variable as its a string type. You need to conver it to a list and append each name to it after str.translate(). Here is the modified code.
```
names2=[name.translate(removed_digits) for name in names1]
```
I hope your problem will solved. | You can try something like this:
```
names=input("Data:")
names1=names.strip().split(',') #split names
for name in names1:
names2 = name.strip().split(' ') #split name and digit
if names2[0] not in lst1:
print(f"{name}:Not Matching to our database.")
``` | 10,846 |
62,789,471 | I'm running python in docker and run across the `ModuleNotFoundError: No module named 'flask'` error message. any thoughts what am I missing in the Dockerfile or requirements ?
```sh
FROM python:3.7.2-alpine
RUN pip install --upgrade pip
RUN apk update && \
apk add --virtual build-deps gcc python-dev
RUN ad... | 2020/07/08 | [
"https://Stackoverflow.com/questions/62789471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13115677/"
] | One way using `itertools.starmap`, `islice` and `operator.sub`:
```
from operator import sub
from itertools import starmap, islice
l = list(range(1, 10000000))
[l[0], *starmap(sub, zip(islice(l, 1, None), l))]
```
Output:
```
[1, 1, 1, ..., 1]
```
---
Benchmark:
```
l = list(range(1, 100000000))
# OP's metho... | You could use [numpy.diff](https://numpy.org/doc/stable/reference/generated/numpy.diff.html), For example:
```py
import numpy as np
a = [1, 2, 3, 4, 5]
npa = np.array(a)
a_diff = np.diff(npa)
``` | 10,847 |
69,788,691 | I am new here. I am a begginer with python so I am trying to write a code that allows me to remove the link break of a list in python.
I have the following list (which is more extense), but I will share a part of it.
```
info = ['COLOMBIA Y LA \nNUEVA REVOLUCIÓN \nINDUSTRIAL\nPropuestas del Foco \nde Tecnologías Con... | 2021/10/31 | [
"https://Stackoverflow.com/questions/69788691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17293731/"
] | You can use list comprehension:
```
info = [i.replace("\n", "") for i in info]
``` | You can use a generator comprehension and then join each entries of the list by a separator character, `sep`, I choose an empty string.
```
sep = '' # choose the separator character
text = sep.join(s.replace('\n', '') for s in info)
``` | 10,849 |
31,972,419 | I have a file whose contents are
```
{'FileID': 'a3333.txt','Timestamp': '2014-12-05T02:01:28.271Z','SuccessList':'a,b,c,d,e'}
```
When I read the file using python, I get the string as
```
"{'FileID': 'a3333.txt','Timestamp': '2014-12-05T02:01:28.271Z','SuccessList':'a,b,c,d,e'}"
```
I want the double quotes t... | 2015/08/12 | [
"https://Stackoverflow.com/questions/31972419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1642114/"
] | If the files as stored are intended to be JSON then they are invalid. The JSON format doesn't allow the use of single quotes to delimit strings. **Assuming you have no single quotes within the key/value strings** themselves, you can replace the single quotes with double quotes and then read in using the JSON module:
`... | If your string actually contains double quotes (which it might not, as they could just be part of the printed representation), you could get rid of them with a slice, e.g.,
```
>>> hello = '"hello more stuff things"'
>>> hello
'"hello more stuff things"'
>>> hello[1:-1]
'hello more stuff things'
```
Note in this cas... | 10,850 |
10,436,130 | How should this python be expressed
```
gl_enums = ... # map from name to values for opengl enums
# use with gl_enums["enum name"]
```
in clojure? This works, but is it right?
```
(def gl-enums ...) ; map from name to values for opengl enums
(defn gl-enum [k] (or (gl-enums k) (throw (SomeException.))))
; use with (... | 2012/05/03 | [
"https://Stackoverflow.com/questions/10436130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322866/"
] | Your original example is OK. Two approaches you are also likely to come across:
```
;; not very idiomatic
(defn example
[m]
(if (contains? m :name)
(:name m)
(throw (IllegalArgumentException. (format "key %s is missing" :name)))))
;; idiomatic
(defn example
[m]
(if-let [v (:name m)]
v
(throw (... | Just use a regular hashmap:
```
(def gl-enums {:name1 "value1", :name2 "value2",
:name3 "value3", ...})
```
if you don't want to provide keywords (like `:keyword`) but prefer strings, you'll need to use `(get gl-enums str)` in `gl-enum` | 10,853 |
43,684,760 | I have very basic python knowledge. This is my code so far:
when i run this code the error `UnboundLocalError: local variable 'response' referenced before assignment on line 7` displays. I am trying to create a function that compares the response input to two lists and if that input is found true or false is assigned ... | 2017/04/28 | [
"https://Stackoverflow.com/questions/43684760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7937653/"
] | You are complicating things a lot here, but that is understandable if you are new to programming or python.
To put you on the right track, this is a better way to attack the problem:
```
valid_responses = ['a', 'b']
response = input("chose a or b: ").lower().strip()
if response in valid_responses:
print("Valid re... | Instead of enumerating a list of exact possible answers, you could instead match against patterns of possible answers. Here is one way to do that, case insensitively:
```
import re
known_fruits = ['apple', 'orange']
response = str(input("What would you like to eat? (Answer " + ' or '.join(known_fruits) + '): '))
def... | 10,854 |
15,854,916 | i've a problem, like a title.
I've tried to install smart\_selects in my project Django, but does not work.
I followed the readme in <https://github.com/digi604/django-smart-selects>... but the error is:
>
> No module named admin\_static
> Request Method: GET
> Request URL: http://**\*.com/panel/schedevendorcomplet... | 2013/04/06 | [
"https://Stackoverflow.com/questions/15854916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2252933/"
] | Use Java's Calendar: (since my beloved Date is deprecated)
[Calendar API](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html)
Try something like:
```
Calendar c = Calendar.getInstance();
c.setTimeInMillis(1365228375*1000);
System.out.print(c.toString()); - just to demonstrate the API has lots of i... | Well, conversion from seconds to microseconds shouldn't be too difficult;
```
echo time() * 1000;
```
If you need the time stamp to be **acurate** in milliseconds, look at [`microtime()`](http://www.php.net/manual/en/function.microtime.php) however, this function does *not* return an integer so you'll have to do som... | 10,855 |
27,740,044 | I am installing cffi package for cryptography and Jasmin installation.
I did some research before posting question, so I found following option but which is seems not working:
System
------
>
> Mac OSx 10.9.5
>
>
> python2.7
>
>
>
Error
-----
```
c/_cffi_backend.c:13:10: fatal error: 'ffi.h' file not found
... | 2015/01/02 | [
"https://Stackoverflow.com/questions/27740044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694106/"
] | In your terminal try and run:
```
xcode-select --install
```
After that try installing the package again.
By default, XCode installs itself as the IDE and does not set up the environment for the use by command line tools; for example, the `/usr/include` folder will be missing.
Running the above command will ins... | Install CLI development toolchain with
```
$ xcode-select --install
```
If you have a broken pkg-config, unlink it with following command as mentioned in comments.
```
$ brew unlink pkg-config
```
Install libffi package
```
$ brew install pkg-config libffi
```
and then install cffi
```
$ pip install cffi
```... | 10,857 |
47,275,478 | I'm using azure service bus queues in my application and here my question is, is there a way how to check the message queue is empty so that I can shutdown my containers and vms to save cost. If there is way to get that please let me know, preferably in python.
Thanks | 2017/11/13 | [
"https://Stackoverflow.com/questions/47275478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6918471/"
] | For this, you can use [`Azure Service Bus Python SDK`](https://pypi.python.org/pypi/azure-servicebus). What you would need to do is get the properties of a queue using `get_queue` method that will return an object of type `Queue`. This object exposes the total number of messages through `message_count` property. Please... | You could check the length of the messages returned from [peek\_messages](https://azuresdkdocs.blob.core.windows.net/$web/python/azure-servicebus/latest/azure.servicebus.html?highlight=peek_messages#azure.servicebus.ServiceBusReceiver.peek_messages) method on the class `azure.servicebus.ServiceBusReceiver`
```
with se... | 10,860 |
40,130,468 | I am using Alamofire for the HTTP networking in my app. But in my api which is written in python have an header key for getting request, if there is a key then only give response. Now I want to use that header key in my iOS app with Alamofire, I am not getting it how to implement. Below is my code of normal without any... | 2016/10/19 | [
"https://Stackoverflow.com/questions/40130468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5088930/"
] | This should work
```
let headers = [
"appkey": "test"
]
Alamofire.request(.GET, "http://name/user_data/\(userName)@someURL.com", parameters: nil, encoding: .URL, headers: headers).responseJSON {
response in
//handle response
}
``` | ```
let headers: HTTPHeaders = [
"Accept": "application/json",
"appkey": "test"
]
Alamofire.request("http://name/user_data/\(userName)@someURL.com", headers: headers).responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.... | 10,861 |
49,997,303 | Write a program using Python 3.x
Write the scipt that will read "input.txt" and print the first 5 lines of the file input.txt that consists of the single odd number to stdout The file may contain lines having numeric and non numeric data your script should ignore all the lines that contain anything except single odd i... | 2018/04/24 | [
"https://Stackoverflow.com/questions/49997303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8064377/"
] | **Put your admin link like this :**
as `Admin` is not your default `controller` and you not set your route for admin
Put your `admin` link like this
```
<li class="nav-item">
<a class="nav-link" href="<?php echo base_url('admin/index'); ?>">Admin</a>
</li>
```
but if you want to do like this :
```
<li class="... | Please use parent construct and after you can do your way.
```
public function __construct() {
parent :: __construct();
$this->load->model(array('restaurants_m', 'categories_m', 'cities_m', 'customers_m', 'states_m', 'orders_m', 'delivery_boys_m'));
$this->load->library(array('ema... | 10,862 |
55,168,955 | On Mac OS 10.14 (Mojave) I used:
```
pip install -U pytest
```
to install pytest. I got a permission denied error trying to install the packages to `/Users/nagen/Library/Python/2.7`
I tried
```
sudo pip install -U pytest
```
This time it installed successfully
But, despite adding the full path, the terminal doe... | 2019/03/14 | [
"https://Stackoverflow.com/questions/55168955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11204687/"
] | I think the best option might be to use a python virtual env. <https://packaging.python.org/guides/installing-using-pip-and-virtualenv/> is a good starting point
```
> virtualenv env
> source env/bin/activate
> pip install pytest
> pytest
```
This will avoid pathing and permissions issues and keep your environment c... | I would **strongly** recommend using [homebrew](https://brew.sh/). This is the **best** dev tool there is for mac users and I never install things without it.
To install it run the following in terminal:
```
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
```
Now t... | 10,863 |
15,034,151 | I have a directory /a/b/c that has files and subdirectories.
I need to copy the /a/b/c/\* in the /x/y/z directory. What python methods can I use?
I tried `shutil.copytree("a/b/c", "/x/y/z")`, but python tries to create /x/y/z and raises an `error "Directory exists"`. | 2013/02/22 | [
"https://Stackoverflow.com/questions/15034151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260127/"
] | I found this code working which is part of the standard library:
```
from distutils.dir_util import copy_tree
# copy subdirectory example
from_directory = "/a/b/c"
to_directory = "/x/y/z"
copy_tree(from_directory, to_directory)
```
Reference:
* Python 2: <https://docs.python.org/2/distutils/apiref.html#distutils.... | You can also use glob2 to recursively collect all paths (using \*\* subfolders wildcard) and then use shutil.copyfile, saving the paths
glob2 link: <https://code.activestate.com/pypm/glob2/> | 10,864 |
59,296,151 | I'm writing a python script that uses a model to predict a large number of values by groupID, where **efficiency is important** (N on the order of 10^8). I initialize a results matrix and am trying to sequentially update a running sum of values in the results matrix.
Trying to be efficient, in my current method I use ... | 2019/12/12 | [
"https://Stackoverflow.com/questions/59296151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11918892/"
] | The problem is that your in your language dates use the slash separator, which makes Blazor think you're trying to access a different route.
Whenever sending dates as a URL parameter they need to be in invariant culture and use dashes.
```cs
NavigationManager.NavigateTo("routeTest/"+numberToSend+"/"+dateToSend.ToStr... | As you've identified, the DateTime in the URL is affecting the routing due to the slashes.
Send the `DateTime` in ISO8601 format `yyyy-MM-ddTHH:mm:ss`.
You could use:
```
dateToSend.ToString("s", System.Globalization.CultureInfo.InvariantCulture)
```
where the format specifier `s` is known as the [Sortable date/ti... | 10,870 |
62,061,258 | I am trying to create a view that handles the email confirmation but i keep on getting an error, your help is highly appreciated
My views.py
```
import re
from django.contrib.auth import login, logout, authenticate
from django.shortcuts import render, HttpResponseRedirect, Http404
# Create your views here.
from .for... | 2020/05/28 | [
"https://Stackoverflow.com/questions/62061258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13633361/"
] | Use [`justify`](https://stackoverflow.com/a/44559180/2901002) with `DataFrame` constructor:
```
arr = justify(data_df.to_numpy(), invalid_val=np.nan,axis=0)
df = pd.DataFrame(arr, columns=data_df.columns, index=data_df.index)
print(df)
8 16 20 24
0 4.0 0.0 1.0 6.0
0 7.0 2.0 5.0 8.0
0 NaN 3.0 NaN... | This is not that pretty - but with help of `numpy` you can fairly easy get a numpy array with your desired result.
```
import numpy
def shifted_column(values):
none_nan_values = values[ ~np.isnan(values) ]
nan_row = np.zeros(values.shape)
nan_row[:] = np.nan
nan_row[:none_nan_values.size] = none_nan_... | 10,872 |
3,387,663 | HI all
I am trying to use SWIG to export C++ code to Python.
The C sample I read on the web site does work but I have problem with C++ code.
Here are the lines I call
```
swig -c++ -python SWIG_TEST.i
g++ -c -fPIC SWIG_TEST.cpp SWIG_TEST_wrap.cxx -I/usr/include/python2.4/
gcc --shared SWIG_TEST.o SWIG_TEST_wrap.o -... | 2010/08/02 | [
"https://Stackoverflow.com/questions/3387663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245416/"
] | It looks like you aren't linking to the Python runtime library. Something like adding `-lpython24` to your gcc line. (I don't have a Linux system handy at the moment). | you might try building the shared library using `gcc`
```
g++ -shared SWIG_TEST.o SWIG_TEST_wrap.o -o _SWIG_TEST.so
```
rather than using `ld` directly. | 10,873 |
54,856,829 | In TensorFlow <2 the training function for a DDPG actor could be concisely implemented using `tf.keras.backend.function` as follows:
```
critic_output = self.critic([self.actor(state_input), state_input])
actor_updates = self.optimizer_actor.get_updates(params=self.actor.trainable_weights,
... | 2019/02/24 | [
"https://Stackoverflow.com/questions/54856829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3552418/"
] | I found two ways to solve it:
###Using data attribute
Get the max number of pages in the template, assign it to a data attribute, and access it in the scripts. Then check current page against total page numbers, and set disabled states to the load more button when it reaches the last page.
PHP/HTML:
```
<ul id="aja... | The problem appears to be an invalid query to that endpoint so the `success: function()` is never being run in this circumstance.
### Add to All API Errors
You could add the same functionality for all errors like this...
```
error: function(jqXHR, textStatus, errorThrown) {
loadMoreButton.remove();
...... | 10,875 |
43,819,092 | I have installed ngram using pip install ngram. While I am running the following code
```
from ngram import NGram
c=NGram.compare('cereal_crop','cereals')
print c
```
I get the error `ImportError: cannot import name NGram`
Screenshot for it: [](ht... | 2017/05/06 | [
"https://Stackoverflow.com/questions/43819092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4451870/"
] | Your Python script is named `ngram.py`, so it defines a module named `ngram`. When Python runs `from ngram import NGram`, Python ends up looking in your script for something named `NGram`, not in the `ngram` module you have installed.
Try changing the name of your script to something else, for example `ngram_test.py`. | try like this:
```
import ngram
c = ngram.NGram.compare('cereal_crop','cereals')
print c
``` | 10,876 |
45,006,190 | ConnectionRefusedError error showing when register user,
basic information added on database but password field was blank and other database fields submitted please find the following error and our class code,
**Class**
class ProfessionalRegistrationSerializer(serializers.HyperlinkedModelSerializer):
```
password =... | 2017/07/10 | [
"https://Stackoverflow.com/questions/45006190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7225424/"
] | I was getting the same error and it may be due to email verification. I add following code in my setting.py file and now authentication working perfectly
```
ACCOUNT_EMAIL_VERIFICATION = 'none'
ACCOUNT_AUTHENTICATION_METHOD = 'username'
ACCOUNT_EMAIL_REQUIRED = False
``` | You perform a call to a remote server that you can't reach / isn't configured / isn't running.
It's not an issue with Django or DRF. | 10,877 |
27,259,112 | I want to test uploaded python programs with the `unittest` module on a django based web site and give a useful feedback to the student. I created some helper function to get statistics (how many failures and errors) and messages.
```
def suite(*test_cases):
suites = [unittest.makeSuite(case) for case in test_cas... | 2014/12/02 | [
"https://Stackoverflow.com/questions/27259112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813946/"
] | If you have a `TestCase` like:
```
class ExampleTestCase(unittest.TestCase):
def test_example(self):
"""If this fails, it may not be your fault.
Try hacking the integer cache. Evil laugh."""
self.assertEqual(3, 4)
```
You can later, in your `testcase_statistics_and_messages` function, get... | Here is one possible solution - override the specific assertion methods that you're using (`assertEqual`, etc, hopefully not too many) and store the variables in a JSON string as message:
```
import json
import unittest
class ExampleTestCase(unittest.TestCase):
longMessage = False
def assertEqual(self, first... | 10,878 |
53,067,695 | I'm writing a function to find the percentage change using Numpy and function calls. So far what I got is:
```
def change(a,b):
answer = (np.subtract(a[b+1], a[b])) / a[b+1] * 100
return answer
print(change(a,0))
```
"a" is the array I have made and b will be the index/numbers I am trying to calculate.
For exa... | 2018/10/30 | [
"https://Stackoverflow.com/questions/53067695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10541940/"
] | The accepted answer is close but incorrect if you're trying to take % difference from left to right.
You should get the following percent difference:
`1,2,3,5,7` --> `100%, 50%, 66.66%, 40%`
check for yourself: <https://www.calculatorsoup.com/calculators/algebra/percent-change-calculator.php>
Going by what Josmoor9... | 1. Combine all your arrays.
2. Then make a data frame from them.
```
df = pd.df(data=array you made)
```
3. Use the `pct_change()` function on dataframe. It will calculate the % change for all rows in dataframe. | 10,879 |
28,323,435 | I'm trying to use [`logging`'s `SMTPHandler`](https://docs.python.org/3/library/logging.handlers.html#smtphandler). From Python 3.3 on, you can specify a `timeout` keyword argument. If you add that argument in older versions, it fails. To get around this, I used the following:
```
import sys
if sys.version_info >= (3... | 2015/02/04 | [
"https://Stackoverflow.com/questions/28323435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/810870/"
] | Rather than test for the version, use exception handling:
```
try:
smtp_handler = SMTPHandler(SMTP_SERVER, FROM_EMAIL, TO_EMAIL, SUBJECT, timeout=20.0)
except TypeError:
# Python < 3.3, no timeout parameter
smtp_handler = SMTPHandler(SMTP_SERVER, FROM_EMAIL, TO_EMAIL, SUBJECT)
```
Now you can conceivably... | Here is another slightly different approach:
```
from logging.handlers import SMTPHandler
import sys
if sys.version_info >= (3, 3):
# patch in timeout where available
from functools import partial
SMTPHandler = partial(SMTPHandler, timeout=20.0)
```
Now in the rest of the code you can just use:
```
smt... | 10,889 |
5,763,608 | I'm trying to start a script on bootup on a Ubuntu Server 10.10 machine.
The relevant parts of my rc.local look like this:
```
/usr/local/bin/python3.2 "/root/Advantage/main.py" >> /startuplogfile
exit 0
```
If I run ./rc.local from /etc everything works just fine and it writes the following into /startuplogfile:
... | 2011/04/23 | [
"https://Stackoverflow.com/questions/5763608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317163/"
] | You can't depend on `argv[0]` containing something specific. Sometimes you'll get the full path, sometimes only the program name, sometimes something else entirely.
It depends on how the code was invoked. | As you’ve noticed, `argv[0]` can (but doesn’t always) contain the full path of your executable. If you want the file name only, one solution is:
```
#include <libgen.h>
const char *proName = basename(argv[0]);
```
---
As noted by Mat, `argv[0]` is not always reliable — although it should usually be. It depends on ... | 10,892 |
6,730,735 | Last weekend (16. July 2011) our mercurial packages auto-updated to the newest 1.9 mercurial binaries using the mercurial-stable ppa on a ubuntu lucid.
Now pulling from repository over SSH no longer works.
Following error is displayed:
```
remote: Traceback (most recent call last):
remote: File "/usr/share/mercuria... | 2011/07/18 | [
"https://Stackoverflow.com/questions/6730735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/619789/"
] | Ok, found a (workaround) solution by editing a python script.
Edit the script /usr/share/mercurial-server/hg-ssh
At the end of the script replace the line:
```
dispatch.dispatch(['-R', repo, 'serve', '--stdio'])
```
with the line:
```
dispatch.dispatch(dispatch.request(['-R', repo, 'serve', '--stdio']))
```
Repl... | More recent versions of mercurial-server are updated to support the API changes, but **may require** the `refresh-auth` script to be rerun for installations being upgraded. | 10,893 |
56,145,426 | I ran `pip3 install detect-secrets`; but running `detect-secrets` then gives "Command not found".
I also tried variations, for example the switch `--user`; `sudo`; and even `pip` rather than `pip3`. Also with underscore in the name.
I further added all directories shown in `python3.6 -m site` to my `PATH` (Ubuntu 18... | 2019/05/15 | [
"https://Stackoverflow.com/questions/56145426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39242/"
] | You can use Treemap to contain the duplicity and total sum corresponding to your input String. Also using treemap, your output will be in sorted format if that you require.
```java
public static void main(String[] args) {
String[] names = {"a","b","a","a","c","b"};
Integer[] numbers = {5,2,3,1,2,1};
Map<String... | You can use Map interface.
Use your String array "names" as keys. Write a for loop for it and inside:
If your map contains the key, get the value and sum with the new value.
PS: Couldn't write code right now, I can update it later. | 10,894 |
32,342,761 | In my code pasted bellow (which is python 3 code) I expected the for loop to change the original objects (ie I expected NSTEPx to have been changed by the for loop). Since lists and arrays are mutable I should have edited the object by referring to it by the variable "data". However, after this code was run, and I call... | 2015/09/02 | [
"https://Stackoverflow.com/questions/32342761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5286344/"
] | In your loop, `data` refers to an array (some object). The object referred to is mutable. The variable `data` can be changed as well to refer to something else, but that won't change what's in `alldata` (values that refer to objects) or the variables whose contents you implicitly copied to construct `alldata`. Hence, a... | Python has **no** assignment! `data = value` is strictly a *binding* operation, not an assignment. This is really different then in eg C++
A Python variable is like a label, or a yellow sticky note: you can put it on *something* or move it to something else; it does not (**never**) change the *thing* (object) it is on... | 10,902 |
1,381,739 | First of all, thank you for taking the time to read this. I am new to developing applications for the Mac and I am having some problems. My application works fine, and that is not the focus of my question. Rather, I have a python program which essentially does this:
```
for i in values:
os.system(java program_and... | 2009/09/04 | [
"https://Stackoverflow.com/questions/1381739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Does running Java with headless mode = true fix it?
<http://zzamboni.org/brt/2007/12/07/disable-dock-icon-for-java-programs-in-mac-osx-howto/> | As far as I am aware there is no way to disable the annoying double Java bounce without making your Java application a first class citizen on Mac OS X (much like NetBeans, or Eclipse). As for making certain programs not show in the dock, there are .plist modifications that can be made so that the program does not show ... | 10,903 |
47,314,905 | I did import the module with a name, and import it again without a name and both seems to be working fine and gives the same class type.
```
>>> from collections import Counter as c
>>> c
<class 'collections.Counter'>
>>> from collections import Counter
>>> Counter
<class 'collections.Counter'>
```
How does that wo... | 2017/11/15 | [
"https://Stackoverflow.com/questions/47314905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3950422/"
] | Using python 2.7.13:
```
>>> from collections import Counter as c
>>> c
<class 'collections.Counter'>
>>> from collections import Counter
>>> Counter
<class 'collections.Counter'>
>>> id(c), id(Counter)
(140244739511392, 140244739511392)
>>> id(c) == id(Counter)
True
```
Yes, `c` and `Counter` are the same. Two vari... | As I remember , everything you define in python is an object belongs to a class. And yes if a variable object has assigned some value and if you create another variable with same value then python wont create a new reference for the second variable but it will use first variables reference for second variable as well. ... | 10,905 |
24,584,441 | I'm trying to execute an operation to each file found by find - with a specific file extension (wma). For example, in python, I would simply write the following script:
```
for file in os.listdir('.'):
if file.endswith('wma'):
name = file[:-4]
command = "ffmpeg -i '{0}.wma' '{0}.mp3'".format(name)
... | 2014/07/05 | [
"https://Stackoverflow.com/questions/24584441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2014591/"
] | Try to use setMainView method
```
class IndexController extends ControllerBase
{
public function onConstruct(){
}
public function indexAction()
{
return $this->view->setMainView("login/login");
}
}
```
setMainView method use to set the default view. Just put the view name... | Remove the `return` keyword. I believe it is fetching the view you want and then returning it into the base template. | 10,907 |
22,949,270 | Is there a way how to switch off (and on later) this check at runtime?
The motivation is that I need to use third party libraries which do not care about tabs and spaces mixing and thus running my code with [`-t` switch](https://docs.python.org/2/using/cmdline.html#cmdoption-t "switch") issues warnings.
(I hope that ... | 2014/04/08 | [
"https://Stackoverflow.com/questions/22949270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/542196/"
] | Taking a straight percentage of views doesn't give an accurate representation of the item's popularity, either. Although 9 likes out of 18 is "stronger" than 9 likes out of 500, the fact that one video got 500 views and the other got only 18 is a much stronger indication of the video's popularity.
A video that gets a ... | A simple approach would be to come up with a suitable scale factor for each average - and then sum the "weights". The difficult part would be tweaking the scale factors to produce the desired ordering.
From your example data, a starting point might be something like:
```
Weighted Rating = (AV * (1 / 50)) + (AL * 3) -... | 10,910 |
73,668,351 | I have connected an Arduino to a raspberry pi so that a specific event is triggered when I send a signal(in this case a number). When I send a number with the script and tell it just to print in serial monitor it works, when I try and just have it run the motors on start it works fine, however when combining the two: h... | 2022/09/09 | [
"https://Stackoverflow.com/questions/73668351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12527861/"
] | Since you're using func `firstIndex` of an array in this `func indexOfItem(_ item: Item) -> Int?` therefore the `Item` has to be a concrete object (behind the scene of `firstIndex` func is comparing each element of an array and print out the index of the element).
There are 2 ways to do this
* First is using associat... | Finally find simple enough solution:
То make protocol generic with associated type and constraint
this type to Equatable.
```
public protocol Container {
associatedtype EquatableItem: Item, Equatable
var items: [EquatableItem] {get}
}
public protocol Item {
var name: String {get}
}
public extension Cont... | 10,916 |
59,796,680 | I recently moved to a place with terrible internet connection. Ever since then I have been having huge issues getting my programming environments set up with all the tools I need - you don't realize how many things you need to download until each one of those things takes over a day.
For this post I would like to try t... | 2020/01/18 | [
"https://Stackoverflow.com/questions/59796680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6036156/"
] | Use option `--timeout <sec>` to set socket time out.
Also, as @Iain Shelvington mentioned, `timeout = <sec>` in [pip configuration](https://pip.pypa.io/en/stable/user_guide/#configuration) will also work.
*TIP: Every time you want to know something (maybe an option) about a command (tool), before googling, check the ... | To set the `timeout` time to 30sec for example. The easiest way is executing: `pip config global.timeout 30` or going to the pip configuration file ***pip.ini*** located in the directory ***~\AppData\Roaming\pip*** in the case of Windows operating system. If the file does not exist there, create it and write:
```
[glo... | 10,917 |
45,934,259 | I am working on a simple project on PhpStorm and installed GAE plugin and SDK. Running a server and show the project works, but when I try to deploy my application I get this kind of error: (This is a PHP project)
```
C:\Python27\python.exe "C:/Users/asim/AppData/Local/Google/Cloud SDK/google-cloud-sdk/platform/google... | 2017/08/29 | [
"https://Stackoverflow.com/questions/45934259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6428568/"
] | The traceback indicates the failure happens when trying to check for SDK updates, so you *should* be able to work around it by using `appcfg.py`'s `--skip_sdk_update_check` option.
I'm not using the PHP SDK, but I found a similar failure in the SDK upgrade check for the python development server, my solution for that ... | If it is really a SSL handshake error than check to see if machine that you are using to access is behind a firewall. If you are than you will have a problem you might have to ask you network guys to open network up. alternatively you can try to get on to network that is not behind firewall. I might be wrong but I have... | 10,918 |
42,081,376 | I have exactly opposite issue described [here](https://stackoverflow.com/q/11489330/2215679).
In my case I have:
logging.py
```
import logging
log = logging.getLogger(..)
```
I got this error:
```
AttributeError: 'module' object has no attribute 'getLogger'
```
This happens only on project with python 2.7 run u... | 2017/02/07 | [
"https://Stackoverflow.com/questions/42081376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2215679/"
] | I found solution, just putting:
```
from __future__ import absolute_import
```
on top of the file will resolve the issue.
source: [https://docs.python.org/2/library/**future**.html](https://docs.python.org/2/library/__future__.html)
As you may see, in python 3>= absolute import is by default | >
> It is better to rename your local file to be different with builtin module name.
>
>
> | 10,926 |
44,395,941 | OK, so I am currently messing around coding hangman in python and was wondering if I can clear what it says in the python shell as I don't just wan't the person to read the word.
```
import time
keyword = input(" Please enter the word you want the person to guess")
lives = int(input("How many lives would you like to h... | 2017/06/06 | [
"https://Stackoverflow.com/questions/44395941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8020756/"
] | if you are a windows user use this:
```
import os
os.system("cls")
```
Mac/linux then :
```
import os
os.system("clear")
``` | Try this:
```
import subprocess
import time
tmp=subprocess.call('clear', shell=True) # 'cls' in windows
keyword = input(" Please enter the word you want the person to guess")
lives = int(input("How many lives would you like to have?"))
print ("There are ", len(keyword), "letters in the word")
time.sleep(2)
```
Sav... | 10,927 |
67,611,765 | ```
i = SomeIndex()
while mylist[i] is not None:
if mylist[i] == name:
return
foo()
i+=1
```
I want foo() to always run on 1st iteration of loop, if mylist[i] isn't 'name', but never run if its any iteration but the first. I know I could the following, but I don't know if it's the most efficient and p... | 2021/05/19 | [
"https://Stackoverflow.com/questions/67611765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14725111/"
] | Let's "pythonize" your example, step by step.
**1. Remove the `first_index` flag:**
```
start_idx = SomeIndex()
i = start_idx
while mylist[i] is not None:
if mylist[i] == name:
return
if i == start_idx:
foo()
i += 1
```
**2. Convert to `while True`:**
```
start_idx = SomeIndex()
i = st... | You are trying to emulate a do-while, take a look at [this question](https://stackoverflow.com/questions/743164/how-to-emulate-a-do-while-loop) if you want.
Since there is no do-while equivalent in Python, the simple idea is to move the first iteration out of the loop
```
i = SomeIndex()
foo()
while mylist[i] is not ... | 10,930 |
827,557 | I'm building an app on Google App Engine. I'm incredibly new to Python and have been beating my head against the following problem for the past 3 days.
I have a class to represent an RSS Feed and in this class I have a method called setUrl. Input to this method is a URL.
I'm trying to use the re python module to val... | 2009/05/06 | [
"https://Stackoverflow.com/questions/827557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91163/"
] | `urlparse` quite happily takes invalid URLs, it is more a string string-splitting library than any kind of validator. For example:
```
from urlparse import urlparse
urlparse('http://----')
# returns: ParseResult(scheme='http', netloc='----', path='', params='', query='', fragment='')
```
Depending on the situation, ... | The regex provided should match any url of the form <http://www.ietf.org/rfc/rfc3986.txt>; and does when tested in the python interpreter.
What format have the URLs you've been having trouble parsing had? | 10,934 |
55,381,039 | I am trying to get a dynamic text displayed in the system tray (this will be 2 numbers (from 1 to 100) changing every 2 minutes).
I found this [script](http://code.activestate.com/recipes/475155-dynamic-system-tray-icon-wxpython/) as a starting point (but I am not commited to it!).
But I get this error :
```
TypeE... | 2019/03/27 | [
"https://Stackoverflow.com/questions/55381039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154274/"
] | I think this issue was occurring due to using the OpenJDK and not the OracleJDK.
I am no longer having this issue since changing the project SDK to the OracleJDK, so if anyone else ever has this issue in the future... that may be the fix. | * Be sure to see also the Swing/Seesaw section [from the Clojure Cookbook](https://github.com/clojure-cookbook/clojure-cookbook/blob/master/04_local-io/4-25_seesaw/4-25_making-a-window.asciidoc)
* [The newer fn/fx lib](https://github.com/fn-fx/fn-fx) for using JavaFX from Clojure. | 10,944 |
50,431,371 | I am trying to create a python program that uses user input in an equation. When I run the program, it gives this error code, "answer = ((((A\*10**A)\*\*2)**(B\*C))\*D\*\*E) TypeError: unsupported operand type(s) for \*\* or pow(): 'int' and 'str'". My code is:
```
import cmath
A = input("Enter a number for A: ")
B ... | 2018/05/20 | [
"https://Stackoverflow.com/questions/50431371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6754577/"
] | The [`input()`](https://docs.python.org/3/library/functions.html#input) function returns a string value: you need to convert to a number using `Decimal`:
```
from decimal import Decimal
A = Decimal(input("Enter a number for A: "))
# ... etc
```
But your user might enter something that isn't a decimal number, so you... | The compiler thinks your inputs are of string type. You can wrap each of A, B, C, D, E with float() to cast the input into float type, provided you're actually inputting numbers at the terminal. This way, you're taking powers of float numbers instead of strings, which python doesn't know how to handle.
```
A = float(i... | 10,946 |
14,228,659 | I can add the XML node using the ElementTree, but this returns the output in one single line instead of a tree structure look alike when I open the xml file in text format. I also tried using the minidom.toprettyxml but I do not know how to add the output to original XML. Since I would like the script to be reproducibl... | 2013/01/09 | [
"https://Stackoverflow.com/questions/14228659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1027101/"
] | when dealing with element, you can do like this: `element.tail = '\n'`
then,it will be written in single line. | write your xml in elementTree as:
```
import xml.etree.ElementTree as ET
def serialize_xml(write, elem, encoding, qnames, namespaces):
tag = elem.tag
text = elem.text
if tag is ET.Comment:
write("<!--%s-->" % _encode(text, encoding))
elif tag is ET.ProcessingInstruction:
write("<?%s?>"... | 10,950 |
2,565,415 | What is the right way to forming in-memory table in python with direct lookups for rows and columns.
I thought of using dict of dicts this way,
```
class Table(dict):
def __getitem__(self, key):
if key not in self:
self[key]={}
return dict.__getitem__(self, key)
table = Table()
tab... | 2010/04/02 | [
"https://Stackoverflow.com/questions/2565415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231295/"
] | I'd use an [in-memory database](http://www.sqlite.org/inmemorydb.html) with [SQLite](http://docs.python.org/library/sqlite3.html) for this. The sqlite module is even in the standard library since Python 2.5, which means this doesn't even add much to your requirements. | A nested list should be able to do the job here. I would only use nested dictionaries if elements are spread thin across the grid.
```
grid = []
for row in height:
grid.append([])
for cell in width:
grid[-1].append(value)
```
Checking rows is easy:
```
def valueInRow(value, row):
return value in grid[... | 10,952 |
6,184,079 | Similar questions have been asked, but I have not come across an easy-to-do-it way
We have some application logs of various kinds which fill up the space and we face other unwanted issues. How do I write a monitoring script(zipping files of particular size, moving them, watching them, etc..) for this maintenance? I am... | 2011/05/31 | [
"https://Stackoverflow.com/questions/6184079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/294714/"
] | The "standard" way of doing this (atleast on most Gnu/Linux distros) is to use [logrotate](http://www.linuxcommand.org/man_pages/logrotate8.html). I see a `/etc/logrotate.conf` on my Debian machine which has details on which files to rotate and at what frequency. It's triggered by a daily cron entry. This is what I'd r... | Use [logrotate](http://linuxcommand.org/man_pages/logrotate8.html) to do the work for you.
Remember that there are few cases where it **may not work properly**, for example if the logging application keeps the log file always open and is not able to resume it if the file is removed and recreated.
Over the years I enc... | 10,957 |
54,446,492 | I have a requirement where I have to trigger a dataset in a blob to my python code where processing will happen and then store the processed dataset to the blob? Where should I do it? Any notebooks?
Azure functions dont have an option to write a Python code.
Any help would be appreciated. | 2019/01/30 | [
"https://Stackoverflow.com/questions/54446492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9668890/"
] | The difference here is *really* subtle, and can only *easily* be appreciated in IL:
```
class MyBuilder1
{
private MySynchronizer m_synchronizer = new MySynchronizer();
public MyBuilder1()
{
}
}
```
gives us the constructor:
```
.method public hidebysig specialname rtspecialname
instance void... | I almost always choose the second one option (initializing inside the constructor). In my point of view it keeps your code more readable and the control logic is inside the constructor which gives more flexibility to add logic in the future.
But again, it is only my personal opinion. | 10,958 |
60,538,059 | I am trying to download MNIST data in PyTorch using the following code:
```
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('data',
train=True,
download=True,
transform=transforms.Compose([
transforms.ToTensor()... | 2020/03/05 | [
"https://Stackoverflow.com/questions/60538059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4848812/"
] | This is a new bug, reported here: <https://github.com/pytorch/vision/issues/1938>
See that thread for some potential workarounds until the issue is fixed in pytorch itself. | My workaround is: run on your local machine a simple program to download the MNIST dataset from the `torchvision.datasets` module, save with `pickle` a copy on your machine and upload it in your Google Drive.
Is not proper fix but a viable and affordable workaround, hope it helps somehow | 10,961 |
23,080,960 | Here I'm trying to create a pie chart using **matplotlib** python library. But the dates are overlapping if the values are same "0.0" multiple times.
My question is how I can display them separately.
Thanks.

This is what I tried:
```
from pylab... | 2014/04/15 | [
"https://Stackoverflow.com/questions/23080960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3270800/"
] | You can adjust the label positions manually, although that results in a bit more code you would want to for such a simple request. You can detect groups of duplicate labels by examining the positions at which there are placed.
Here is an example with some random data replicating the occurrence of overlapping labels:
... | I am not sure it there is a way to adjust "labeldistance" for every element, but I could solve this using a tricky-way.
I added explode(0, 0.1, 0, 0)
```
from pylab import *
labels = [ "05-02-2014", "23-02-2014","07-02-2014","08-02-2014"]
values = [0, 0, 2, 10]
explode = (0, 0.1, 0, 0)
fig = plt.figure(figsize=(9.0,... | 10,962 |
58,841,308 | I need a domain validator and email validator, ie validate if both exist. The company I'm servicing has a website that validates this for them, ensuring they won't send email to a nonexistent mailbox. It would be an email marketing action anyway. They have something basic about excel, but they want a service to be runn... | 2019/11/13 | [
"https://Stackoverflow.com/questions/58841308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403338/"
] | There is a [documented](https://learn.microsoft.com/graph/api/channel-get-filesfolder?view=graph-rest-1.0&tabs=http) navigational property of the Channel resource called `filesFolder`. From the Graph v1.0 endpoint:
```xml
<EntityType Name="channel" BaseType="microsoft.graph.entity">
<Property Name="displayName" Type... | Currently /filesFolder for Private Channels returns BadGateway | 10,963 |
27,554,484 | I'm trying to use theano but I get an error when I import it.
I've installed cuda\_6.5.14\_linux\_64.run, and passed all the recommended test in Chapter 6 of [this](http://developer.download.nvidia.com/compute/cuda/6_5/rel/docs/CUDA_Getting_Started_Linux.pdf) NVIDIA PDF.
Ultimately I want to be able to install pylearn2... | 2014/12/18 | [
"https://Stackoverflow.com/questions/27554484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2423116/"
] | I encountered exactly the same question.
My solution is to replace cuda-6.5 with cuda-5.5, and everything works fine. | We also saw this error. We found that putting /usr/local/cuda-6.5/bin in $PATH seemed to fix it (even with the root = ... line in .theanorc). | 10,966 |
61,264,563 | When I import numpy and pandas in jupyter it gives error same in spider but in spider works after starting new kernel.
```
import numpy as np
```
---
```
NameError Traceback (most recent call last)
<ipython-input-1-0aa0b027fcb6> in <module>
----> 1 import numpy as np
~\numpy.py in <... | 2020/04/17 | [
"https://Stackoverflow.com/questions/61264563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13287554/"
] | this is showing "NameError" which is due to the
arr=array([1,2,3,4])
you should try something like this
arr=np.array([1,2,3,4]) | Try this:
```
arr=np.array([1,2,3,4])
``` | 10,967 |
73,230,522 | Hi I am new to python and I have a simple question, I have a list consisting of some user info and I want to know how can I write a program to find and update some of that info.
```
user_list = [
{'name': 'Alizom_12',
'gender': 'f',
'age': 34,
'active_day': 170},
{'name': 'Xzt4f',
'gender':... | 2022/08/04 | [
"https://Stackoverflow.com/questions/73230522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19686631/"
] | Even if you accepted the remote version you still created a merge commit which basically contains the information that the changes you made are integrated in the branch. The merge commit will have two parents: the commit you pulled and your local one.
This new commit needs pushing.
You'll see the commit when you insp... | If you haven't set `rebase=true` in `.gitconfig`, please set it up like this:
```
[pull]
rebase = true
```
When you have conflicts you should resolve it and force push it:
```
git push -f
``` | 10,972 |
16,536,101 | I read this on Python tutorial: (<http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files>)
>
> Python on Windows makes a distinction between text and binary files;
> the end-of-line characters in text files are automatically altered slightly
> when data is read or written. This behind-the-sc... | 2013/05/14 | [
"https://Stackoverflow.com/questions/16536101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1769958/"
] | You just have to take care to open files on windows as binary (`open(filename, "rb")`) and not as text files. After that there is no problem using the data.
Particularly the end-of-line on Windows is `'\r\n'`. And if you read a binary file as text file and write it back out, then single `'\n'` are transformed in `'\r\... | >
> I feel binary data don't have such things like end-of-line.
>
>
>
Binary files can have ANY POSSIBLE character in them, including the character \n. You do not want python implicitly converting any characters in a binary file to something else. Python has no idea it is reading a binary file unless you tell it s... | 10,975 |
60,882,099 | I have a redhat server with docker installed
I want to create a docker image in which I want to run django with MySQL but the problem is django is unable to connect to MySQL server(remote server).
I'm getting following error:
```
Plugin caching_sha2_password could not be loaded: /usr/lib/x86_64-linux-gnu/mariadb19/pl... | 2020/03/27 | [
"https://Stackoverflow.com/questions/60882099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10386411/"
] | The primary reason is simplicity. The existing rule is easy to understand (you clearly understand it) and easy to implement. The data-flow analysis required (to distinguish between acceptable and unacceptable uses in general) is complex and not normally necessary for a compiler, so it was thought a bad idea to require ... | In Ada, when you try to think about accessibility, you have to do it in terms of access types instead of variables. There's no lifetime analysis of variables (contrarily to what Rust does, I think). So, what's the worst that could happen? If your pointer type level is less than the target variable level, accessibility ... | 10,978 |
11,450,649 | I'm having a really tough time with getting the results page of this url with python's urllib2:
```
http://www.google.com/search?tbs=sbi:AMhZZitAaz7goe6AsfVSmFw1sbwsmX0uIjeVnzKHjEXMck70H3j32Q-6FApxrhxdSyMo0OedyWkxk3-qYbyf0q1OqNspjLu8DlyNnWVbNjiKGo87QUjQHf2_1idZ1q_1vvm5gzOCMpChYiKsKYdMywOLjJzqmzYoJNOU2UsTs_1zZGWjU-... | 2012/07/12 | [
"https://Stackoverflow.com/questions/11450649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1488252/"
] | Your user-agent is not defined !
Take that one :
```
#!/usr/bin/python
import urllib2
url = "http://www.google.com/search?q=mysearch";
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
print opener.open(url).read()
raw_input()
```
If you like find an other user-agent, you can wri... | Google has several anti-scraping techniques in place, since they don't want users to get to the results without the APIs or real browsers.
If you are serious about scraping this kind of pages, I suggest you look into: [Selenium](http://seleniumhq.org/) or [Spynner](http://code.google.com/p/spynner/).
Another advanta... | 10,979 |
66,488,745 | **PROBLEM ENCOUNTERED:**
>
> E/AndroidRuntime: FATAL EXCEPTION: main
> Process: org.tensorflow.lite.examples.detection, PID: 14719
> java.lang.AssertionError: Error occurred when initializing ObjectDetector: Mobile SSD models are expected to have exactly 4 outputs, found 8
>
>
>
**Problem Description**
* Android... | 2021/03/05 | [
"https://Stackoverflow.com/questions/66488745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15334979/"
] | After further study, I believe the aforementioned issue was raised since the model has 8 tensors output but the Android application written in Java can only support 4 tensors output (at least the example provided by Google only supports 4 tensors output)
I am not very certain about the number of tensors output on diff... | For those who will stumble on this problem/question later: limitations on the number of output tensors are part of Tensorflow Lite Object Detection API specification described [here](https://www.tensorflow.org/lite/inference_with_metadata/task_library/object_detector#model_compatibility_requirements)
I don't know how t... | 10,980 |
27,239,348 | I am using photologue to create a photo gallery site with django. I installed django-tagging into my virtualenv, not knowing it was no longer supported by photologue. Now, after having performed migrations, whenever I try to add a photo or view the photo, I get FieldError at /admin/photologue/photo/upload\_zip/
Cannot ... | 2014/12/01 | [
"https://Stackoverflow.com/questions/27239348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4043633/"
] | The problem seems to arise from the fact, that django-tagging was somehow still present on the virtualenv.
In your traceback after photologue saves a model, django-tagging reacts to the sent signal and tries to update any related tags:
```
File "/home/cameron/Envs/photologue/local/lib/python2.7/site-packages/django/d... | Well the error is simple -- in that you are requesting a field in the database that does not exist. Since you haven't posted code it is hard to be more specific than that. Was one of your templates built, referencing a field named 'items' that is no longer there?
Please edit your question to include a FULL traceback ... | 10,981 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.