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 |
|---|---|---|---|---|---|---|
21,977,987 | When I run a program from a USB memory, and remove the USB memory the program still goes on running (I mean with out really copying the program into the Windows PC).
However, does the program make its copy inside the Windows in any hidden location or temporary folder while running by the python IDLE. From where the pyt... | 2014/02/24 | [
"https://Stackoverflow.com/questions/21977987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | There are plenty of ways someone can get your program, even if you remove the USB drive.
* They can install a program that triggers when a USB stick is inserted, search the stick for `.py` files, and copies them to disk.
* If the Python installation you're using is on the disk instead of the USB drive, they can replac... | It sounds like you are doing something you probably shouldn't be doing. Depending on how much people want your code they could go as far as physically freezing the ram and doing a forensic IT analysis. In short, you can't prevent code cloning on a machine you don't administer. | 1,469 |
17,973,507 | I have a long list of xy coordinates, and would like to convert it into numpy array.
```
>>> import numpy as np
>>> xy = np.random.rand(1000000, 2).tolist()
```
The obvious way would be:
```
>>> a = np.array(xy) # Very slow...
```
However, the above code is unreasonably slow. Interestingly, to transpose the long ... | 2013/07/31 | [
"https://Stackoverflow.com/questions/17973507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2003079/"
] | Implementing this in Cython without the extra checking involved to determine dimensionality, etc. nearly eliminates the time difference you are seeing.
Here's the `.pyx` file I used to verify that.
```
from numpy cimport ndarray as ar
import numpy as np
cimport cython
@cython.boundscheck(False)
@cython.wraparound(Fal... | This is because the fastest-varying index of your list is the last one, so `np.array()` has to traverse the array many times because the first index is much larger. If your list was transposed, `np.array()` would be faster than your `longlist2array`:
```
In [65]: import numpy as np
In [66]: xy = np.random.rand(10000,... | 1,470 |
68,957,505 | ```
input = (Columbia and (India or Singapore) and Malaysia)
output = [Columbia, India, Singapore, Malaysia]
```
Basically ignore the python keywords and brackets
I tried with the below code, but still not able to eliminate the braces.
```
import keyword
my_str=input()
l1=list(my_str.split(" "))
l2=[x for x in l... | 2021/08/27 | [
"https://Stackoverflow.com/questions/68957505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15695277/"
] | If you want to do it using first principles, you can use the code that is presented on the [Wikipedia page for Halton sequence](https://en.wikipedia.org/wiki/Halton_sequence):
```py
def halton(b):
"""Generator function for Halton sequence."""
n, d = 0, 1
while True:
x = d - n
if x == 1:
... | In Python, SciPy is the main scientific computing package, and it [contains a Halton sequence generator](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.qmc.Halton.html), among other QMC functions.
For plotting, the standard way with SciPy is matplotlib; if you're not familiar with that, the [tutorial... | 1,473 |
73,104,518 | using opencv for capturing image in python
i want to make this image :
code for this :
```
# Image Processing
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (51,51), 15)
th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
ret, test_image =... | 2022/07/25 | [
"https://Stackoverflow.com/questions/73104518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16383903/"
] | For each position, look for the 4 possibles values, that for each a condition of existance
```
for i in range(len(arr)):
for j in range(len(arr[i])):
key = f'{i}{j}'
if i != 0:
d[key].append(arr[i - 1][j])
if j != 0:
d[key].append(arr[i][j - 1])
if i != (len(... | One approach using a dictionary comprehension:
```
from itertools import product
arr = [[0, 2, 3],
[2, 0, 4],
[3, 4, 0]]
def cross(i, j, a):
res = []
for ii, jj in zip([0, 1, 0, -1], [-1, 0, 1, 0]):
ni = (i + ii)
nj = (j + jj)
if (-1 < ni < len(a[0])) and (-1 < nj < len(... | 1,474 |
28,376,849 | The Eclipse PyDev plugin includes fantastic integrated `autopep8` support. It formats the code to PEP8 style automatically on save, with several knobs and options to tailor it to your needs.
But the `autopep8` import formatter breaks `site.addsitedir()` usage.
```
import site
site.addsitedir('/opt/path/lib/python')
... | 2015/02/07 | [
"https://Stackoverflow.com/questions/28376849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2125392/"
] | Oldie but still relevant as I found this one issue.
I'm using VSCode and autopep8.
You can disable formatting by adding `# nopep8` to the relevant lines.
ps. Checked the docs for a link but could not find it :( | The best option I can find is to turn off import sorts in PyDev. This is not a complete solution, but it's better than completely turning off `autopep8` code formatting.
Just uncheck the `Sort imports on save?` option in the Eclipse/PyDev Preferences.
For Eclipse Kepler, Service Release 2, with PyDev 3.9.2, you can... | 1,479 |
6,916,054 | I'm working with python using Matplotlib and PIL and a need to look into a image select and cut the area that i have to work with, leaving only the image of the selected area.I alredy know how to cut imagens with pil(using im.crop) but how can i select the coordinates to croped the image with mouse clicks?
To better e... | 2011/08/02 | [
"https://Stackoverflow.com/questions/6916054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/669332/"
] | You could use [matplotlib.widgets.RectangleSelector](http://matplotlib.sourceforge.net/api/widgets_api.html?highlight=matplotlib.widgets#matplotlib.widgets.RectangleSelector) (thanks to Joe Kington for this suggestion) to handle button press events:
```
import numpy as np
import matplotlib.pyplot as plt
import Image
i... | are you using tk? it will depend on what window management you are using. High level though, you'll want something like:
```
def onMouseDown():
// get and save your coordinates
def onMouseUp():
// save these coordinates as well
// now compare your coordinates to fingure out which corners
// are being... | 1,480 |
50,489,637 | I am learning C++, is there something like python-pip in C++? I am uing `json`/`YAML` packages in my 1st project, I want to know which is the correct way to manage dependencies in my project, and after I finished developing, which is the correct way to migrate dependencies to production environment? | 2018/05/23 | [
"https://Stackoverflow.com/questions/50489637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5735646/"
] | C++ doesn't have a standard package manager or build system: this is one of the major pain points of the language. You have a few options:
* Manually install dependencies when required.
* Use your OS's package manager.
* Adopt a third-party package manager such as [conan.io](http://conan.io).
None of the above soluti... | As far as I know, there is no central library management system in C++ similar to `pip`. You need to download and install the packages you need manually or through some package manager if your OS supports it.
As for managing multiple libraries in a C++ project, you could use [CMAKE](https://cmake.org/) or something si... | 1,481 |
18,755,963 | I have designed a GUI using python tkinter. And now I want to set style for Checkbutton and Labelframe, such as the font, the color .etc
I have read some answers on the topics of tkinter style, and I have used the following method to set style for both Checkbutton and Labelframe.
But they don't actually work.
```
Roo... | 2013/09/12 | [
"https://Stackoverflow.com/questions/18755963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2771241/"
] | You need to configure the Label sub-component:
```
from tkinter import *
from tkinter import ttk
root = Tk()
s = ttk.Style()
s.configure('Red.TLabelframe.Label', font=('courier', 15, 'bold'))
s.configure('Red.TLabelframe.Label', foreground ='red')
s.configure('Red.TLabelframe.Label', background='blue')
lf = ttk.Lab... | As the accepted answer didn't really help me when I wanted to do a simple changing of weight of a `ttk.LabelFrame` font (if you do it like recommended, you end up with a misplaced label), I'll provide what worked for me.
You have to use `labelwidget` option argument of `ttk.LabelFrame` first preparing a seperate `ttk.... | 1,482 |
38,163,087 | Having an issue where I would fill out the form and when I click to save the input, it would show the info submitted into the `query` but my `production_id` value would return as `None`.
**Here is the error:**
```
Environment:
Request Method: POST
Request URL: http://192.168.33.10:8000/podfunnel/episodeinfo/
Django... | 2016/07/02 | [
"https://Stackoverflow.com/questions/38163087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3557390/"
] | It looks like `production_id` can be `None` in your view, in which case you can't use it when you call reverse. It would be better to use `production.id` instead. You have just saved the production in your view, so `production.id` will be set.
```
return HttpResponseRedirect(reverse('podfunnel:episodeimagefiles', kwar... | You can't always redirect to `episodeimagefiles` if you didn't provide appropriate initial value for `production_id`:
```
# See if a production_id is passed on the kwargs, if so, retrieve and fill current data.
# if not just provide empty form since will be new.
production_id = kwargs.get('production_id', ... | 1,485 |
63,033,970 | Using python3.8.1, installing newest version, on Windows 10:
`pip install PyNaCl` gives me this error (last 10 lines):
```
File "C:\Program Files (x86)\Python3\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "C:\Program Files (x86)\Python3\lib\distutils\dist.p... | 2020/07/22 | [
"https://Stackoverflow.com/questions/63033970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8558929/"
] | I ultimately solved it by using `python -m pip install --no-use-pep517 pynacl` | Upgrading pip within the venv worked for me:
```
.\env\Scripts\activate
pip install -U pip
pip install -r requirements.txt
deactivate
``` | 1,486 |
28,891,405 | I am trying to contract some vertices in igraph (using the python api) while keeping the names of the vertices. It isn't clear to me how to keep the name attribute of the graph. The nodes of the graph are people and I'm trying to collapse people with corrupted names.
I looked at the R documentation and I still don't s... | 2015/03/06 | [
"https://Stackoverflow.com/questions/28891405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639290/"
] | In Python, the keyword argument you need is called `combine_attrs` and not `vertex.attr.comb`. See `help(Graph.contract_vertices)` from the Python command line after having imported igraph. Also, the keyword argument accepts either a single specifier (such as `first`) or a dictionary. Your first example is invalid beca... | Nevermind. You can just enter a dictionary without using the wording
```
vertex.attr.comb
``` | 1,487 |
70,806,221 | So I have a "terminal" like program written in python and in this program I need to accept "mkdir" and another input and save the input after mkdir as a variable. It would work how sys.argv works when executing a python program but this would have to work from inside the program and I have no idea how to make this work... | 2022/01/21 | [
"https://Stackoverflow.com/questions/70806221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17746152/"
] | May use the pattern (`\\[[^\\]]+(\\[|$)|(^|\\])[^\\[]+\\]`) in `str_detect`
```
library(dplyr)
library(stringr)
df %>%
filter(str_detect(Utterance, "\\[[^\\]]+(\\[|$)|(^|\\])[^\\[]+\\]"))
id Utterance
1 1 [but if I came !ho!me
2 3 =[yeah] I mea... | If you need a function to validate (nested) parenthesis, here is a stack based one.
```
valid_delim <- function(x, delim = c(open = "[", close = "]"), max_stack_size = 10L){
f <- function(x, delim, max_stack_size){
if(is.null(names(delim))) {
names(delim) <- c("open", "close")
}
if(nchar(x) > 0L){
... | 1,488 |
66,830,558 | I just started a new project in django, I run the command 'django-admin startproject + project\_name', and 'python manage.py startapp + app\_name'. Created a project and app.
I also added my new app to the settings:
[settings pic](https://i.stack.imgur.com/aMIpy.png)
After that I tried to create my first module on 'm... | 2021/03/27 | [
"https://Stackoverflow.com/questions/66830558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15493450/"
] | You want a `dict: {letter:positions}` , for that a `defaultdict` is well suited
```
from collections import defaultdict
def nb_occurances(word):
dict_occ = {}
positions = defaultdict(list)
for i, c in enumerate(word):
dict_occ[c] = word.count(c)
positions[c].append(i)
return dict_occ, ... | Did you consider using the `collections.Counter` class?
```py
from collections import Counter
def nb_occurances(str):
ctr = Counter(str)
for ch, cnt in ctr.items():
print(ch, '->', cnt)
nb_occurances('ababccab')
```
Prints:
```
a -> 3
b -> 3
c -> 2
``` | 1,490 |
43,573,582 | I'm trying to make a graph with a pretty massive key:
```
my_plot = degrees.plot(kind='bar',stacked=True,title="% of Degrees by Field",fontsize=20,figsize=(24, 16))
my_plot.set_xlabel("Institution", fontsize=20)
my_plot.set_ylabel("% of Degrees by Field", fontsize=20)
my_plot.legend(["Agriculture, Agriculture Oper... | 2017/04/23 | [
"https://Stackoverflow.com/questions/43573582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7907634/"
] | >
> but as a2[][] is locally declared then its elements should not be initialosed by deaflt
>
>
>
There's a big difference between a *variable* and an array entry.
`b` not being initialized is a common coding error, so the compiler calls it out.
But `a2` is initialized, and the contents of an array are set to th... | ```
public class HelloWorld{
public static void main(String []args){
System.out.println("sampleArray[0] is ");
int sampleArray[] = new int[7];
System.out.println(sampleArray[0]);
}
}
Output
sampleArray[0] is
0
``` | 1,494 |
54,445,338 | A python list consist of a number of items that is equally divided by 3.
The list looks like this:
```
the_list = ['ab','cd','e','fgh','i', 'jklm']
```
I want to merge 3 items at the time for the entire list. How should I do that? (the list could have any number of items as long as the number of items can be divid... | 2019/01/30 | [
"https://Stackoverflow.com/questions/54445338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2466763/"
] | You can slice the list while iterating an index over the length of the list with a step of 3 in a list comprehension:
```
[''.join(the_list[i:i + 3]) for i in range(0, len(the_list), 3)]
```
You can also create an iterator from the list and use `zip` with `itertools.repeat` to group 3 items at a time:
```
from iter... | Here's one way using a list comprehension and `range`:
```
output = [''.join(the_list[i:i+3]) for i in range(0, len(the_list), 3)]
``` | 1,495 |
9,701,227 | I don't understand the answers for a [similar question.](https://stackoverflow.com/questions/9359677/why-python-reduce-skip-over-the-none-element)
It is clear that this should return `True`
```
l = [1,1,1]
reduce(lambda x,y: x== y, l)
```
However, how do you explain this retuns `False` (when `None==None` is `True`... | 2012/03/14 | [
"https://Stackoverflow.com/questions/9701227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94363/"
] | Because
```
1 == True # 1 == (1 == 1)
```
is `True`, but
```
None == True # None == (None == None)
```
is `False` (and `None == False` is `False` as well, so once you got `False`, it stays `False`).
That's how `reduce` works: It passes each element and the **result** of the previous evaluation to the callback. ... | Your second example return `False` because the first time `None == None` gives `True`, but `True == None` gives `False`.
Take a look at the [`reduce` doc](http://docs.python.org/library/functions.html#reduce) to see how it works.
Also note that "comparisons to singletons like `None` should always be done with `is` or... | 1,496 |
56,966,429 | I want to do this
```py
from some_cool_library import fancy_calculation
arr = [1,2,3,4,5]
for i, item in enumerate(arr):
the_rest = arr[:i] + arr[i+1:]
print(item, fancy_calculation(the_rest))
[Expected output:] # some fancy output from the fancy_calculation
12.13452134
2416245.4315432
542.343152
15150.1152
... | 2019/07/10 | [
"https://Stackoverflow.com/questions/56966429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8809992/"
] | Try This-
```
SELECT A.smanTeam,
A.TotalTarget,
B.TotalSales,
B.TotalSales*100/A.TotalTarget TotalPercentage
FROM
(
SELECT smanTeam,SUM(Target) TotalTarget
FROM Sman S
INNER JOIN SalesTarget ST ON S.smanID = ST.smanID
GROUP BY smanTeam
)A
LEFT JOIN
(
SELECT smanTeam, SUM(Amount) TotalSales
FRO... | Try below query:
```
select smanTeam, sum(Target) TotalTarget, sum(Amount) TotalSales , sum(Target)/sum(Amount) TotalPercentage from (
select smanTeam, Target, Amount from Sman sm
join
(select smanID, sum(Target) Target from SalesTarget group by smanID) st
on sm.smanID = st.smanID
join
... | 1,501 |
48,435,417 | If I have python code that requires indenting (`for`, `with`, function, etc), will a single line comment end potentially the context of the construct if I place it incorrectly? For example, presuming `step1`, `step2` and `step3` are functions already defined, will:
```
def myFunc():
step1()
# step2()
step3()... | 2018/01/25 | [
"https://Stackoverflow.com/questions/48435417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1099237/"
] | Try it out:
```
def myFunc():
print(1)
# print(2)
print(3)
myFunc()
```
which outputs:
```
1
3
```
So yeah, the answer is "Line comments don't need to match indentation". That said, [PEP8 really prefers that they do, just for readability](https://www.python.org/dev/peps/pep-0008/#block-comments). | It doesn't really matter where you place the `#`
Either in the first identation level or close to the instruction, everything underneath it is going to be executed.
I suggest you to play with the code below and You'll figure it out yourself.
```
a = 1
b = 10
c = 100
d = 1000
if (a == 1):
result = a+b
# resul... | 1,502 |
32,270,272 | I need to get a particular attribute value from a tag whose inner word matches my query word. For example, consider a target html-
```html
<span data-attr="something" attr1="" ><i>other_word</i></span>
<span data-attr="required" attr1="" ><i>word_to_match</i></span>
<span data-attr="something1" attr1="" ><i>some_other... | 2015/08/28 | [
"https://Stackoverflow.com/questions/32270272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2636802/"
] | You're not too far off. You need to iterate the words in each line and check if they are in the dictionary. Also, you need to call `read_words`, otherwise `ret` doesn't exist in the `for` loop.
```
dictionary = read_words(dictionary)
for paper in library:
file = os.path.join(path, paper)
text = open(file, "r")... | If you want to check if any element in the list are in the line
**change this from this :**
```
if re.match("(.*)(ret[])(.*)", line):
```
**To this :**
```
if any(word in line for word in ret)
``` | 1,506 |
34,048,316 | I have a sample file which looks like
```
emp_id(int),name(string),age(int)
1,hasa,34
2,dafa,45
3,fasa,12
8f,123Rag,12
8,fafl,12
```
Requirement: Column data types are specified as strings and integers. Emp\_id should be a integer not string. these conditions ll be the same for name and age columns.
**My output sh... | 2015/12/02 | [
"https://Stackoverflow.com/questions/34048316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1696853/"
] | Here is an awk-solution:
```
awk -F"," 'NR==1{for(i=1; i <= NF; i++){
split($i,a,"(");
name[i]=a[1];
type[i] = ($i ~ "int" ? "INT" : "String")}next}
{for(i=1; i <= NF; i++){
if($i != int($i) && type[i] == "INT"){error[i]... | With `perl` I would tackle it like this:
* Define some regex patterns that match/don't match the string content.
* pick out the header row - separate it into names and types. (Optionally reporting if a type doesn't match).
* iterate your fields, matching by column, figuring out type and applying the regex to validate
... | 1,507 |
71,448,461 | I was writing a python code in VS Code and somehow it's not detecting the input() function like it should.
Suppose, the code is as simple as
```
def main():
x= int ( input() )
print(x)
if __name__ == "__main__":
main()
```
even then, for some reason it is throwing error and I cannot figure out why.
... | 2022/03/12 | [
"https://Stackoverflow.com/questions/71448461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16979277/"
] | The traceback shows you where to look. It's actually the `int` function throwing a `ValueError`. It looks as if you're feeding it a filepath whereas it it's expecting a number.
You could add a check to repeat the input if incorrect like so:
```py
user_input = None
while not user_input:
raw_input = input("Put in a... | it's working!!!
see my example that says why you don't understand this:
```py
>>> x1 = input('enter a number: ')
enter a number: 10
>>> x1
'10'
>>> x2 = int(x1)
>>> x2
10
>>> x1 = input() # no text
100
>>> # it takes
>>> x1
'100'
>>> # but how you try?
>>> x1 = input()
NOT-NUMBER OR EMPTY-TEXT
>>> x2 = int(x1)
Trace... | 1,508 |
37,124,504 | All,
I wrote a small python program to create a file which is used as an input file to run an external program called srce3d. Here it is:
```
fin = open('eff.pwr.template','r')
fout = open('eff.pwr','wr')
for line in fin:
if 'li' in line:
fout.write( line.replace('-2.000000E+00', `-15.0`) )... | 2016/05/09 | [
"https://Stackoverflow.com/questions/37124504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5590629/"
] | Firstly you are missing the function calls for close.
```
fin.close() ## the round braces () were missing.
fout.close()
```
A better way to do the same is using contexts.
```
with open('eff.pwr.template','r') as fin, open('eff.pwr','wr') as fout:
## do all processing here
``` | You didn't actually close the file – you have to *call* `file.close`. So,
```
fin.close
fout.close
```
should be
```
fin.close()
fout.close()
``` | 1,510 |
29,411,952 | I need to delete all the rows in a csv file which have more than a certain number of columns.
This happens because sometimes the code, which generates the csv file, skips some values and prints the following on the same line.
Example: Consider the following file to parse. I want to remove all the rows which have mo... | 2015/04/02 | [
"https://Stackoverflow.com/questions/29411952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3014331/"
] | This can be done straight forward with `awk`:
```
awk -F, 'NF<=3' file
```
This uses the `awk` variable `NF` that holds the number of fields in the current line. Since we have set the field separator to the comma (with `-F,` or, equivalent, `-v FS=","`), then it is just a matter of checking when the number of fields... | Try the following (do not omit to replace your file path and your max column):
```bash
#! /bin/bash
filepath=test.csv
max_columns=3
for line in $(cat $filepath);
do
count=$(echo "$line" | grep -o "," | wc -l)
if [ $(($count + 1)) -le $max_columns ]
then
echo $line
fi
done
```
Co... | 1,511 |
47,635,838 | I'm trying to use the LinearSVC of sklearn and export the decision tree to a .dot file. I can fit the classifier with sample data and then use it on some test data but the export to the .dot file gives a NotFittedError.
```
data = pd.read_csv("census-income-data.data", skipinitialspace=True, usecols=list(range(0, 41))... | 2017/12/04 | [
"https://Stackoverflow.com/questions/47635838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6534294/"
] | You are using a [function](http://scikit-learn.org/stable/modules/generated/sklearn.tree.export_graphviz.html#sklearn-tree-export-graphviz) to plot a decision-tree. Look at the first argument: *decision\_tree*, like an object of [this](http://scikit-learn.org/stable/modules/tree.html).
A SVM is not a decision-tree! It... | In `sklearn.tree.export_graphviz`, the first parameter is a fitted decision tree.
You give a fitted estimator, but not a decision tree.
**Indeed, `LinearSVC` is not a decision tree.**
Try with `sklearn.tree.DecisionTreeClassifier` instead of `sklearn.svm.LinearSVC`. | 1,512 |
47,443,434 | I'm new to python/data science in general, trying to understand why the below isn't working:
```
import pandas as pd
url = 'https://s3.amazonaws.com/nyc-tlc/trip+data/fhv_tripdata_2017-06.csv'
trip_df = []
for chunk in pd.read_csv(url, chunksize=1000, nrows=10000):
trip_df.append(chunk)
trip_df = pd.concat(trip_df... | 2017/11/22 | [
"https://Stackoverflow.com/questions/47443434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8992936/"
] | Try this:
```
reader = pd.read_csv(url, chunksize=1000, nrows=10000)
df = pd.concat([x for x in reader], ignore_index=True)
```
>
> how would I just get part of it, say 5,000 rows?
>
>
>
```
df = pd.read_csv(url, nrows=5000)
``` | Just get the 5000 rows in the command line with
```
wget -q -O - https://s3.amazonaws.com/nyc-tlc/trip+data/fhv_tripdata_2017-06.csv | head -n 5000 > tmp.csv
```
and then proceed with tmp.csv | 1,513 |
10,931,150 | php has the [`strtr`](http://php.net/manual/en/function.strtr.php) function:
```
strtr('aa-bb-cc', array('aa' => 'bbz', 'bb' => 'x', 'cc' => 'y'));
# bbz-x-y
```
It replaces dictionary keys in a string with corresponding values and (important) doesn't replace already replaced strings. A naive attempt to write the sa... | 2012/06/07 | [
"https://Stackoverflow.com/questions/10931150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989121/"
] | Here is a naive algorithm:
Use an index to walk the original string character by character and check for each index whether one of the search strings is equal to the string from the current index on. If a match is found, push the replacement in a buffer and proceed the index by the length of the matched string. If no ... | [`str.translate`](http://docs.python.org/library/stdtypes.html#str.translate) is the equivalent, but can only map to single characters. | 1,515 |
36,900,272 | Being a complete begginer in python, I decided to install the python interpreter 3.4.4, and also PyDev plugin for eclipse IDE. I am also using windows 10.
I have encountered a problem regarding certain imports, namely : `from PIL import Image, ImageTk`, which is apparently an unresolved import.
I have looked at certa... | 2016/04/27 | [
"https://Stackoverflow.com/questions/36900272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4375983/"
] | Found the solution, here's what I did:
1. Set the PYTHONPATH [like it is shown in this article](https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7/4855685#4855685), make sure python.exe is accessible via cmd,
2. Via cmd, type `pip install pillow`. Alternatively, you can enter the sam... | For Python import problems in PyDev, the project web site has a page on [interpreter configuration](http://www.pydev.org/manual_101_interpreter.html) that is a good place to start. I recently had a similar problem that I solved by adding a module to the forced builtins tab. | 1,522 |
21,845,390 | hello friends i just started to use GitHub and i just want to know it is possible to download github repository to my local computer through by Using GitHub Api or Api libraries (ie. python library " pygithub3" for Github api) | 2014/02/18 | [
"https://Stackoverflow.com/questions/21845390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3321823/"
] | Using [`github3.py`](http://github3py.rtfd.org/) you can clone all of your repositories (including forks and private repositories) by doing:
```
import github3
import subprocess
g = github3.login('username', 'password')
for repo in g.iter_repos(type='all'):
subprocess.call(['git', 'clone', repo.clone_url])
```
... | As illustrated in [this Gist](https://gist.github.com/jharjono/1159239), the simplest solution is simply to call git clone.
```python
#!/usr/bin/env python
# Script to clone all the github repos that a user is watching
import requests
import json
import subprocess
# Grab all the URLs of the watched repo
user = 'jharj... | 1,523 |
36,238,155 | I have a script in python that consists of multiple list of functions, and at every end of a list I want to put a back function that will let me return to the beginning of the script and choose another list. for example:
```
list = ("1. List of all users",
"2. List of all groups",
"3. Reset password",
"4. ... | 2016/03/26 | [
"https://Stackoverflow.com/questions/36238155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5974999/"
] | Maybe your EditTexts are not initialized, you need something like `quantity1 = (EditText) findViewById(R.id.YOUR_EDIT_TEXT_ID)` for both. | Check what you are passing...check my example.
```
package general;
public class TestNumberFormat {
public static void main(String[] args){
String addquantity = "40";
String subquantity = "30";
int final_ = Integer.parseInt(addquantity) - Integer.parseInt(subquantity);
System.out.println("PRI... | 1,524 |
66,602,480 | I am learning fastapi, and I am starting a uvicorn server on localhost. Whenever there is an error/exception, I am not getting the traceback.
All I am getting is : `INFO: 127.0.0.1:56914 - "POST /create/user/ HTTP/1.1" 500 Internal Server Error`
So, It is difficult to debug, I am trying out logging module of python
`... | 2021/03/12 | [
"https://Stackoverflow.com/questions/66602480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14354318/"
] | Solution / Fix
==============
Now, when you execute uvicorn by the in-Python command `uvicorn.run(app)`, this is your next move:
take the ucivorn default logging config and add the handler from your application to it:
```py
config = {}
# this is default (site-packages\uvicorn\main.py)
config['log_config'] = {
... | For "500 Internal Server Error" occurring during a post request, if you invoke FastAPI in debug mode:
```
app = FastAPI(debug=True)
```
Retry the request with Chrome dev tools Network tab open. When you see the failing request show up (note - my route url was '/rule' here):
[ of Red Hat is to make files group owned by GID 0 - the user in the container is always in the root group. You won't be able to chown, but you can selectively expose which files to write to.
A second op... | Can you see the logs using
```
kubectl logs <podname> -p
```
This should give you the errors why the pod failed. | 1,527 |
62,056,688 | ```
eleUserMessage = driver.find_element_by_id("xxxxxxx")
eleUserMessage.send_keys(email)
```
Im trying to use selenium with python to auto fill out a form and fill in my details. So far I have read in my info from a .txt file and stored them in variables for easy reference. When I Find the element and try to... | 2020/05/28 | [
"https://Stackoverflow.com/questions/62056688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13631666/"
] | Because you are storing your details in a text file, it is likely that when you create the email variable there is a newline at the end of the string as this is how text files work. This would explain why the form gets submitted because it is the equivalent of typing the email followed by the enter key. You can try to ... | if you just want to fill out a form ,then submit the finished form.
you can try :
```
eleUserMessage = driver.find_element_by_xpath("//select[@name='name']")
all_options = eleUserMessage.find_elements_by_tag_name("option")
for option in all_options:
print("Value is: %s" % option.get_attribute("valu... | 1,532 |
57,275,797 | This question may seem very basic, however, I would like to improve the code I have written. I have a function that will need either 2 or 3 parameters, depending on some other conditions. I'm checking the length and passing either 2 or 3 with and if statement (see code). I'm sure there must be a better and compact way ... | 2019/07/30 | [
"https://Stackoverflow.com/questions/57275797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2255752/"
] | Not sure what data types you have and how your method looks like, but with \*args you can solve that:
```
def cdf(ppt_fut, *params):
print(ppt_fut)
print(params)
```
Then you can call it like that:
```
cdf(1, 2, 3, 4) # -> prints: 1 (2,3,4)
cdf(1, 2, 3) # -> prints: 1 (2,3)
```
The `params` is in this cas... | You can unpack elements of a list into a function call with `*`.
You don't need to know how many items there are in the list to do this. But this means you can introduce errors if the number of items don't match the function arguments. It's therefore a good idea to check your data for some basic sanity as well.
For ... | 1,533 |
26,328,648 | [Answered first part, please scroll for second question edit]
Currently coding a web scraper in python.
I have the following example string:
`Columbus Blue Jackets at Buffalo Sabres - 10/09/2014`
I want to split it so that I have [Columbus Blue Jackets, Buffalo Sabres, 10/09/2014]
I read up on regular expressions i... | 2014/10/12 | [
"https://Stackoverflow.com/questions/26328648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2621303/"
] | ```
print re.split(r"\s+at\s+|\s+-\s+",teams)
```
Output:`['Columbus Blue Jackets', 'Buffalo Sabres', '10/09/2014']`
Try this.You can do it in one line.Here `teams` is your string.This will give you desired results.
Edit:
```
def getTable(url):
currentMatchup = Crawl.setup(url)
teams = currentMatchup.title... | Capture them into groups with lazy dot-match-all repetition.
```
(.*?)\s+at\s+(.*?)\s+-\s+(\d{2}/\d{2}/\d{4})
```
[***Demo***](http://regex101.com/r/lU3wV3/1)
---
```
import re;
match = re.search(r"(.*?)\s+at\s+(.*?)\s+-\s+(\d{2}/\d{2}/\d{4})", "Columbus Blue Jackets at Buffalo Sabres - 10/09/2014")
print match.g... | 1,535 |
63,557,957 | I am a beginner in python, pycharm and Linux, I want to open an existing Django project. But when I use "python manage.py runserver", I am getting a series of trace-back errors which I am attaching below.
I have installed all the LAMP stack i.e., Linux OS, Apache2 Web server,MariaDB and MYSQLclient with latest versions... | 2020/08/24 | [
"https://Stackoverflow.com/questions/63557957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14156220/"
] | The input pipeline of a dataset is always traced into a graph (as if you used [`@tf.function`](https://www.tensorflow.org/api_docs/python/tf/function)) to make it faster, which means, among other things, that you cannot use `.numpy()`. You can however use [`tf.numpy_function`](https://www.tensorflow.org/api_docs/python... | A bit wordy, but try it like this:
```
def transform(example):
str_example = example.numpy().decode("utf-8")
json_example = json.loads(str_example)
overall = json_example.get('overall', None)
text = json_example.get('reviewText', None)
return (overall, text)
line_dataset... | 1,538 |
2,293,968 | For my project, the role of the Lecturer (defined as a class) is to offer projects to students. Project itself is also a class. I have some global dictionaries, keyed by the unique numeric id's for lecturers and projects that map to objects.
Thus for the "lecturers" dictionary (currently):
```
lecturer[id] = Lecture... | 2010/02/19 | [
"https://Stackoverflow.com/questions/2293968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/273875/"
] | `set` is better since you don't care about order and have no duplicate.
You can parse the file easily with the [csv](http://docs.python.org/library/csv.html?highlight=sv#module-csv) module (with a `delimiter` of `' '`).
Once you have the `lec_name` you must check if that lecturer's already know; for that purpose, kee... | Sets are useful when you want to guarantee you only have one instance of each item. They are also faster than a list at calculating whether an item is present in the collection.
Lists are faster at adding items, and also have an ordering.
This sounds like you would like a set. You sound like you are very close alread... | 1,539 |
2,112,632 | Is it possible to create a grid like below?
I didn't found anything in the forum.
```
#euler-project problem number 11
#In the 20 times 20 grid below,
#four numbers along a diagonal line have been marked in red.
#The product of these numbers is 26 times 63 times 78 times 14 = 1788696.
#What is the greatest product of ... | 2010/01/21 | [
"https://Stackoverflow.com/questions/2112632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237934/"
] | Check out [NumPy](http://numpy.scipy.org/) - specifically, the [N-dimensional array](http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html) object. | Your code example won't compile unless you put commas between the list elements.
For example, this will compile:
```
value = [
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9,10,11,12]
]
```
If you're interested in taking strings like you show, and **parsing** them into a list of lists (or nump... | 1,542 |
58,846,573 | I'm building a voice assistant using python. I want to make it available as a web application. How do I build the same?
Thanks | 2019/11/13 | [
"https://Stackoverflow.com/questions/58846573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10441927/"
] | When you set
```
channel_shift_range=10,
brightness_range=(0.7, 1.3)
```
This modifies the RNG of this generator so that the Image RNG and the Mask RNG are not in sync anymore.
I propose you use a custom Sequence for this task until the KP new API is released. (see <https://github.com/keras-team/governance/blob/m... | For anyone else struggling with this - concatenating the images and masks along the channel axis is a handy way to synchronise the augmentations
```
image_mask = np.concatenate([image, mask], axis=3)
image_mask = augmenter.flow(image_mask).next()
image = image_mask [:, :, :, 0]
mask = image_mask [:, :, :, 1]
``` | 1,550 |
56,047,365 | I need a python code to extract the selected word using python.
```
<a class="tel ttel">
<span class="mobilesv icon-hg"></span>
<span class="mobilesv icon-rq"></span>
<span class="mobilesv icon-ba"></span>
<span class="mobilesv icon-rq"></span>
<span class="mobilesv icon-ba"></span>
<span class="mobilesv icon-ikj"></s... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56047365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8235643/"
] | You can change line 1 to `import Data.List hiding (find)`, assuming you never intend to use the `find` defined there. | In your situation your options are:
1. Rename your own `find` into something else.
2. Import `Data.List` as qualified: `import qualified Data.List`. You can add `as L` to shorten code that uses stuff from `Data.List`. | 1,551 |
35,811,400 | I have about 650 csv-based matrices. I plan on loading each one using Numpy as in the following example:
```
m1 = numpy.loadtext(open("matrix1.txt", "rb"), delimiter=",", skiprows=1)
```
There are matrix2.txt, matrix3.txt, ..., matrix650.txt files that I need to process.
My end goal is to multiply each matrix by ea... | 2016/03/05 | [
"https://Stackoverflow.com/questions/35811400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3973851/"
] | **1. Variant: Nice code but reads all matrices at once**
```
matrixFileCount = 3
matrices = [np.loadtxt(open("matrix%s.txt" % i ), delimiter=",", skiprows=1) for i in range(1,matrixFileCount+1)]
allC = itertools.combinations([x for x in range(matrixFileCount)], 2)
allCMultiply = [np.dot(matrices[c[0]], matrices[c[1]])... | Kordi's answer loads *all* of the matrices before doing the multiplication. And that's fine if you know the matrices are going to be small. If you want to conserve memory, however, I'd do the following:
```
import numpy as np
def get_dot_product(fnames):
assert len(fnames) > 0
accum_val = np.loadtxt(fnames[0]... | 1,552 |
43,814,236 | Example dataset columns: ["A","B","C","D","num1","num2"]. So I have 6 columns - first 4 for grouping and last 2 are numeric and means will be calculated based on groupBy statements.
I want to groupBy all possible combinations of the 4 grouping columns.
I wish to avoid explicitly typing all possible groupBy's such as gr... | 2017/05/05 | [
"https://Stackoverflow.com/questions/43814236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6647085/"
] | Syntax errors are a computer not being able to posses an imput.
Like this:
`answer = 1 +/ 6`
The computer does not recognize the `+/`
a semantics error are human errors. The computer will execute the code, but it will not be as wanted
Like this:
```
if(player = win){
print "You Lose"
}
```
It will print "Y... | Syntax error is an error which will make your code "unprocessable".
```
if true {}
```
instead of
```
if (true) {}
```
for example
Semantics error and logical errors are the same. Your code is correct, but doesn't do what you think it does.
```
while(c = true) {}
```
instead of
```
while (c == true) {}
```
... | 1,557 |
38,686,830 | I'm using python to input data to my script
then trying to return it back
on demand to show the results
I tried to write it as simple as possible since it's only practicing and trying to get the hang of python
here's how my script looks like
```
#!/usr/python
## imports #####
##################
import os
import... | 2016/07/31 | [
"https://Stackoverflow.com/questions/38686830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2310584/"
] | You are getting an error because your JSON data is an array and what you have done is:
```
XmlNode xml = JsonConvert.DeserializeXmlNode(sBody, "BiddingHistory");
```
the above line of code will only work for JSON objects.
So, if your JSON is an Array, then try this:
```
XmlNode xml = JsonConvert.DeserializeXmlNode... | Use service stack from nuget [Service Stack](https://www.nuget.org/packages/ServiceStack/)
add reference to your program
```
using ServiceStack;
```
Convert your json to object
```
var jRst = JsonConvert.DeserializeObject(body);
```
after that you can get xml using service stack like below
```
var xml = jRst.To... | 1,558 |
9,372,672 | I want to use vlc.py to play mpeg2 stream <http://wiki.videolan.org/Python_bindings>.
There are some examples here: <http://git.videolan.org/?p=vlc/bindings/python.git;a=tree;f=examples;hb=HEAD>
When I run the examples, it just can play video file, I want to know is there any examples to play video stream ? | 2012/02/21 | [
"https://Stackoverflow.com/questions/9372672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335499/"
] | According to [this](http://pastebin.com/edncPpW0) Pastebin entry, linked to in [this](https://mailman.videolan.org/pipermail/vlc-devel/2012-September/090310.html) mailing list, it can be solved using a method like this:
```
import vlc
i = vlc.Instance('--verbose 2'.split())
p = i.media_player_new()
p.set_mrl('rtp://@2... | This is a bare bones solution:
```
import vlc
Instance = vlc.Instance()
player = Instance.media_player_new()
Media = Instance.media_new('http://localhost/postcard/GWPE.avi')
Media.get_mrl()
player.set_media(Media)
player.play()
```
if the media is a local file you will have to alter:
```
Media = Instance.media_new... | 1,559 |
40,890,768 | Tensorflow is now available on Windows:
```
https://developers.googleblog.com/2016/11/tensorflow-0-12-adds-support-for-windows.html
```
I used pip install tensorflow.
I try running the intro code:
```
https://www.tensorflow.org/versions/r0.12/get_started/index.html
```
I get this error:
```
C:\Python\Python3... | 2016/11/30 | [
"https://Stackoverflow.com/questions/40890768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1239984/"
] | From the path of your Python interpreter (`C:\Python\Python35-32`), it appears that you are using the 32-bit version of Python 3.5. The official TensorFlow packages are only available for 64-bit architectures (`x64`/`amd64`), so you have two options:
1. Install the [64-bit version](https://www.python.org/ftp/python/3.... | The problem is not with platform (amd64) but with GPU drivers. You need to either install packages which runs on CPU or use that GPU ones you already installed but install also CUDA drivers. | 1,562 |
55,681,488 | There is an existing question [How to write binary data to stdout in python 3?](https://stackoverflow.com/questions/908331/how-to-write-binary-data-to-stdout-in-python-3) but all of the answers suggest `sys.stdout.buffer` or variants thereof (e.g., manually rewrapping the file descriptor), which have a problem: they do... | 2019/04/15 | [
"https://Stackoverflow.com/questions/55681488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23845/"
] | Can't you interleave calls to `write` with `flush` ?
```
sys.stdout.write("A")
sys.stdout.buffer.write(b"B")
```
Results in:
>
> BA
>
>
>
---
```
sys.stdout.write("A")
sys.stdout.flush()
sys.stdout.buffer.write(b"B")
sys.stdout.flush()
```
Results in:
>
> AB
>
>
> | You can define a local function called `_print` (or even override the system `print` function by naming it `print`) as follows:
```
import sys
def _print(data):
"""
If data is bytes, write to stdout using sys.stdout.buffer.write,
otherwise, assume it's str and convert to bytes with utf-8
encoding befo... | 1,565 |
48,935,995 | I am a newbie in python. I have a question about the dimension of array.
I have (10,192,192,1) array which type is (class 'numpy.ndarray').
I would like to divid this array to 10 separated array like 10 \* (1,192,192,1). but I always got (192,192,1) array when I separate.
How can I get separated arrays as a same dimen... | 2018/02/22 | [
"https://Stackoverflow.com/questions/48935995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8032125/"
] | An intent object couldn't be created after the finish. Try it before `finish();`
```
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
```
**Update:** In your case import the intent like this.
```
import android.content.Intent
``` | As your code implies, you are calling `finish()` method before calling your new activity. In other words, the following lines of code will never run:
```
// Opening the Login Activity using Intent.
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
```
In order to sol... | 1,566 |
15,512,741 | I have a .txt file that is UTF-8 formatted and have problems to read it into Python. I have a large number of files and a conversion would be cumbersome.
So if I read the file in via
```
for line in file_obj:
...
```
I get the following error:
```
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/... | 2013/03/19 | [
"https://Stackoverflow.com/questions/15512741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | There are two choices.
1. Specify the encoding when opening the file, instead of using the default.
2. Open the file in binary mode, and explicitly `decode` from `bytes` to `str`.
The first is obviously the simpler one. You don't show how you're opening the file, but assuming your code looks like this:
```
with open... | For Python 2 and 3 solution, use codecs:
```
import codecs
file_obj = codecs.open('ur file', "r", "utf-8")
for line in file_obj:
...
```
Otherwise -- Python 3 -- use abarnert's [solution](https://stackoverflow.com/a/15512760/298607) | 1,568 |
45,414,796 | I have a list of objects with multiple attributes. I want to filter the list based on one attribute of the object (country\_code), i.e.
Current list
```
elems = [{'region_code': 'EUD', 'country_code': 'ROM', 'country_desc': 'Romania', 'event_number': '6880'},
{'region_code': 'EUD', 'country_code': 'ROM', 'country_de... | 2017/07/31 | [
"https://Stackoverflow.com/questions/45414796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5142595/"
] | I think your first approach is already pretty close to being optimal. Dictionary lookup is fast (just as fast as in a `set`) and the loop is easy to understand, even though a bit lengthy (by Python standards), but you should not sacrifice readability for brevity.
You can, however, shave off one line using `setdefault`... | I think that your approach is just fine. It would be slightly better to check `elem['country_code'] not in unique` instead of `elem['country_code'] not in unique.keys()`.
However, here is another way to do it with a list comprehension:
```
visited = set()
res = [e for e in elems
if e['country_code'] not in vi... | 1,569 |
58,997,105 | Fatal Python error: failed to get random numbers to initialize Python
Environment windows 10, VSC 15
Using CreateProcessA winapi and passing lpenvironment variable to run python with scripts.
when lpenvironment is passed null, it works fine.
If I set environment variable PATH and PYTHONPATH = "paths", and pass that L... | 2019/11/22 | [
"https://Stackoverflow.com/questions/58997105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9758247/"
] | The environment you pass to `CreateProcessA` must include `SYSTEMROOT`, otherwise the Win32 API call `CryptAcquireContext` will fail when called inside python during initialization.
When passing in NULL as lpEnvironment, your new process inherits the environment of the calling process, which has `SYSTEMROOT` already d... | To follow up with an example how this can very easily be triggered in pure Python software out in the real world, there are times where it is useful for Python to open up an instance of itself to do some task, where the sub-task need a specific `PYTHONPATH` be set. Often times this may be done lazily on less fussy plat... | 1,570 |
28,859,295 | If I am in **/home/usr** and I call python **/usr/local/rcom/bin/something.py**
How can I make the script inside **something.py** know he resides in **/usr/local/rcom/bin**?
The `os.path.abspath` is calculated with the `cwd` which is **/home/usr** in this case. | 2015/03/04 | [
"https://Stackoverflow.com/questions/28859295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67153/"
] | Assign the result of `df.groupby('User_ID')['Datetime'].apply(lambda g: len(g)>1)` to a variable so you can perform boolean indexing and then use the index from this to call `isin` and filter your orig df:
```
In [366]:
users = df.groupby('User_ID')['Datetime'].apply(lambda g: len(g)>1)
users
Out[366]:
User_ID
18975... | first, make sure you have no duplicate entries:
```
df = df.drop_duplicates()
```
then, figure out the counts for each:
```
counts = df.groupby('User_ID').Datetime.count()
```
finally, figure out where the indexes overlap:
```
df[df.User_ID.isin(counts[counts > 1].index)]
``` | 1,571 |
4,585,776 | I am trying for a while installing [Hg-Git addon](http://hg-git.github.com/) to my Windows 7 Operating system
1. I have crossed several difficulties like installing Python and other utilities described in [this blog](http://blog.sadphaeton.com/2009/01/20/python-development-windows-part-2-installing-easyinstallcould-b... | 2011/01/03 | [
"https://Stackoverflow.com/questions/4585776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/559792/"
] | Ok i got it so ... For others - you need to clone this repo
**HTTPS:**
```
git clone https://github.com/jelmer/dulwich.git
```
**SSH:**
```
git clone git@github.com:jelmer/dulwich.git
```
or just download source - after that you need to go to its folder when you downloaded in command line type:
```
python setu... | I created a powershell script which does the installation in one step. The prereq is you have some build tools and python already installed:
<http://ig2600.blogspot.com/2013/02/using-git-via-hg-on-windows.html> | 1,572 |
25,343,981 | I'm writing a preprocessor in python, part of which works with an AST.
There is a `render()` method that takes care of converting various statements to source code.
Now, I have it like this (shortened):
```
def render(self, s):
""" Render a statement by type. """
# code block (used in structures)
if isi... | 2014/08/16 | [
"https://Stackoverflow.com/questions/25343981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2180189/"
] | Would something like this work?
```
self.map = {
S_Block : self._render_block,
S_Empty : self._render_empty,
S_Function: self._render_function
}
def render(self, s):
return self.map[type(s)](s)
```
Keeping a reference to a class object as a key in a dictionary and having it's ... | The overloading syntax you are looking for can be achieved using [Guido van Rossum's multimethod decorator](http://www.artima.com/weblogs/viewpost.jsp?thread=101605).
Here is a variant of the multimethod decorator which can decorate class methods (the original decorates plain functions). I've named the variant `multi... | 1,574 |
13,621,095 | I want to use mmseg in Go as in other languages, for example, in python you can use pymmseg
So, is there is a similar Go package?
Or, how can I call the C functions from Go?
Or, how can I call shared library (\*.so) from Go like in python? | 2012/11/29 | [
"https://Stackoverflow.com/questions/13621095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/860788/"
] | you can call use C Libs as described in this tutorial:
<http://cheesesun.blogspot.de/2009/12/basic-cgo.html>
and:
<http://siganakis.com/linking-c-libraries-with-go-lang-and-stdc99>
or you may have a look at this library:
<https://github.com/awsong/MMSEGO>
its for chinese, but you may could use it to put your own ... | Use `cgo` to call C code from Go.
[Command cgo](http://golang.org/cmd/cgo/)
[C? Go? Cgo!](http://blog.golang.org/2011/03/c-go-cgo.html) | 1,583 |
64,143,930 | I'm trying to read a json file as a pandas dataframe and convert it to a numpy array:
```
sample.json = [[["1", "2"], ["3", "4"]], [["7", "8"], ["9", "10"]]]
-------------------------------------------------------------------
df = pd.read_json('sample.json', dtype=float)
data = df.to_numpy()
pr... | 2020/09/30 | [
"https://Stackoverflow.com/questions/64143930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14061296/"
] | Why not load the JSON file with the builtin `json` module and convert to a numpy array?
```
import json
import numpy as np
data = json.loads("""[[["1", "2"], ["3", "4"]], [["7", "8"], ["9", "10"]]]""")
np.array(data, dtype=float)
array([[[ 1., 2.],
[ 3., 4.]],
[[ 7., 8.],
[ 9., 10.]]])
`... | Your data is 3-dimensional, not 2-dimensional. DataFrames are 2-dimensional, so the only way that it can convert your `sample.json` to a dataframe is by having a 2-dimensional table containing 1-dimensional items.
The easiest is to skip the pandas part completely:
```
import json
with open('/home/robby/temp/sample.js... | 1,584 |
52,090,461 | I want to use firebase-admin on GAE.
So I installed firebase-admin following method.
<https://cloud.google.com/appengine/docs/standard/python/tools/using-libraries-python-27>
appengine\_config.py
```
from google.appengine.ext import vendor
# Add any libraries install in the "lib" folder.
vendor.add('lib')
```
req... | 2018/08/30 | [
"https://Stackoverflow.com/questions/52090461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8118439/"
] | The `firebase-admin` package [requires `six>=1.6.1`](http://%60https://github.com/firebase/firebase-admin-python/blob/master/setup.py#L45), so manually copying in version `1.11.0` to your app won't cause problems with that library.
However, you should ensure that the code in your app that you originally added the `six... | If there's a different version of a library in the lib directory and in the app.yaml, the one in the lib directory is the one which will be available to your app.
So, effectively, your app will be using six 1.11.0. You can verify that by logging `six.__version__` and see what version you get.
To avoid confusions, I wo... | 1,585 |
53,908,319 | Numbers that do not contain 4 convert just fine, but once number that contain 4 is tested, it does not convert properly.
I am new to python and I am struggling to see what was wrong in the code. The code for converting Arabic number to Roman numerals work for numbers that does not contain 4 in them. I have tried to te... | 2018/12/24 | [
"https://Stackoverflow.com/questions/53908319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10827443/"
] | Welcome to SO!
The problem is the way you are trying to define and change your variables. For example, this piece of code:
```
elif I == 4:
I == 0
IV == 1
```
should look like this instead:
```
elif I == 4:
I = 0
IV = 1
```
`==` is a boolean Operator that will return `True` if tw... | This converts any positive integer to roman numeral string:
```
def roman(num: int) -> str:
chlist = "VXLCDM"
rev = [int(ch) for ch in reversed(str(num))]
chlist = ["I"] + [chlist[i % len(chlist)] + "\u0304" * (i // len(chlist))
for i in range(0, len(rev) * 2)]
def period(p: int, ... | 1,586 |
33,797,793 | Here is part of program 'Trackbar as the Color Palette' in python which is include with opencv. I want to use it in c++.
My problem is the last line.
```
r = cv2.getTrackbarPos('R','image')
g = cv2.getTrackbarPos('G','image')
b = cv2.getTrackbarPos('B','image')
img[:] = [b,g,r]
```
Without this command I just have ... | 2015/11/19 | [
"https://Stackoverflow.com/questions/33797793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5580005/"
] | You probably want to set all pixels of the `CV_8UC3` image `img` to the color given by `b`, `g` and `r`;
You can do this in OpenCV like:
```
img.setTo(Vec3b(b, g, r));
```
or equivalently:
```
img.setTo(Scalar(b, g, r));
```
---
In your code you're missing basically all the important parts:
* the infinite loop... | I think, you are looking for std::for\_each(). This code is untested. It is intended to show the concept, It might contain bugs:
```
// color type - use whatever you have
using color = std::array<char, 3>;
// prepare image, wherever you get that from
auto img = std::vector<color>{width * height, color{{0x00, 0x00, 0x... | 1,591 |
36,308,537 | I am trying to create a variable in python with prefix as `list` and then number which will be generated dynamically in the script. For example
I am trying to have a list10 where list is the prefix and 10 is the number generated dynamically.
In TCL we give like
```
list${i}
```
Is there same way in python too? | 2016/03/30 | [
"https://Stackoverflow.com/questions/36308537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1336962/"
] | The pythonic way to do this would be to make a dictionary to store your lists with the generated names as the dictionary's keys:
```
d = {}
d['list1'] = [1, 2, 3]
d['list2'] = ['a', 'b', 'c']
```
EDIT: generate key names
You can create keys like this:
```
key = 'list' + str(1) # or whatever number you are using
d... | You can use `locals()`, `vars()`, or `globals()` and inject your variable name there. For eg.
```
>>> list10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'list10' is not defined
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'x': [], '_... | 1,592 |
5,882,362 | What is the difference between `thread.start_new_thread` and `threading.Thread.start` in python?
I have noticed that when `start_new_thread` is called, the new thread terminates as soon as the calling thread terminates. `threading.Thread.start` is the opposite: the calling thread waits for other threads to terminat... | 2011/05/04 | [
"https://Stackoverflow.com/questions/5882362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322419/"
] | The `thread` module is the low-level threading API of Python. Its direct usage isn't recommended, unless you really need to. The `threading` module is a high-level API, built on top of `thread`. The `Thread.start` method is actually implemented using `thread.start_new_thread`.
The `daemon` attribute of `Thread` must b... | See the [threading.Thread.daemon](http://docs.python.org/library/threading.html#threading.Thread.daemon) flag - basically whenever no non-daemon threads are running, the interpreter terminates. | 1,593 |
53,748,145 | I'm trying to containerize my django file, and I keep running into the issue:`(2006, ’Can\‘t connect to local MySQL server through socket \‘/var/run/mysqld/mysqld.sock\’ (2 “No such file or directory”)`
I found out later mysql.sock is in this location:`/tmp/mysql.sock` instead of `/var/run/mysqld/mysqld.sock`, how do ... | 2018/12/12 | [
"https://Stackoverflow.com/questions/53748145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10241176/"
] | Without external dependencies, you can use [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) to extract elements from `A` that don't have ids in `B` and `concat` that with `B`:
```js
const A = [{id: 1, name: 'x'}, {id: 2, name: 'y'}, {id: 3, name: 'z'}];
const B... | Since you are already using lodash, you can use `_.unionBy` which merges the arrays using a criterion by which uniqueness is computed:
```
let result = _.unionBy(B, A, "id");
```
Start with `B` before `A`, so that in case of duplicates, `B` values are taken instead of `A` ones.
**Example:**
```js
let A = [
{ id... | 1,594 |
55,577,893 | I want to run a recursive function in Numba, using nopython mode. Until now I'm only getting errors. This is a very simple code, the user gives a tuple with less than five elements and then the function creates another tuple with a new value added to the tuple (in this case, the number 3). This is repeated until the fi... | 2019/04/08 | [
"https://Stackoverflow.com/questions/55577893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2136601/"
] | There are several reasons why you shouldn't do that:
* This is generally a kind of approach that will likely be faster in pure Python than in a numba-decorated function.
* Iteration will be simpler and probably faster, however beware that concatenating tuples is generally an `O(n)` operation, even in numba. So the ove... | According to [this list of proposals](https://numba.pydata.org/numba-doc/latest/proposals/typing_recursion.html) in the current releases:
>
> Recursion support in numba is currently limited to self-recursion with
> explicit type annotation for the function. This limitation comes from
> the inability to determine th... | 1,599 |
65,770,185 | I try to make a python script that gets the dam occupancy rates from a website. Here is the code:
```
baraj_link = "https://www.turkiye.gov.tr/istanbul-su-ve-kanalizasyon-idaresi-baraj-doluluk-oranlari"
response = requests.get(baraj_link)
soup = BeautifulSoup(response.text, "lxml")
values_list = []
values = soup.find... | 2021/01/18 | [
"https://Stackoverflow.com/questions/65770185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14375618/"
] | ### Solution
For the descending order we multiply here by -1 each value in the array then sort the array and then multiply back with -1.
Ultimately we build the result string with string concatenation and print it out
```
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
... | Hope it will work as per your requirement->
```
public static void main(String[] args) {
Integer[] arr = {1,3,3,9,60 };
List<Integer> flat = Arrays.stream(arr).sorted((a, b) -> findfirst(b) - findfirst(a)).collect(Collectors.toList());
System.out.println(flat);
}
... | 1,600 |
30,207,041 | Been using the safe and easy confines of PyCharm for a bit now, but I'm trying to get more familiar with using a text editor and the terminal together, so I've forced myself to start using iPython Notebook and Emacs. Aaaaand I have some really dumb questions.
* after firing up ipython notebook from terminal with the c... | 2015/05/13 | [
"https://Stackoverflow.com/questions/30207041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4698759/"
] | * Yes, you can not use the same terminal. Solutions: open another terminal or run `ipython notebook` inside [`screen`](http://www.gnu.org/software/screen/manual/screen.html). If you use Windows you might want to take a look into [this question](https://stackoverflow.com/questions/5473384/terminal-multiplexer-for-micros... | * You can run your IPython notebook process in background.
On Unix platforms you can perform that with (note the leading `&`):
```
ipython notebook &
```
Or after a "normal" run, hit `[Control+z]` and run the `bg` command
([some lecture](http://web.mit.edu/gnu/doc/html/features_5.html)).
* you can convert `.ipynb`... | 1,606 |
44,813,375 | I am interested in the truth value of Python sets like `{'a', 'b'}`, or the empty set `set()` (which is not the same as the empty dictionary `{}`). In particular, I would like to know whether `bool(my_set)` is `False` if and only if the set `my_set` is empty.
Ignoring primitive (such as numerals) as well as user-defin... | 2017/06/28 | [
"https://Stackoverflow.com/questions/44813375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6867099/"
] | After looking at the source code for CPython, I would guess this is a documentation error, however, it could be implementation dependent and therefore would be a good issue to raise on the Python bug tracker.
Specifically, [object.c](https://github.com/python/cpython/blob/a66f9c6bb134561a24374f10e8c35417d356ce14/Objec... | That part of the docs is poorly written, or rather, poorly maintained. The following clause:
>
> instances of user-defined classes, if the class defines a `__bool__()` or `__len__()` method, when that method returns the integer zero or bool value False.
>
>
>
really applies to *all* classes, user-defined or not, ... | 1,607 |
59,063,829 | I tried to get a vector dot product in a nested list
For example :
```
A = np.array([[1,2,1,3],[2,1,2,3],[3,1,2,4]])
```
And I tried to get:
```
B = [[15], [19, 23]]
```
Where 15 = np.dot(A[0],A[1]),
19 = np.dot(A[0],A[2]),
23 = np.dot(A[1],A[2])
The fist inner\_list in B is the dot product of A[0] and A[1],
... | 2019/11/27 | [
"https://Stackoverflow.com/questions/59063829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10595338/"
] | Here is a explicit for loop coupled with list comprehension solution:
```
In [1]: import numpy as np
In [2]: A = np.array([[1,2,1,3],[2,1,2,3],[3,1,2,4]])
In [5]: def get_dp(A):
...: out = []
...: for i, a in enumerate(A[1:]):
...: out.append([np.dot(a, b) for b in A[:i+1]])
...: retu... | An iterator class that spits out elements same as B.
If you want the full list, you can `list(iter_dotprod(A))`
example:
```py
class iter_dotprod:
def __init__(self, nested_arr):
self.nested_arr = nested_arr
self.hist = []
def __iter__(self):
self.n = 0
return self
def _... | 1,610 |
64,799,010 | I am trying to get all ec2 instances details in a csv file, followed another post "https://stackoverflow.com/questions/62815990/export-aws-ec2-details-to-xlsx-csv-using-boto3-and-python". But was having attribute error for Instances. So I am trying this:
```
import boto3
import datetime
import csv
ec2 = ... | 2020/11/12 | [
"https://Stackoverflow.com/questions/64799010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14614887/"
] | Since you are using `DictWriter`, your `output` should be:
```
output = {
'Instancename': Instancename,
'Id': Id,
'State': State,
'Platform': str(Platform),
'InstanceType': InstanceType ,
'Launched': str(Lau... | A [`DictWriter`](https://docs.python.org/3/library/csv.html#csv.DictWriter) - as the name would suggest - writes `dicts` i.e. dictionaries to a CSV file. The dictionary must have the keys that correspond to the column names. See the example in the docs I linked.
In the code you posted, you are passing `output` - a str... | 1,611 |
72,842,182 | I am using flask with this code:
```py
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True, port=8000)
```
```html
<form method="GET">
<p>Phone number:</p>
<i... | 2022/07/02 | [
"https://Stackoverflow.com/questions/72842182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19409503/"
] | In most cases, if you are using `react-hook-form`, you don't need to track form fields with `useState` hook.
Using a `Controller` component is the right way to go. But there is a problem with `onChange` handler in your 1st method.
When you submit form, you are getting default date `null` because `field` is destructed... | I couldn't replicate your setup, but my guess is that in the first render the
reference to the 'setOriginalReleaseDate' is lost when being passed through the Controller's render arrow function.
```
...
onChange={(newValue) => {
setOriginalReleaseDate(newValue);
... | 1,612 |
48,399,812 | I have a python script that has to be executed with start and end dates. I want to execute this file for each day in the year 2012, so I thought a while-loop inside a bash script would do the job but my bash-skills are not sufficient.
This is what I tried:
```
day_start = 2012-01-01
while [ "$day_start" != 2013-01... | 2018/01/23 | [
"https://Stackoverflow.com/questions/48399812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7436993/"
] | Answer is simply stupid... Just restart your OS X. I don't know why, it looks like that operation system needs to rebuild some data after doing scenario from this question | Found submitted issue and solved it using the steps given here <https://github.com/desktop/desktop/issues/3625>
* Open Keychain Access.app
* Right click on login
* Click locking
* Click unlocking | 1,617 |
8,957,186 | >
> **Possible Duplicate:**
>
> [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator)
>
>
>
In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression.
For example,
```
return (i < x) ? i : x
```
This ... | 2012/01/21 | [
"https://Stackoverflow.com/questions/8957186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1162865/"
] | `a if b else c` syntax was introduced in Python 2.5. Most people have already upgraded to the recent version but in legacy code you may find another approach:
```
some_var = a<b and a or c
```
If you ever will be using this syntax remember that `a` must not evaluate to False. | Try this in Python:
```
return i if i < x else x
```
It's exactly the equivalent of the following expression in Java, C, C++ C#
```
return i < x ? i : x;
```
Read more about Python's [conditional expressions](http://docs.python.org/reference/expressions.html#conditional-expressions). | 1,618 |
44,781,806 | I seem to be breaking `tkinter` on linux by using some multi-threading. As far as I can see, I am managing to trigger a garbage collection on a thread which is not the main GUI thread. This is causing `__del__` to be run on a `tk.StringVar` instance, which tries to call the `tcl` stack from the wrong thread, causing ch... | 2017/06/27 | [
"https://Stackoverflow.com/questions/44781806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3403507/"
] | I had exactly the same problem
It was a nightmare to find the cause of the issue. I exaustivelly verified that no tkinter object was being called from any thread. I made a mechanism based in queues to handle tkinter objects in threads.
There are many examples on the web on how to do that, or... search for a module 'mt... | Tkinter is not thread safe. Calling Tkinter objects in a thread may cause things such as "The **del** method on Widget verifies that the Widget instance is being deleted from the other thread."
You can use locking and queues to make it done properly.
Check this example:
[Tkinter: How to use threads to preventing main... | 1,628 |
72,882,082 | Can someone explain me what is going on here and how to prevent this?
I have a **main.py** with the following code:
```python
import utils
import torch
if __name__ == "__main__":
# Foo
print("Foo")
# Bar
utils.bar()
model = torch.hub.load("ultralytics/yolov5", "yolov5s")
```
I outsourced some... | 2022/07/06 | [
"https://Stackoverflow.com/questions/72882082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4875142/"
] | It is not `DELETE * FROM`, but `DELETE FROM`.
```
DELETE FROM mlode WHERE kd >= DATE '2019-01-01';
``` | ```
BEGIN TRANSACTION
DELETE FROM [TABLE] WHERE [DATEFIELD] > DATEFROMPARTS(2018, 12, 30)
COMMIT TRANSACTION
``` | 1,629 |
19,699,314 | Below is my test code.
When running with python2.7 it shows that the program won't receive any signal until all spawned threads finish.
While with python3.2, only the main thread's sigintHandler gets called.
I'am confused with how python handles threads and signal, so how do I spawn a thread and do signal hand... | 2013/10/31 | [
"https://Stackoverflow.com/questions/19699314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922727/"
] | You can give like
```
$(this).datepicker({
"dateFormat": 'mm/dd/yy',
"changeMonth": true,
"changeYear": true,
"yearRange": year + ":" + year
});
``` | Read [yearRange](http://api.jqueryui.com/datepicker/#option-yearRange)
```
var year_text = year + ":" + year ;
```
or
```
"yearRange": year + ":" + year
``` | 1,630 |
48,577,536 | **Background**
I would like to do mini-batch training of "stateful" LSTMs in Keras. My input training data is in a large matrix "X" whose dimensions are m x n where
```python
m = number-of-subsequences
n = number-of-time-steps-per-sequence
```
Each row of X contains a subsequence which picks up where the subsequenc... | 2018/02/02 | [
"https://Stackoverflow.com/questions/48577536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4441470/"
] | You can set you ViewHolder class as [`inner`](https://kotlinlang.org/docs/reference/nested-classes.html) | Use the `companion object`:
```
class MyAdapter(private val dataList: ArrayList<String>) :
RecyclerView.Adapter<MyAdapter.ViewHolder>() {
class ViewHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener {
fun bindData() {
//some statements
}
override fun onClic... | 1,632 |
2,111,765 | totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I ... | 2010/01/21 | [
"https://Stackoverflow.com/questions/2111765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/256037/"
] | I can't reproduce your problem with a simple test:
```
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> group = u'Luleå'
>>> logging.warning('Group: %s', group)
WARNING:root:Group: Luleå
>>> logging.wa... | have you tried manually making any result unicode?
```
logging.debug(u'new groups %s' % unicode(list_of_groups("UTF-8"))
``` | 1,635 |
46,591,968 | im new to python and im failing to achieve this.
I have two lists of lists:
```
list1 = [['user1', 'id1'], ['user2', 'id2'], ['user3', 'id3']...]
list2 = [['id1', 'group1'], ['id1', 'group2'], ['id2', 'group1'], ['id2', 'group4']...]
```
And what i need is a single list like this:
```
[['user1','id1','group1'],['u... | 2017/10/05 | [
"https://Stackoverflow.com/questions/46591968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8419741/"
] | There's no such thing in python. There are methods for multidimensional arrays in `numpy`, but they are not really suitable for text.
Your second list functions as a dictionary, so make one
```
dict2 = {key:value for key, value in list2}
```
and then
```
new_list = [[a, b, dict2[b]] for a, b in list1]
``` | If you have to use lists of lists, you can use a comprehension to achieve this.
```
list1 = [['user1', 'id1'], ['user2', 'id2']]
list2 = [['id1', 'group1'], ['id1', 'group2'], ['id2', 'group1'], ['id2', 'group4']]
listOut = [[x[0],x[1],y[1]] for x in list1 for y in list2 if x[1] == y[0]]
output => [['user1', 'id1', ... | 1,645 |
57,660,887 | I just need contexts to be an Array ie., 'contexts' :[{}] instead of 'contexts':{}
Below is my python code which helps in converting python data-frame to required JSON format
This is the sample df for one row
```
name type aim context
xxx xxx specs 67646546 United States of America
data = {'e... | 2019/08/26 | [
"https://Stackoverflow.com/questions/57660887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11922956/"
] | I think this does it:
```
import pandas as pd
import json
df = pd.DataFrame([['xxx xxx','specs','67646546','United States of America']],
columns = ['name', 'type', 'aim', 'context' ])
data = {'entities':[]}
for key,grp in df.groupby('name'):
for idx, row in grp.iterrows():
temp_dic... | The problem is here in the following code
```
temp_dict_alpha = {'name':key,'type':row['type'],'data' :{'contexts':{'attributes':{},'context':{'dcountry':row['dcountry']}}}}
```
As you can see , you are already creating a `contexts` `dict` and assigning values to it. What you could do is something like this
```
... | 1,647 |
3,764,791 | Is there any fb tag i can use to wrap around my html anchor tag so that if the user isn't logged in, they will get prompted to login before getting access to the link?
I'm using python/django in backend.
Thanks,
David | 2010/09/21 | [
"https://Stackoverflow.com/questions/3764791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/225128/"
] | This is just an interpretation question, but I would say that you would take the decimal representation of a number, and count the total number of digits that are 6, 4, or 9. For example:
* 100 --> 0
* 4 --> 1
* 469 --> 3
* 444 --> 3
Get it now? | One interpretation - example:
Given `678799391`, the number of digits would be `0` for `4`, `1` for `6` and `3` for `9`. The sum of the occurences would be `0 + 1 + 3 = 4`. | 1,648 |
60,578,442 | When I tried to add value of language python3 returns error that this object is not JSON serializible.
models:
```
from django.db import models
from django.contrib.auth.models import AbstractUser, AbstractBaseUser
class Admin(AbstractUser):
class Meta(AbstractUser.Meta):
pass
class HahaUser(AbstractBas... | 2020/03/07 | [
"https://Stackoverflow.com/questions/60578442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13023793/"
] | The result of account.language is an instance. So, in your `registration_view`, data['language'] got an instance rather than string or number. That's the reason why data's language is not JSON serializable.
Based on your requirements, you can change it to
`data['language'] = account.language.name` | As exception says, `language` is an object of `Language` model and it's not a primitive type. So you should use some attributes of Language model like `language_id` or `language_name` instead of language object.
```py
from rest_framework import serializers
from main import models
class RegistrationSerializer(seriali... | 1,652 |
47,978,878 | Hi I am using APScheduler in a Django project. How can I plan a call of a function in python when the job is done? A callback function.
I store job as Django models in DB. As it completes, I want to mark it as `completed=1` in the table. | 2017/12/26 | [
"https://Stackoverflow.com/questions/47978878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4537090/"
] | The easiest and generic way to do it would be to add your callback function to the end of the scheduled job. You can also build on top of the scheduler class to include a self.function\_callback() at the end of the tasks.
Quick example:
```
def tick():
print('Tick! The time is: %s' % datetime.now())
time.slee... | [Listener](https://apscheduler.readthedocs.io/en/latest/userguide.html#scheduler-events) allows to hook various [events](https://apscheduler.readthedocs.io/en/latest/modules/events.html#event-codes) of APScheduler. I have succeeded to get the *next run time* of my job using EVENT\_JOB\_SUBMITTED.
(Updated)
I confirmed... | 1,655 |
1,780,066 | hopefully someone here can shed some light on my issue :D
I've been creating a Windows XP service in python that is designed to monitor/repair selected Windows/Application/Service settings, atm I have been focusing on default DCOM settings.
The idea is to backup our default configuration within another registry key f... | 2009/11/22 | [
"https://Stackoverflow.com/questions/1780066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94071/"
] | So I guess it's time to admit my stupidity.... :P
It turns out this was not a python issue, py2exe issue, nor a WMI issue. :(
This was more or less a simple permission issue. So simple I overlooked it for the better part of a month. :(
Rule of thumb, if you want to create a service that calls to specific registry ke... | I am not an expert at this, but here are my two cents worth:
[This article](http://www.firebirdsql.org/devel/python/docs/3.3.0/installation.html) tells me that you might need to be logged in as someone with the required target system permissions.
However, I find that a little excessive. Have you tried compiling your... | 1,656 |
69,153,402 | Lets say I have a list that references another list, as follows:
```
list1 = [1,2,3,4,5]
list2 = [list1[0], list1[1], list1[2]]
```
I wish to interact with list1 through list2, as follows:
```
list2[1] = 'a'
print(list1[1])
```
and that result should be 'a'.
Is this possible? Help me python geniuses | 2021/09/12 | [
"https://Stackoverflow.com/questions/69153402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14272990/"
] | What we do is not derive `ListOfSomething` from the list base class. We would make `ListOfSomething` the singleton and have a generic list class.
```cpp
class ListOfSomething
{
public:
static ListOfSomething& instance()
{
static ListOfSomething los;
return los;
}
// Obtain a reference to the ... | As explained by Bart, the trick here is to pass the name of the derived class as a template parameter. Here is the final form of the class that works as originally desired:
```
template <class T>
class ListOf<T>
{
public:
static T *method();
};
```
and you invoke it like this
```
class ListOfSomething : public Li... | 1,657 |
45,561,366 | I'm a beginner at video processing using python.
I have a raw video data captured from a camera and I need to check whether the video has bright or dark frames in it.
So far what I have achieved is I can read the raw video using numpy in python.
Below is my code.
```
import numpy as np
fd = open('my_video_file.raw... | 2017/08/08 | [
"https://Stackoverflow.com/questions/45561366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4680053/"
] | If you have colorfull frames with red, green and blue channels, i.e NxMx3 matrix then you can convert this matrix from RGB representation to HSV (Hue, Saturation, Value) representation which is also will be NxMx3 matrix. Then you can take Value page from this matrix, i.e. third channel of this matrix and calculate aver... | Just a little insight on your problem. (You might want to read up a little more on digital image representation, [e.g. here](http://pippin.gimp.org/image_processing/chap_dir.html)). The frames of your video are read in in `uint8` format, i.e. pixels are encoded with values ranging from 0 to 255.
In general, higher val... | 1,658 |
55,713,339 | I'm trying to implement the following formula in python for X and Y points
[](https://i.stack.imgur.com/Lv0au.png)
I have tried following approach
```
def f(c):
"""This function computes the curvature of the leaf."""
tt = c
n = (tt[0]*... | 2019/04/16 | [
"https://Stackoverflow.com/questions/55713339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5347207/"
] | You do not specify exactly what the structure of the parameter `pts` is. But it seems that it is a two-dimensional array where each row has two values `x` and `y` and the rows are the points in your curve. That itself is problematic, since [the documentation](https://docs.scipy.org/doc/numpy/reference/generated/numpy.g... | I think your problem is that x and y are arrays of double values.
The array x is the independent variable; I'd expect it to be sorted into ascending order. If I evaluate y[i], I expect to get the value of the curve at x[i].
When you call that numpy function you get an array of derivative values that are the same shap... | 1,659 |
2,344,712 | The hindrance we have to ship python is the large size of the standard library.
Is there a minimal python distribution or an easy way to pick and choose what we want from
the standard library?
The platform is linux. | 2010/02/26 | [
"https://Stackoverflow.com/questions/2344712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282368/"
] | If all you want is to get the minimum subset you need (rather than build an `exe` which would constrain you to Windows systems), use the standard library module [modulefinder](http://docs.python.org/library/modulefinder.html) to list all modules your program requires (you'll get all dependencies, direct and indirect). ... | Have you looked at [py2exe](http://www.py2exe.org/)? It provides a way to ship Python programs without requiring a Python installation. | 1,660 |
22,164,245 | I'm using a java program to split an array among histogram bins. Now, I want to manually label the histogram bins. So - I want to convert some thing like the sequence: {-0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.5,1,1.5,2,2.5,4} into the following image -
:
```
import matplotlib.pyplot as plt
d = [-0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.5,1,1.5,2,2.5,4]
hist(d)
plt.show()
```
As for putting special labels on the histogram, that's covered in the question: [Matplotlib - label each bin](https://stackoverflow.com/ques... | On the java side, an useful (and not too big) library could be GRAL <http://trac.erichseifert.de/gral/>
An histogram example is here:
<http://trac.erichseifert.de/gral/browser/gral-examples/src/main/java/de/erichseifert/gral/examples/barplot/HistogramPlot.java>
And specifically about axis rotation:
<http://www.erichs... | 1,663 |
35,050,766 | I am currently using Python and R together (using rmagic/rpy2) to help select different user input variables for a certain type of analysis.
I have read a csv file and created a dataframe in R. What I have also done is allowed the users to input a number of variables of which the names must match those in the header ... | 2016/01/28 | [
"https://Stackoverflow.com/questions/35050766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5849513/"
] | Consider having Python call the R script as child process via command line passing the string variables as arguments. In R, use the double bracket column reference to use strings:
**Python** Script *(using subprocess module)*
```
import subprocess
var_1 = 'age'
var_2 = 'sex'
Rfilename = '/path/to/SomeScript.R'
# B... | Yes it is possible:
```
var_1 <- "head(iris$Species)"
eval(parse(text=var_1))
# [1] setosa setosa setosa setosa setosa setosa
# Levels: setosa versicolor virginica
``` | 1,665 |
54,396,064 | I would like to ask how to exchange dates from loop in to an array in python?
I need an array of irregular, random dates with hours. So, I prepared a solution:
```
import datetime
import radar
r2 =()
for a in range(1,10):
r2 = r2+(radar.random_datetime(start='1985-05-01', stop='1985-05-04'),)
r3 = list(r2)
prin... | 2019/01/28 | [
"https://Stackoverflow.com/questions/54396064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10842659/"
] | You can convert the datetime to a string with [`str()`](https://docs.python.org/3/library/stdtypes.html#str) like:
### Code:
```
str(radar.random_datetime(start='1985-05-01', stop='1985-05-04'))
```
### Test Code:
```
import radar
r2 = ()
for a in range(1, 10):
r2 = r2 + (str(
radar.random_datetime(st... | Use [strftime](http://docs.python.org/2/library/time.html#time.strftime) to convert the date generated by radar before adding it to the list.
e.g.
```
import datetime
import radar
r2 =()
for a in range(1,10):
t=datetime.datetime(radar.random_datetime(start='1985-05-01', stop='1985-05-04'))
r2 = r2+(t.strftime('%Y-%m... | 1,666 |
23,086,078 | I have list that has 20 coordinates (x and y coordinates). I can calculate the distance between any two coordinates, but I have a hard time writing an algorithm that will iterate through the list and calculate the distance between the first node and every other node. for example,
```
ListOfCoordinates = [(1,2), (3,4)... | 2014/04/15 | [
"https://Stackoverflow.com/questions/23086078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3536195/"
] | Whenever you need something combinatorics-oriented ("I need first and second, then first and third, then...") chances are the `itertools` module has what you need.
```
from math import hypot
def distance(p1,p2):
"""Euclidean distance between two points."""
x1,y1 = p1
x2,y2 = p2
return hypot(x2 - x1, y... | ```
In [6]: l = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)]
In [7]: def distance(a, b):
return (a[0] - b[0], a[1] - b[1])
...:
In [8]: for m in l[1:]:
print(distance(l[0], m))
...:
(-2, -2)
(-4, -4)
(-6, -6)
(-8, -8)
(-10, -10)
```... | 1,667 |
74,180,904 | I am learning python and I am almost done with making tick tack toe but the code for checking if the game is a tie seems more complicated then it needs to be. is there a way of simplifying this?
```
if a1 != " " and a2 != " " and a3 != " " and b1 != " " and b2 != " " and b3 != " " and c1 != " " and c2 != " " and c... | 2022/10/24 | [
"https://Stackoverflow.com/questions/74180904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20321517/"
] | I think there is no implemented method in the SDK for that but after looking a bit, I found this one: [request](https://cloud.google.com/storage/docs/json_api/v1/objects/list#request)
You could try to execute an HTTP GET specifying the parameters (you can find an example of the use of parameters here: [query\_paramete... | By default the google API iterators manage page size for you. The RowIterator returns a single row by default, backed internally by fetched pages that rely on the backend to select an appropriate size.
If however you want to specify a fixed max page size, you can use the [`google.golang.org/api/iterator`](https://pkg.... | 1,670 |
18,004,605 | I got stuck on another part of this exercise. The program that is being coded allows you to drill phrases (It gives you a piece of code, you write out the English translation) and I'm confused on how the "convert" function works. Full code: <http://learnpythonthehardway.org/book/ex41.html>
```
def convert(snippet, phr... | 2013/08/01 | [
"https://Stackoverflow.com/questions/18004605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2640186/"
] | If it can help you,
```
class_names = [w.capitalize() for w in
random.sample(WORDS, snippet.count("%%%"))]
```
is equivalent to
```
class_names = []
for w in random.sample(WORDS, snippet.count("%%%")):
class_names.append(w.capitalize())
```
The .count() will return the number of occurence of "%%%... | `w.capitalize()` is like `.uppercase()`, but it only captilizes the first character. | 1,671 |
17,708,683 | I'm trying to deploy a Flask app on a Linode VPS running Ubuntu 10.10. I've been following this tutorial (<https://library.linode.com/web-servers/nginx/python-uwsgi/ubuntu-10.10-maverick#sph_configure-nginx>) but I keep getting a 502 Bad Gateway error.
Here this is /etc/default/uwsgi:
```
PYTHONPATH=/var/www/reframei... | 2013/07/17 | [
"https://Stackoverflow.com/questions/17708683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2193598/"
] | With `uwsgi_pass 127.0.0.1:9001;` you declared to Nginx your intent to talk to uWSGI through TCP socket, but have not warned uWSGI about it.
Try adding a corresponding socket line to your `/etc/default/uwsgi` file:
```
PYTHONPATH=/var/www/reframeit-im
MODULE=wsgi
socket=127.0.0.1:9001
``` | Please add "protocol = uwsgi" apart from what Flavio has suggested. As below
```
PYTHONPATH=/var/www/reframeit-im
MODULE=wsgi
socket=127.0.0.1:9001
protocol = uwsgi
``` | 1,672 |
66,996,147 | I have a python list that looks like this:
```
my_list = [2, 4, 1 ,0, 3]
```
My goal is to iterate over this list in a manner where the next index is the current value and then to append all the index in another list and then stop the iteration once a cycle is over. Hence,
>
> Starting from 0 it contains the value... | 2021/04/08 | [
"https://Stackoverflow.com/questions/66996147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1813039/"
] | A `while` loop is a better structure here; set `i` to point to the first element in `my_list` and then iterate until you find `i` in `new_list`:
```py
my_list = [2,4,1,0,3]
new_list = []
i = 0
while i not in new_list:
new_list.append(i)
i = my_list[i]
print(new_list)
```
Output:
```py
[0, 2, 1, 4, 3]
```... | You can try this. using variable swapping you can reassign rather than appending and creating a new variable
```
my_list = [2,4,1,0,3]
n= len(my_list)
for i in range(n-1):
for j in range(0,n-i-1):
if my_list[j] > my_list[j+1]:
my_list[j], my_list[j+1] = my_list[j+1],my_list[j]
print(my_list)
... | 1,673 |
35,132,569 | What I'm trying to do is build a regressor based on a value in a feature.
That is to say, I have some columns where one of them is more important (let's suppose it is `gender`) (of course it is different from the target value Y).
I want to say:
- If the `gender` is Male then use the randomForest regressor
- El... | 2016/02/01 | [
"https://Stackoverflow.com/questions/35132569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3497084/"
] | You might be able to implement your own regressor. Let us assume that `gender` is the first feature. Then you could do something like
```
class MyRegressor():
'''uses different regressors internally'''
def __init__(self):
self.randomForest = initializeRandomForest()
self.kNN = initializekNN()
... | I personally am new to Python but I would use the data type of a list. I would then proceed to making a membership check and reference the list you just wrote. Then proceed to say that if member = true then run/use randomForest regressor. If false use/run another regressor. | 1,674 |
60,873,608 | Need substition for using label/goto -used in languages like C,..- in python
So basically, I am a newb at python (and honestly, programming).I have been experimenting with super basic stuff and have hit a "roadblock".
```
print("Hello User!")
print("Welcome to your BMI Calculator.")
print("Please choose your system o... | 2020/03/26 | [
"https://Stackoverflow.com/questions/60873608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13130669/"
] | I don't recommend you start your programming career with `goto`, that's how you can get perfectly written `spaghetti code`.
Let's review your use case here, you want to go back to asking user if he did not gave you an expected input, why not use a loop instead of `goto`?
```
ans = "unexpected"
while(ans != "A" and an... | Put everything in 'while (true)' starting with first 'if' statement. And remove last 'else' statement. | 1,675 |
3,162,450 | I am looking for references (tutorials, books, academic literature) concerning structuring unstructured text in a manner similar to the google calendar quick add button.
I understand this may come under the NLP category, but I am interested only in the process of going from something like "Levi jeans size 32 A0b293"
... | 2010/07/01 | [
"https://Stackoverflow.com/questions/3162450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93580/"
] | You need to provide more information about the source of the text (the web? user input?), the domain (is it just clothes?), the potential formatting and vocabulary...
Assuming worst case scenario you need to start learning NLP. A very good free book is the documentation of NLTK: <http://www.nltk.org/book> . It is also... | Possibly look at "Collective Intelligence" by Toby Segaran. I seem to remember that addressing the basics of this in one chapter. | 1,676 |
68,890,393 | I'm trying to install a Python package called "mudes" on another server using terminal. When I want to install it using
```
pip install mudes
```
or
```
pip3 install mudes
```
, I get the following error:
```
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-hn4hol_z/spacy/
```
I ha... | 2021/08/23 | [
"https://Stackoverflow.com/questions/68890393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I had the same issue trying to install pycaret. I'm no expert so I don't know why but this work for me
```
pip3 install --upgrade pip
``` | The setuptools might be outdated. Try running this command first and see if it helps.
```
pip install --upgrade setuptools
``` | 1,681 |
46,510,770 | I'm kind of new to python and I need to run a script all day. However, the memory used by the script keeps increasing over time until python crashes... I've tried stuff but nothing works :( Maybe I'm doing something wrong I don't know. Here's what my code looks like :
```
while True:
try:
import functions and... | 2017/10/01 | [
"https://Stackoverflow.com/questions/46510770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8703130/"
] | The closest thing Xcode has is a button at the bottom of the project navigator to show only files with source-control status. Clicking the button shows files that have uncommitted changes.
[](https://i.stack.imgur.com/PmT8M.png) | As Mark answered you can filter all the modified files, after that don't forget to turn on **Comparison**, so you can see where the code got changed.
[](https://i.stack.imgur.com/Wmugd.png) | 1,683 |
58,854,194 | I'm getting the following error when using the [Microsoft Python Speech-to-Text Quickstart ("Quickstart: Recognize speech from an audio file")](https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/quickstarts/speech-to-text-from-file?tabs=linux&pivots=programming-language-python#sample-code) with t... | 2019/11/14 | [
"https://Stackoverflow.com/questions/58854194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908967/"
] | mp3-encoded audio is not supported as an input format. Please use a WAV(PCM) file with 16-bit samples, 16 kHz sample rate, and a single channel (Mono). | The default audio streaming format is WAV (16kHz or 8kHz, 16-bit, and mono PCM). Outside of WAV / PCM, the compressed input formats listed below are also supported.
However if you use C#/Java/C++/Objective C and if you want to use compressed audio formats such as **.mp3**, you can handle it by using **GStreamer**
Fo... | 1,684 |
10,865,483 | What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that:
```
+---------------------+-----------+---------+
| font | documents | domains |
+---------------------+-----------+---------+
|... | 2012/06/02 | [
"https://Stackoverflow.com/questions/10865483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986743/"
] | There is no need for an external library. The prints out the data with the column names. All lines with the 'columns' variable can be eliminated if you do not need the column names.
```
sql = "SELECT * FROM someTable"
cursor.execute(sql)
conn.commit()
results = cursor.fetchall()
widths = []
columns = []
tavnit = '|'
... | The data is in some list it seems, and are printing the header. Consider some formatting like this:
```
res = ['trebuchet ms', 8868, 417]
res = ['lucida sans unicode', 3525, 116]
```
and
```
print(' {0[0]:20s} {0[1]:10d} {0[2]:10d}'.format(res))
```
give you
```
trebuchet ms 8868 417
lucid... | 1,687 |
4,591,125 | I did several Boolean Comparisons:
```
>>> (True or False) is True
True
>>> (True or False) == True
True
```
It sounds like `==` and `is` are interchangeable for Boolean-values.
Sometimes it's more clear to use `is`
I want to know that:
Are `True` and `False` pre-allocated in python?
Is `bool(var)` always retur... | 2011/01/04 | [
"https://Stackoverflow.com/questions/4591125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348785/"
] | It seems that all answers deal with `True` and `False` as defined after an interpreter startup. Before booleans became part of Python they were often defined as part of a program. Even now (Python 2.6.6) they are only names that can be pointed to different objects:
```
>>> True = 1
>>> (2 > 1)
True
>>> (2 > 1) == True... | `==` and `is` are both comparison operators, which would return a boolean value - `True` or `False`. True has a numeric value of 1 and False has a numeric value of 0.
The operator `==` compare the values of two objects and objects compared are most often are the same types (int vs int, float vs float), If you compare ... | 1,697 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.