qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
70,026,043 | I'm trying to figure out why I'm getting this error message.
I'm running the webdriver.Chrome() with selenium in a Windows environment.
When I run:
```
driver.get("http://www.google.com")
```
Or any url for that matter, python returns an HTML doc to the terminal saying;
```
Access denied, your system policy has d... | 2021/11/18 | [
"https://Stackoverflow.com/questions/70026043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16909626/"
] | An alternative to using `upvar` is to use `set <var_name>` to retrieve the value of var\_name. When <var\_name> is `${mod}_sig`, then you can use `set` to retrieve the value of the variable without the possibility of altering the value of the original variable (like `upvar`)
```
set modules {moduleA moduleB moduleC}
... | This is where you want the [`upvar`](https://www.tcl-lang.org/man/tcl8.6/TclCmd/upvar.htm) command
to "alias" one variable to another.
```
set modules {moduleA moduleB moduleC}
set moduleA_sig {1 2 3 4}
set moduleB_sig {11 22 33 44}
set moduleC_sig {111 222 333 444}
foreach mod $modules {
upvar 0 ${mod}_sig this... |
70,026,043 | I'm trying to figure out why I'm getting this error message.
I'm running the webdriver.Chrome() with selenium in a Windows environment.
When I run:
```
driver.get("http://www.google.com")
```
Or any url for that matter, python returns an HTML doc to the terminal saying;
```
Access denied, your system policy has d... | 2021/11/18 | [
"https://Stackoverflow.com/questions/70026043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16909626/"
] | Another approach is to use an array (Or [dict](https://www.tcl.tk/man/tcl8.6/TclCmd/dict.html)) to hold values instead of trying to compose variable names on the fly at runtime.
Array:
```
#!/usr/bin/env tclsh
set modules {moduleA moduleB moduleC}
set sig(moduleA) {1 2 3 4}
set sig(moduleB) {11 22 33 44}
set sig(mo... | This is where you want the [`upvar`](https://www.tcl-lang.org/man/tcl8.6/TclCmd/upvar.htm) command
to "alias" one variable to another.
```
set modules {moduleA moduleB moduleC}
set moduleA_sig {1 2 3 4}
set moduleB_sig {11 22 33 44}
set moduleC_sig {111 222 333 444}
foreach mod $modules {
upvar 0 ${mod}_sig this... |
41,789,133 | Tensorflow r0.12's documentation for tf.nn.rnn\_cell.LSTMCell describes this as the init:
```
tf.nn.rnn_cell.LSTMCell.__call__(inputs, state, scope=None)
```
where `state` is as follows:
>
> state: if state\_is\_tuple is False, this must be a state Tensor, 2-D, batch x state\_size. If state\_is\_tuple is True, thi... | 2017/01/22 | [
"https://Stackoverflow.com/questions/41789133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5299052/"
] | I've stumbled upon same question, here's how I understand it! Minimalistic LSTM example:
```
import tensorflow as tf
sample_input = tf.constant([[1,2,3]],dtype=tf.float32)
LSTM_CELL_SIZE = 2
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(LSTM_CELL_SIZE, state_is_tuple=True)
state = (tf.zeros([1,LSTM_CELL_SIZE]),)*2
outp... | Maybe this excerpt from the code will help
```
def __call__(self, inputs, state, scope=None):
"""Long short-term memory cell (LSTM)."""
with vs.variable_scope(scope or type(self).__name__): # "BasicLSTMCell"
# Parameters of gates are concatenated into one multiply for efficiency.
if self._state_is_tuple:
... |
41,789,133 | Tensorflow r0.12's documentation for tf.nn.rnn\_cell.LSTMCell describes this as the init:
```
tf.nn.rnn_cell.LSTMCell.__call__(inputs, state, scope=None)
```
where `state` is as follows:
>
> state: if state\_is\_tuple is False, this must be a state Tensor, 2-D, batch x state\_size. If state\_is\_tuple is True, thi... | 2017/01/22 | [
"https://Stackoverflow.com/questions/41789133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5299052/"
] | I agree that the documentation is unclear. Looking at [`tf.nn.rnn_cell.LSTMCell.__call__`](https://github.com/tensorflow/tensorflow/blob/66d5d1fa0c192ca4c9b75cde216866805eb160f2/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py#L291-L382) clarifies (I took the code from TensorFlow 1.0.0):
```
def __call__(self, ... | Maybe this excerpt from the code will help
```
def __call__(self, inputs, state, scope=None):
"""Long short-term memory cell (LSTM)."""
with vs.variable_scope(scope or type(self).__name__): # "BasicLSTMCell"
# Parameters of gates are concatenated into one multiply for efficiency.
if self._state_is_tuple:
... |
41,789,133 | Tensorflow r0.12's documentation for tf.nn.rnn\_cell.LSTMCell describes this as the init:
```
tf.nn.rnn_cell.LSTMCell.__call__(inputs, state, scope=None)
```
where `state` is as follows:
>
> state: if state\_is\_tuple is False, this must be a state Tensor, 2-D, batch x state\_size. If state\_is\_tuple is True, thi... | 2017/01/22 | [
"https://Stackoverflow.com/questions/41789133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5299052/"
] | Maybe this excerpt from the code will help
```
def __call__(self, inputs, state, scope=None):
"""Long short-term memory cell (LSTM)."""
with vs.variable_scope(scope or type(self).__name__): # "BasicLSTMCell"
# Parameters of gates are concatenated into one multiply for efficiency.
if self._state_is_tuple:
... | <https://github.com/tensorflow/tensorflow/blob/r1.2/tensorflow/python/ops/rnn_cell_impl.py>
Line #308 - 314
class LSTMStateTuple(\_LSTMStateTuple):
"""Tuple used by LSTM Cells for `state_size`, `zero_state`, and output state.
Stores two elements: `(c, h)`, in that order.
Only used when `state_is_tuple=True`.
""" |
41,789,133 | Tensorflow r0.12's documentation for tf.nn.rnn\_cell.LSTMCell describes this as the init:
```
tf.nn.rnn_cell.LSTMCell.__call__(inputs, state, scope=None)
```
where `state` is as follows:
>
> state: if state\_is\_tuple is False, this must be a state Tensor, 2-D, batch x state\_size. If state\_is\_tuple is True, thi... | 2017/01/22 | [
"https://Stackoverflow.com/questions/41789133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5299052/"
] | I've stumbled upon same question, here's how I understand it! Minimalistic LSTM example:
```
import tensorflow as tf
sample_input = tf.constant([[1,2,3]],dtype=tf.float32)
LSTM_CELL_SIZE = 2
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(LSTM_CELL_SIZE, state_is_tuple=True)
state = (tf.zeros([1,LSTM_CELL_SIZE]),)*2
outp... | I agree that the documentation is unclear. Looking at [`tf.nn.rnn_cell.LSTMCell.__call__`](https://github.com/tensorflow/tensorflow/blob/66d5d1fa0c192ca4c9b75cde216866805eb160f2/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py#L291-L382) clarifies (I took the code from TensorFlow 1.0.0):
```
def __call__(self, ... |
41,789,133 | Tensorflow r0.12's documentation for tf.nn.rnn\_cell.LSTMCell describes this as the init:
```
tf.nn.rnn_cell.LSTMCell.__call__(inputs, state, scope=None)
```
where `state` is as follows:
>
> state: if state\_is\_tuple is False, this must be a state Tensor, 2-D, batch x state\_size. If state\_is\_tuple is True, thi... | 2017/01/22 | [
"https://Stackoverflow.com/questions/41789133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5299052/"
] | I've stumbled upon same question, here's how I understand it! Minimalistic LSTM example:
```
import tensorflow as tf
sample_input = tf.constant([[1,2,3]],dtype=tf.float32)
LSTM_CELL_SIZE = 2
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(LSTM_CELL_SIZE, state_is_tuple=True)
state = (tf.zeros([1,LSTM_CELL_SIZE]),)*2
outp... | <https://github.com/tensorflow/tensorflow/blob/r1.2/tensorflow/python/ops/rnn_cell_impl.py>
Line #308 - 314
class LSTMStateTuple(\_LSTMStateTuple):
"""Tuple used by LSTM Cells for `state_size`, `zero_state`, and output state.
Stores two elements: `(c, h)`, in that order.
Only used when `state_is_tuple=True`.
""" |
41,789,133 | Tensorflow r0.12's documentation for tf.nn.rnn\_cell.LSTMCell describes this as the init:
```
tf.nn.rnn_cell.LSTMCell.__call__(inputs, state, scope=None)
```
where `state` is as follows:
>
> state: if state\_is\_tuple is False, this must be a state Tensor, 2-D, batch x state\_size. If state\_is\_tuple is True, thi... | 2017/01/22 | [
"https://Stackoverflow.com/questions/41789133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5299052/"
] | I agree that the documentation is unclear. Looking at [`tf.nn.rnn_cell.LSTMCell.__call__`](https://github.com/tensorflow/tensorflow/blob/66d5d1fa0c192ca4c9b75cde216866805eb160f2/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py#L291-L382) clarifies (I took the code from TensorFlow 1.0.0):
```
def __call__(self, ... | <https://github.com/tensorflow/tensorflow/blob/r1.2/tensorflow/python/ops/rnn_cell_impl.py>
Line #308 - 314
class LSTMStateTuple(\_LSTMStateTuple):
"""Tuple used by LSTM Cells for `state_size`, `zero_state`, and output state.
Stores two elements: `(c, h)`, in that order.
Only used when `state_is_tuple=True`.
""" |
71,524,462 | I'm coding a little tool that displays the key presses on the screen with Tkinter, useful for screen recording.
**Is there a way to get a listener for all key presses of the system *globally* with Tkinter?** (for every keystroke including `F1`, `CTRL`, ..., even when the Tkinter window does not have the focus)
I curr... | 2022/03/18 | [
"https://Stackoverflow.com/questions/71524462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422096/"
] | **Solution 1**: if you need to catch keyboard events in your current window, you can use:
```
from tkinter import *
def key_press(event):
key = event.char
print(f"'{key}' is pressed")
root = Tk()
root.geometry('640x480')
root.bind('<Key>', key_press)
mainloop()
```
**Solution 2**: if you want to capture ke... | As suggested in [tkinter using two keys at the same time](https://stackoverflow.com/questions/39606019/tkinter-using-two-keys-at-the-same-time), you can detect all key pressed at the same time with the following:
```py
history = []
def keyup(e):
print(e.keycode)
if e.keycode in history :
history.pop(... |
56,600,918 | When you call DataFrame.to\_numpy(), pandas will find the NumPy dtype that can hold all of the dtypes in the DataFrame. But how to perform the reverse operation?
I have an 'numpy.ndarray' object 'pred'. It looks like this:
>
> [[0.00599913 0.00506044 0.00508315 ... 0.00540191 0.00542058 0.00542058]]
>
>
>
I am t... | 2019/06/14 | [
"https://Stackoverflow.com/questions/56600918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11376406/"
] | `pred` is an `ndarray`. It does not have a `to_csv` method. That's something a `pandas` `DataFrame` has.
But lets look at the first stuff.
Copying your array display, adding commas, lets me make a list:
```
In [1]: alist = [[0.00599913, 0.00506044, 0.00508315, 0.00540191, 0.00542058, 0.
...: 00542058]] ... | ```py
import numpy as np
import pandas as pd
x = [1,2,3,4,5,6,7]
x = np.array(x)
y = pd.Series(x)
print(y)
y.to_csv('a.csv')
``` |
56,600,918 | When you call DataFrame.to\_numpy(), pandas will find the NumPy dtype that can hold all of the dtypes in the DataFrame. But how to perform the reverse operation?
I have an 'numpy.ndarray' object 'pred'. It looks like this:
>
> [[0.00599913 0.00506044 0.00508315 ... 0.00540191 0.00542058 0.00542058]]
>
>
>
I am t... | 2019/06/14 | [
"https://Stackoverflow.com/questions/56600918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11376406/"
] | You can solve the issue with one line of code to convert ndarray to pandas df and then to csv file.
```
pd.DataFrame(X_train_res).to_csv("x_train_smote_oversample.csv")
``` | `pred` is an `ndarray`. It does not have a `to_csv` method. That's something a `pandas` `DataFrame` has.
But lets look at the first stuff.
Copying your array display, adding commas, lets me make a list:
```
In [1]: alist = [[0.00599913, 0.00506044, 0.00508315, 0.00540191, 0.00542058, 0.
...: 00542058]] ... |
56,600,918 | When you call DataFrame.to\_numpy(), pandas will find the NumPy dtype that can hold all of the dtypes in the DataFrame. But how to perform the reverse operation?
I have an 'numpy.ndarray' object 'pred'. It looks like this:
>
> [[0.00599913 0.00506044 0.00508315 ... 0.00540191 0.00542058 0.00542058]]
>
>
>
I am t... | 2019/06/14 | [
"https://Stackoverflow.com/questions/56600918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11376406/"
] | You can solve the issue with one line of code to convert ndarray to pandas df and then to csv file.
```
pd.DataFrame(X_train_res).to_csv("x_train_smote_oversample.csv")
``` | ```py
import numpy as np
import pandas as pd
x = [1,2,3,4,5,6,7]
x = np.array(x)
y = pd.Series(x)
print(y)
y.to_csv('a.csv')
``` |
56,651,258 | I am trying to install the **owlready2** lib in Ubuntu by following the method below but I face a problem.
* I updated the system and applications
* Installed Python 3 and made it the working version (default)
* Installed pip3
* Used pip and pip3 to install the owlready2 lib
But I faced the below problem which seems ... | 2019/06/18 | [
"https://Stackoverflow.com/questions/56651258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5851759/"
] | Try to install your package with the following command:
```
python3 -m pip install -I owlready2
```
If pip3 does not work, you also install Owlready2 manually : download the sources, then run in a terminal:
```
cd /path/to/Owlready2
python setup.py build
python setup.py install # as root
```
Also, that would b... | I encountered the same problem.
It seems that the issue might lie in something that was added in version 0.14 (at the time of writing the newest version is 0.19). If the owlready2 version is newer than 0.13 then you will encounter the problem.
I have tested these Python versions - 3.7.3 (works), 3.6.8(works), 3.5.2... |
12,199,819 | I'm a beginner programmer, and i've been trying to use the python markdown library in my web app. everything works fine, except the nl2br extension.
When I tried to convert text file to html using md.convert(text), it doesn't see to convert newlines to `<br>`.
for example, before I convert, the text is:
```
Puerto R... | 2012/08/30 | [
"https://Stackoverflow.com/questions/12199819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1623886/"
] | Try adding two or more white spaces at the end of a line to insert `<br/>` tags
Example:
```
hello
world
```
results in
```
<p>hello <br>
world</p>
```
Notice that there are two spaces after the word hello. This only works if you have some text before the two spaces at the end of a line. But this has nothing t... | Found this question looking for a clarification myself. Hence adding an update despite being 7 years late.
---
Reference thread on the Python Markdown Project: <https://github.com/Python-Markdown/markdown/issues/707>
Turns out that this is indeed the expected behaviour, and hence, the `nl2br` extension converts onl... |
44,548,111 | I am working on a **SaaS** solution currently provisioning **sonarqube and gerrit** applications on kubernetes.
As part of that I want to create a new schema in my postgres database for every new application that I provision. Application is connecting using following connection string, (i.e., instance1, instance2, ins... | 2017/06/14 | [
"https://Stackoverflow.com/questions/44548111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4189388/"
] | for those kind of operation it would be better to use collections,
the method [removeAll()](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#removeAll-java.util.Collection-) will filter the data containers, from the doc:
>
> Removes from this list all of its elements that are contained in the
> specifi... | You may try this:
```
a.removeAll(b);
``` |
44,548,111 | I am working on a **SaaS** solution currently provisioning **sonarqube and gerrit** applications on kubernetes.
As part of that I want to create a new schema in my postgres database for every new application that I provision. Application is connecting using following connection string, (i.e., instance1, instance2, ins... | 2017/06/14 | [
"https://Stackoverflow.com/questions/44548111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4189388/"
] | for those kind of operation it would be better to use collections,
the method [removeAll()](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#removeAll-java.util.Collection-) will filter the data containers, from the doc:
>
> Removes from this list all of its elements that are contained in the
> specifi... | Simply parse the second list and add unique elements to the first, delete others.
```
for (Integer elem : secondList)
if (firstList.contains(elem))
firstList.remove(elem);
else
firstList.add(elem);
```
In `firstList` you will have the values present only in one of the lists. |
44,548,111 | I am working on a **SaaS** solution currently provisioning **sonarqube and gerrit** applications on kubernetes.
As part of that I want to create a new schema in my postgres database for every new application that I provision. Application is connecting using following connection string, (i.e., instance1, instance2, ins... | 2017/06/14 | [
"https://Stackoverflow.com/questions/44548111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4189388/"
] | for those kind of operation it would be better to use collections,
the method [removeAll()](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#removeAll-java.util.Collection-) will filter the data containers, from the doc:
>
> Removes from this list all of its elements that are contained in the
> specifi... | Simple solution is to calculate the intersection and remove that from the desired list. If you only want what is missing, you can optimize this a little by going a solution like ΦXocę 웃 Пepeúpa ツ.
The great thing about this solution is that you can easily expand this to use 3+ sets/lists. Instead of A-B = diff or A-I(... |
44,548,111 | I am working on a **SaaS** solution currently provisioning **sonarqube and gerrit** applications on kubernetes.
As part of that I want to create a new schema in my postgres database for every new application that I provision. Application is connecting using following connection string, (i.e., instance1, instance2, ins... | 2017/06/14 | [
"https://Stackoverflow.com/questions/44548111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4189388/"
] | Simple solution is to calculate the intersection and remove that from the desired list. If you only want what is missing, you can optimize this a little by going a solution like ΦXocę 웃 Пepeúpa ツ.
The great thing about this solution is that you can easily expand this to use 3+ sets/lists. Instead of A-B = diff or A-I(... | You may try this:
```
a.removeAll(b);
``` |
44,548,111 | I am working on a **SaaS** solution currently provisioning **sonarqube and gerrit** applications on kubernetes.
As part of that I want to create a new schema in my postgres database for every new application that I provision. Application is connecting using following connection string, (i.e., instance1, instance2, ins... | 2017/06/14 | [
"https://Stackoverflow.com/questions/44548111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4189388/"
] | Simple solution is to calculate the intersection and remove that from the desired list. If you only want what is missing, you can optimize this a little by going a solution like ΦXocę 웃 Пepeúpa ツ.
The great thing about this solution is that you can easily expand this to use 3+ sets/lists. Instead of A-B = diff or A-I(... | Simply parse the second list and add unique elements to the first, delete others.
```
for (Integer elem : secondList)
if (firstList.contains(elem))
firstList.remove(elem);
else
firstList.add(elem);
```
In `firstList` you will have the values present only in one of the lists. |
70,545,797 | I have this image for a treeline crop. I need to find the general direction in which the crop is aligned. I'm trying to get the Hough lines of the image, and then find the mode of distribution of angles.[](https://i.stack.imgur.com/8GWAX.jpg)
I've been following [t... | 2021/12/31 | [
"https://Stackoverflow.com/questions/70545797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15230180/"
] | You can use a **2D FFT** to find the general direction in which the crop is aligned (as proposed by mozway in the comments). The idea is that the general direction can be easily extracted from *centred beaming rays appearing in the magnitude spectrum* when the input contains many lines in the same direction. You can fi... | Just for completeness I would like to post the Sobel Gradient Angle way as well.
General idea:
1. for every pixel, compute X and Y gradient (e.g. with Sobel)
2. Compute the angle from the X and Y gradient information and their distribution
3. find the modes e.g. with a histogram and select the highest one
Written in... |
10,308,340 | I have a list of rules for a given input file for my function. If any of them are violated in the file given, I want my program to return an error message and quit.
* Every gene in the file should be on the same chromosome
Thus for a lines such as:
NM\_001003443 chr11 + 5997152 5927598 5921052 5926098 1 5928752,5925... | 2012/04/25 | [
"https://Stackoverflow.com/questions/10308340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1348509/"
] | Just read the file and have a while loop check each line to make sure it contains `chr11`. There are string functions to search for substrings in a string. As soon as you find a line that returns false (does not contain `chr11`) then break out of the loop and set a flag `valid = false`.
```
import re
fp = open(infile... | Is it safe to assume that the first chr is the correct one? If so, use this:
```
import re
chrlist = re.findall("chr[0-9]+", open('file').read())
# ^ this is a list with all chr(whatever numbers)
for chr in chrlist:
if chr != chrlist[0]
print("Chr does not match")
break
``` |
10,308,340 | I have a list of rules for a given input file for my function. If any of them are violated in the file given, I want my program to return an error message and quit.
* Every gene in the file should be on the same chromosome
Thus for a lines such as:
NM\_001003443 chr11 + 5997152 5927598 5921052 5926098 1 5928752,5925... | 2012/04/25 | [
"https://Stackoverflow.com/questions/10308340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1348509/"
] | Just read the file and have a while loop check each line to make sure it contains `chr11`. There are string functions to search for substrings in a string. As soon as you find a line that returns false (does not contain `chr11`) then break out of the loop and set a flag `valid = false`.
```
import re
fp = open(infile... | My solution uses a "match group" to collect the matched numbers from the "chr" string.
```
import re
pat = re.compile(r'\schr(\d+)\s')
def chr_val(line):
m = re.search(pat, line)
if m is not None:
return m.group(1)
else:
return ''
def is_valid(f):
line = f.readline()
v = chr_val(... |
10,308,340 | I have a list of rules for a given input file for my function. If any of them are violated in the file given, I want my program to return an error message and quit.
* Every gene in the file should be on the same chromosome
Thus for a lines such as:
NM\_001003443 chr11 + 5997152 5927598 5921052 5926098 1 5928752,5925... | 2012/04/25 | [
"https://Stackoverflow.com/questions/10308340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1348509/"
] | Is it safe to assume that the first chr is the correct one? If so, use this:
```
import re
chrlist = re.findall("chr[0-9]+", open('file').read())
# ^ this is a list with all chr(whatever numbers)
for chr in chrlist:
if chr != chrlist[0]
print("Chr does not match")
break
``` | My solution uses a "match group" to collect the matched numbers from the "chr" string.
```
import re
pat = re.compile(r'\schr(\d+)\s')
def chr_val(line):
m = re.search(pat, line)
if m is not None:
return m.group(1)
else:
return ''
def is_valid(f):
line = f.readline()
v = chr_val(... |
71,186,021 | I´m new into python, so I apreciate any help.
I´m trying to develope a code that can search for a specific word in a csv file, but I don´t why he doesn´t recognize a word that I know it is in the program. I'm always getting "Não encontrei".
My code:
```
#Definir perfis
def pilar():
pilar = input("Perfil do pilar... | 2022/02/19 | [
"https://Stackoverflow.com/questions/71186021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | An enum without associated values conforms implicitly to Equatable **and** Hashable.
From the documentation:
[Hashable](https://developer.apple.com/documentation/swift/hashable/)
>
> When you define an enumeration without associated values, it gains Hashable conformance automatically, and you can add Hashable confo... | To chime in:
If you *did* want to implement `==` yourself, the way to do it would be with pattern matching. Surprisingly (to me), the code below seems to call neither `~=` nor `==`.
```
enum TestEnum: Equatable {
case one, two, three, four, five
static func ==(lhs: TestEnum, rhs: TestEnum) -> Bool {
... |
66,396,659 | I am using imbalanced dataset(54:38:7%) with RFECV for feature selection like this:
```
# making a multi logloss metric
from sklearn.metrics import log_loss, make_scorer
log_loss_rfe = make_scorer(score_func=log_loss, greater_is_better=False)
# initiating Light GBM classifier
lgb_rfe = LGBMClassifier(objective='multi... | 2021/02/27 | [
"https://Stackoverflow.com/questions/66396659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11814996/"
] | Log-loss needs the probability predictions, not the class predictions, so you should add
```py
log_loss_rfe = make_scorer(score_func=log_loss, needs_proba=True, greater_is_better=False)
```
The error is because without that, the passed `y_pred` is one-dimensional (classes 0,1,2) and `sklearn` [assumes it's a binary ... | Consider applying *stratified* cross-validation, which will try to preserve the fraction of samples for each class. Experiment with one of these scikit-learn cross-validators:
[`sklearn.model_selection.StratifiedKFold`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html?highl... |
73,251,418 | I'd like to filter a `df` by date. But I would like all the values with any date before today's date (python).
For example from the table below, I'd like the rows that have a date before today's date (i.e. row 1 to row 3).
| ID | date |
| --- | --- |
| 1 | 2022-03-25 06:00:00 |
| 2 | 2022-04-25 06:00:00 |
| 3 | 2022-... | 2022/08/05 | [
"https://Stackoverflow.com/questions/73251418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18028924/"
] | You can try this?
```
from datetime import datetime
df[df['date'] < datetime.now()]
```
Output:
```
ID date
0 1 2022-03-25 06:00:00
1 2 2022-04-25 06:00:00
2 3 2022-05-25 06:00:00
``` | This will work
```
#convert column to datetime object
df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True, errors='coerce')
#filter column
df.loc[df['date'] < datetime.now()]
``` |
40,780,004 | What's the result of returning `NotImplemented` from `__eq__` special method in python 3 (well 3.5 if it matters)?
The documentation isn't clear; the [only relevant text I found](https://docs.python.org/3/library/constants.html#NotImplemented) only vaguely refers to "some other fallback":
>
> When `NotImplemented` i... | 2016/11/24 | [
"https://Stackoverflow.com/questions/40780004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/336527/"
] | Actually the `==` and `!=` check work identical to the ordering comparison operators (`<` and similar) except that they don't raise the **appropriate exception** but fall-back to identity comparison. That's the only difference.
This can be easily seen in the [CPython source code (version 3.5.10)](https://github.com/py... | Not sure where (or if) it is in the docs, but the basic behavior is:
* try the operation: `__eq__(lhs, rhs)`
* if result is not `NotImplemented` return it
* else try the reflected operation: `__eq__(rhs, lhs)`
* if result is not `NotImplemented` return it
* otherwise use appropriate fall back:
eq -> same objects? -> ... |
16,480,625 | A variable `AA` is in `aaa.py`. I want to use this variable in my other python file `bbb.py`
How do I access this variable? | 2013/05/10 | [
"https://Stackoverflow.com/questions/16480625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351602/"
] | You're looking for [modules!](http://docs.python.org/2/tutorial/modules.html)
In `aaa.py`:
```
AA = 'Foo'
```
In `bbb.py`:
```
import aaa
print aaa.AA # Or print(aaa.AA) for Python 3
# Prints Foo
```
Or this works as well:
```
from aaa import AA
print AA
# Prints Foo
``` | You can import it; this will execute the whole script though.
```
from aaa import AA
``` |
16,480,625 | A variable `AA` is in `aaa.py`. I want to use this variable in my other python file `bbb.py`
How do I access this variable? | 2013/05/10 | [
"https://Stackoverflow.com/questions/16480625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351602/"
] | You can import it; this will execute the whole script though.
```
from aaa import AA
``` | Although importing is the best approach (like poke or Haidro wrote), here is another workaround, if you're generating data with one script and want to access them in another, without executing "`bbb.py`". So if you're dealing with large lists/dicts, this approach works well, although it's an overkill if you simply tryi... |
16,480,625 | A variable `AA` is in `aaa.py`. I want to use this variable in my other python file `bbb.py`
How do I access this variable? | 2013/05/10 | [
"https://Stackoverflow.com/questions/16480625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351602/"
] | You're looking for [modules!](http://docs.python.org/2/tutorial/modules.html)
In `aaa.py`:
```
AA = 'Foo'
```
In `bbb.py`:
```
import aaa
print aaa.AA # Or print(aaa.AA) for Python 3
# Prints Foo
```
Or this works as well:
```
from aaa import AA
print AA
# Prints Foo
``` | In your file `bbb.py`, add the following:
```
import sys
sys.path.append("/path/to/aaa.py/folder/")
from aaa import AA
```
Also would suggest reading more about Python modules and how `import` works. [Official Documentation on Modules.](http://docs.python.org/2/tutorial/modules.html) |
16,480,625 | A variable `AA` is in `aaa.py`. I want to use this variable in my other python file `bbb.py`
How do I access this variable? | 2013/05/10 | [
"https://Stackoverflow.com/questions/16480625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351602/"
] | In your file `bbb.py`, add the following:
```
import sys
sys.path.append("/path/to/aaa.py/folder/")
from aaa import AA
```
Also would suggest reading more about Python modules and how `import` works. [Official Documentation on Modules.](http://docs.python.org/2/tutorial/modules.html) | Although importing is the best approach (like poke or Haidro wrote), here is another workaround, if you're generating data with one script and want to access them in another, without executing "`bbb.py`". So if you're dealing with large lists/dicts, this approach works well, although it's an overkill if you simply tryi... |
16,480,625 | A variable `AA` is in `aaa.py`. I want to use this variable in my other python file `bbb.py`
How do I access this variable? | 2013/05/10 | [
"https://Stackoverflow.com/questions/16480625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351602/"
] | You're looking for [modules!](http://docs.python.org/2/tutorial/modules.html)
In `aaa.py`:
```
AA = 'Foo'
```
In `bbb.py`:
```
import aaa
print aaa.AA # Or print(aaa.AA) for Python 3
# Prints Foo
```
Or this works as well:
```
from aaa import AA
print AA
# Prints Foo
``` | Although importing is the best approach (like poke or Haidro wrote), here is another workaround, if you're generating data with one script and want to access them in another, without executing "`bbb.py`". So if you're dealing with large lists/dicts, this approach works well, although it's an overkill if you simply tryi... |
54,849,211 | I have two lists:
```
providers = ["a", "b", "c", "d", "e"]
ips = ["100.12.23.34", "199.134.3.01", "123.143.2.34", "154.234.4.66"]
```
I want the output to look like:
```
[{'provider_name':'a', 'server':'100.12.23.34'},.....]
```
How do i do this in python using for loop? | 2019/02/24 | [
"https://Stackoverflow.com/questions/54849211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11082580/"
] | Here is an easy to follow solution. For more reading on the zip method if necessary [click here](https://www.programiz.com/python-programming/methods/built-in/zip).
```
new = []
for i, j in zip(providers, ips):
new.append({"provider_name": i, "server": j})
``` | Use:
```
>>> providers = ["a", "b", "c", "d", "e"]
>>> ips = ["100.12.23.34", "199.134.3.01", "123.143.2.34", "154.234.4.66"]
>>> [{'provider_name':x, 'server':y} for x,y in zip(providers,ips)]
[{'provider_name': 'a', 'server': '100.12.23.34'}, {'provider_name': 'b', 'server': '199.134.3.01'}, {'provider_name': 'c', '... |
54,849,211 | I have two lists:
```
providers = ["a", "b", "c", "d", "e"]
ips = ["100.12.23.34", "199.134.3.01", "123.143.2.34", "154.234.4.66"]
```
I want the output to look like:
```
[{'provider_name':'a', 'server':'100.12.23.34'},.....]
```
How do i do this in python using for loop? | 2019/02/24 | [
"https://Stackoverflow.com/questions/54849211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11082580/"
] | Here is an easy to follow solution. For more reading on the zip method if necessary [click here](https://www.programiz.com/python-programming/methods/built-in/zip).
```
new = []
for i, j in zip(providers, ips):
new.append({"provider_name": i, "server": j})
``` | Option without any zip:
```
providers = ["a", "b", "c", "d", "e"]
ips = ["100.12.23.34", "199.134.3.01", "123.143.2.34", "154.234.4.66"]
[ {'provider_name': providers[i], 'server': ips[i] } for i in range(len(ips)) ]
``` |
56,022,332 | I have been trying to upload a Pandas dataframe to a JSON object in Cloud Storage using Cloud Function. Follwing is my code -
```
def upload_blob(bucket_name, source_file_name, destination_blob_name):
"""Uploads a file to the bucket."""
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucke... | 2019/05/07 | [
"https://Stackoverflow.com/questions/56022332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4853331/"
] | You are passing a string to [blob.upload\_from\_file()](https://googleapis.github.io/google-cloud-python/latest/storage/blobs.html#google.cloud.storage.blob.Blob.upload_from_file), but this method requires a file object. You probably want to use [blob.upload\_from\_filename()](https://googleapis.github.io/google-cloud-... | Use a bucket object instead of string
something like `upload_blob(conn.get_bucket(mybucket),'/tmp/abc.json','abc.json')}` |
39,040,250 | I have scraped a website with scrapy and stored the data in a json file.
Link to the json file: <https://drive.google.com/file/d/0B6JCr_BzSFMHLURsTGdORmlPX0E/view?usp=sharing>
But the json isn't standard json and gives errors:
```
>>> import json
>>> with open("/root/code/itjuzi/itjuzi/investorinfo.json") as file:... | 2016/08/19 | [
"https://Stackoverflow.com/questions/39040250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2672481/"
] | try this:
```
import json
with open('data.json') as data_file:
data = json.load(data_file)
```
This has the advantage of dealing well with large JSON files that do not fit in memory
EDIT:
Your data is not valid JSON.
Delete the following in the first 3 lines and it will validate:
```
[{
"website": ["\u5341... | Try following codes: (you are missing one something)
```
>>> import json
>>> with open("/root/code/itjuzi/itjuzi/investorinfo.json") as file:
... data = json.load(file.read())
``` |
5,852,199 | I'm writing a web application (<http://www.checkio.org/>) which allows users to write python code. As one feedback metric among many, I'd like to enable profiling while running checks on this code. This is to allow users to get a very rough idea of the relative efficiency of various solutions.
I need the profile to b... | 2011/05/01 | [
"https://Stackoverflow.com/questions/5852199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146821/"
] | Python's standard profiler module provides [deterministic profiling](http://docs.python.org/library/profile.html#what-is-deterministic-profiling). | I also suggest giving a try to yappi. (http://code.google.com/p/yappi/) In v0.62, it supports CPU time profiling and you can stop the profiler at any time you want... |
45,363,629 | Let's say I have a list l1 = [a,b,c,d,e] and I want to map it to a dictionary that would contain the following {a:1, b:2, c:3, d:4, e:5}
I know how to do it in a very naive way, but I would like something more 'pythonic'
The naive way:
```
dic = {}
j = 1
for i in list1:
dic[i] = j
j += 1
``` | 2017/07/28 | [
"https://Stackoverflow.com/questions/45363629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4369996/"
] | How about using a dictionary comprehension:
```
>>> {v: k for k, v in enumerate(l1, 1)}
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
``` | Just to make up for the flub earlier... You can use the `dict` type constructor with `itertools.count` and `zip`:
```
>>> L1 = ['a','b','c','d']
>>> from itertools import count
>>> dict(zip(L1, count(1)))
{'c': 3, 'b': 2, 'a': 1, 'd': 4}
``` |
65,056,382 | I created a script that runs perfectly fine in visual studio code but I'm now trying to automate the script, which is proving to be a little tricky. I've turned the file into a Unix executable file for the automation but when I click on my script, the code that I’ve implemented doesn’t do what I want it to.
I’ve got a... | 2020/11/29 | [
"https://Stackoverflow.com/questions/65056382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You just need to escape the backslash `\`, so it turns into two backslashes `\\`
```js
console.log(JSON.parse('{"x":"Hello \\" test"}'))
``` | ```js
let mydata = `{"x":"Hello \" test "}`
let escapeJsonFunc = function(str) {
return str.replace(/\\/g,'\\');
};
console.log( escapeJsonFunc(mydata) )
``` |
57,728,801 | I have a large (around 200Mb) single-line json file and I want to convert this to a more readable multi-line json (or txt) file.
I tried to open the file with text editors like sublime text and it takes forever to open. So, I would like to make the conversion without opening the file.
Therefore, I cannot use the int... | 2019/08/30 | [
"https://Stackoverflow.com/questions/57728801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8889727/"
] | The simplest method would be using `jq` to pretty print the json:
```
jq . myjsonfile.json > pretty.json
```
But from the python output, I suspect the json file may be ill-formed. | if you can identify a character sequence that ends a line (e.g. a curly bracket followed by a semicolon) you can use sed for it
```
$ sed 's/};/\n/g' <<< "my};test};string"
my
test
string
``` |
57,728,801 | I have a large (around 200Mb) single-line json file and I want to convert this to a more readable multi-line json (or txt) file.
I tried to open the file with text editors like sublime text and it takes forever to open. So, I would like to make the conversion without opening the file.
Therefore, I cannot use the int... | 2019/08/30 | [
"https://Stackoverflow.com/questions/57728801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8889727/"
] | The simplest method would be using `jq` to pretty print the json:
```
jq . myjsonfile.json > pretty.json
```
But from the python output, I suspect the json file may be ill-formed. | alternatively, you can use [**`jtc`**](https://github.com/ldn-softdev/jtc) unix utility to pretty-print your one-liner json:
```
jtc myjsonfile.json
```
you can use there `-t` option to control indentation.
If you like *to convert* `myjsonfile.json` from one-liner into pretty-printed, then use option `-f`:
```
j... |
57,728,801 | I have a large (around 200Mb) single-line json file and I want to convert this to a more readable multi-line json (or txt) file.
I tried to open the file with text editors like sublime text and it takes forever to open. So, I would like to make the conversion without opening the file.
Therefore, I cannot use the int... | 2019/08/30 | [
"https://Stackoverflow.com/questions/57728801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8889727/"
] | alternatively, you can use [**`jtc`**](https://github.com/ldn-softdev/jtc) unix utility to pretty-print your one-liner json:
```
jtc myjsonfile.json
```
you can use there `-t` option to control indentation.
If you like *to convert* `myjsonfile.json` from one-liner into pretty-printed, then use option `-f`:
```
j... | if you can identify a character sequence that ends a line (e.g. a curly bracket followed by a semicolon) you can use sed for it
```
$ sed 's/};/\n/g' <<< "my};test};string"
my
test
string
``` |
17,507,799 | I've built a little app engine app that lets users upload short recordings. Some of the recordings are done in-browser with <https://github.com/mattdiamond/Recorderjs>, which creates wav files. To save space, I'd like to convert those to ogg before writing them to the app engine datastore, so that I use less of my outg... | 2013/07/06 | [
"https://Stackoverflow.com/questions/17507799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610668/"
] | Pymedia isn't pure python so you won't be able to use it on app engine.
You probably want to build something on Compute Engine to do this. | Provided it's possible to replace Matt Diamond's recorderjs with its fork, [chris-rudmin/Recorderjs](https://github.com/chris-rudmin/Recorderjs) ([demo page](https://rawgit.com/chris-rudmin/Recorderjs/master/example.html)) in AppEngine, this should be feasible. Or first encode to WAV and use [opusenc.js](https://github... |
20,423,599 | If I write the following in python, I get a syntax error, why so?
```
a = 1
b = (a+=1)
```
I am using python version 2.7
what I get when I run it, the following:
```
>>> a = 1
>>> b = (a +=1)
File "<stdin>", line 1
b = (a +=1)
^
SyntaxError: invalid syntax
>>>
``` | 2013/12/06 | [
"https://Stackoverflow.com/questions/20423599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932405/"
] | Unlike in some other languages, assignment (including augmented assignment, like `+=`) in Python is *not* an expression. This also affects things like this:
```
(a=1) > 2
```
which is legal in C, and several other languages.
The reason generally given for this is because it helps to prevent a class of bugs like th... | `a +=1` is a statement in Python and you can't assign a statement to a variable. Though it is a valid syntax in languages like C, PHP, etc but not Python.
```
b = (a+=1)
```
An equivalent version will be:
```
>>> a = 1
>>> a += 1
>>> b = a
``` |
20,423,599 | If I write the following in python, I get a syntax error, why so?
```
a = 1
b = (a+=1)
```
I am using python version 2.7
what I get when I run it, the following:
```
>>> a = 1
>>> b = (a +=1)
File "<stdin>", line 1
b = (a +=1)
^
SyntaxError: invalid syntax
>>>
``` | 2013/12/06 | [
"https://Stackoverflow.com/questions/20423599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932405/"
] | `a +=1` is a statement in Python and you can't assign a statement to a variable. Though it is a valid syntax in languages like C, PHP, etc but not Python.
```
b = (a+=1)
```
An equivalent version will be:
```
>>> a = 1
>>> a += 1
>>> b = a
``` | All the answers provided here are good, I just want to add that you can achieve what you want in a one-line expression, but written in a different manner:
```
b, a = a+1, a+1
```
Here you're doing *almost* the same thing: incrementing `a` by 1, and assigning the value of `a+1` to b - I'm telling 'almost' because her... |
20,423,599 | If I write the following in python, I get a syntax error, why so?
```
a = 1
b = (a+=1)
```
I am using python version 2.7
what I get when I run it, the following:
```
>>> a = 1
>>> b = (a +=1)
File "<stdin>", line 1
b = (a +=1)
^
SyntaxError: invalid syntax
>>>
``` | 2013/12/06 | [
"https://Stackoverflow.com/questions/20423599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932405/"
] | Unlike in some other languages, assignment (including augmented assignment, like `+=`) in Python is *not* an expression. This also affects things like this:
```
(a=1) > 2
```
which is legal in C, and several other languages.
The reason generally given for this is because it helps to prevent a class of bugs like th... | As @Ashwini stated, `a+=1` is an assigment, not a value. You can't assign it to `b`, or any variable. What you probably want is:
```
b = a+1
``` |
20,423,599 | If I write the following in python, I get a syntax error, why so?
```
a = 1
b = (a+=1)
```
I am using python version 2.7
what I get when I run it, the following:
```
>>> a = 1
>>> b = (a +=1)
File "<stdin>", line 1
b = (a +=1)
^
SyntaxError: invalid syntax
>>>
``` | 2013/12/06 | [
"https://Stackoverflow.com/questions/20423599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932405/"
] | As @Ashwini stated, `a+=1` is an assigment, not a value. You can't assign it to `b`, or any variable. What you probably want is:
```
b = a+1
``` | All the answers provided here are good, I just want to add that you can achieve what you want in a one-line expression, but written in a different manner:
```
b, a = a+1, a+1
```
Here you're doing *almost* the same thing: incrementing `a` by 1, and assigning the value of `a+1` to b - I'm telling 'almost' because her... |
20,423,599 | If I write the following in python, I get a syntax error, why so?
```
a = 1
b = (a+=1)
```
I am using python version 2.7
what I get when I run it, the following:
```
>>> a = 1
>>> b = (a +=1)
File "<stdin>", line 1
b = (a +=1)
^
SyntaxError: invalid syntax
>>>
``` | 2013/12/06 | [
"https://Stackoverflow.com/questions/20423599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932405/"
] | Unlike in some other languages, assignment (including augmented assignment, like `+=`) in Python is *not* an expression. This also affects things like this:
```
(a=1) > 2
```
which is legal in C, and several other languages.
The reason generally given for this is because it helps to prevent a class of bugs like th... | All the answers provided here are good, I just want to add that you can achieve what you want in a one-line expression, but written in a different manner:
```
b, a = a+1, a+1
```
Here you're doing *almost* the same thing: incrementing `a` by 1, and assigning the value of `a+1` to b - I'm telling 'almost' because her... |
1,423,214 | I have this python code for opening a .cfg file, writing to it and saving it:
```
import ConfigParser
def get_lock_file():
cf = ConfigParser.ConfigParser()
cf.read("svn.lock")
return cf
def save_lock_file(configurationParser):
cf = configurationParser
config_file = ope... | 2009/09/14 | [
"https://Stackoverflow.com/questions/1423214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128508/"
] | Just to note that configuration file handling is simpler with ConfigObj.
To read and then write a config file:
```
from configobj import ConfigObj
config = ConfigObj(filename)
value = config['entry']
config['entry'] = newvalue
config.write()
``` | Looks good to me.
If both places call `get_lock_file`, then `cf.set(...)`, and then `save_lock_file`, and no exceptions are raised, this should work.
If you have different threads or processes accessing the same file you could have a race condition:
1. thread/process A reads the file
2. thread/process B reads the fi... |
1,423,214 | I have this python code for opening a .cfg file, writing to it and saving it:
```
import ConfigParser
def get_lock_file():
cf = ConfigParser.ConfigParser()
cf.read("svn.lock")
return cf
def save_lock_file(configurationParser):
cf = configurationParser
config_file = ope... | 2009/09/14 | [
"https://Stackoverflow.com/questions/1423214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128508/"
] | Just to note that configuration file handling is simpler with ConfigObj.
To read and then write a config file:
```
from configobj import ConfigObj
config = ConfigObj(filename)
value = config['entry']
config['entry'] = newvalue
config.write()
``` | Works for me.
```
C:\temp>type svn.lock
[some_prop_section]
Hello=World
C:\temp>python
ActivePython 2.6.2.2 (ActiveState Software Inc.) based on
Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import Conf... |
64,436,875 | I have a python package project 'webapi' and I want to set up in a way so that other people can "pip install webapi". If I want to put it on a private server with a specific ip: xx.xx.xx.xx.
So other people with the access right don't need to git clone the project and install it locally into their virtual environment. ... | 2020/10/20 | [
"https://Stackoverflow.com/questions/64436875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3943868/"
] | I guess the question is unclear, if you want to upload your webapi package to PyPi you can read [this article](https://medium.com/@joel.barmettler/how-to-upload-your-python-package-to-pypi-65edc5fe9c56). But this will make your package public and i'm not quite sure that's what you want.
If what you want is a private py... | It seems like you need a software repository management application such as [Pulp](https://pulpproject.org/) take a look at [their plugin section](https://pulpproject.org/content-plugins/) and their documentation is [here](https://pulp-python.readthedocs.io/en/latest/). I use it as a private python repository for syste... |
64,436,875 | I have a python package project 'webapi' and I want to set up in a way so that other people can "pip install webapi". If I want to put it on a private server with a specific ip: xx.xx.xx.xx.
So other people with the access right don't need to git clone the project and install it locally into their virtual environment. ... | 2020/10/20 | [
"https://Stackoverflow.com/questions/64436875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3943868/"
] | I guess the question is unclear, if you want to upload your webapi package to PyPi you can read [this article](https://medium.com/@joel.barmettler/how-to-upload-your-python-package-to-pypi-65edc5fe9c56). But this will make your package public and i'm not quite sure that's what you want.
If what you want is a private py... | Linode provides another way of setting up a private pip repos. Most important is to work with your team to decide which package dependencies that need to be maintained.
[guides/how-to-create-a-private-python-package-repository/](https://www.linode.com/docs/guides/how-to-create-a-private-python-package-repository/) |
2,726,171 | I am trying to change the font size using python's ImageDraw library.
You can do something like [this](http://infohost.nmt.edu/tcc/help/pubs/pil/image-font.html):
```
fontPath = "/usr/share/fonts/dejavu-lgc/DejaVuLGCSansCondensed-Bold.ttf"
sans16 = ImageFont.truetype ( fontPath, 16 )
im = Image.new ( "RGB", (20... | 2010/04/28 | [
"https://Stackoverflow.com/questions/2726171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | Per [PIL's docs](http://www.pythonware.com/library/pil/handbook/imagedraw.htm), `ImageDraw`'s default font is a bitmap font, and therefore it cannot be scaled. For scaling, you need to select a true-type font. I hope it's not difficult to find a nice truetype font that "looks kinda like" the default font in your desire... | Just do this
```
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
def image_char(char,image_size, font_size):
img = Image.new("RGB", (image_size, image_size), (255,255,255))
print img.getpixel((0,0))
draw = ImageDraw.Draw(img)
font_path = "/Users/admin/Library/... |
2,726,171 | I am trying to change the font size using python's ImageDraw library.
You can do something like [this](http://infohost.nmt.edu/tcc/help/pubs/pil/image-font.html):
```
fontPath = "/usr/share/fonts/dejavu-lgc/DejaVuLGCSansCondensed-Bold.ttf"
sans16 = ImageFont.truetype ( fontPath, 16 )
im = Image.new ( "RGB", (20... | 2010/04/28 | [
"https://Stackoverflow.com/questions/2726171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | Per [PIL's docs](http://www.pythonware.com/library/pil/handbook/imagedraw.htm), `ImageDraw`'s default font is a bitmap font, and therefore it cannot be scaled. For scaling, you need to select a true-type font. I hope it's not difficult to find a nice truetype font that "looks kinda like" the default font in your desire... | You could scale the image down, draw the text and then scale the image up again:
```
im = ImageOps.scale(im, 0.5)
draw = ImageDraw.Draw(im)
draw.text((0, 0),"MyText",(0,0,0))
im = ImageOps.scale(im, 2)
```
This effectively increases the font size by a factor of 2. |
2,726,171 | I am trying to change the font size using python's ImageDraw library.
You can do something like [this](http://infohost.nmt.edu/tcc/help/pubs/pil/image-font.html):
```
fontPath = "/usr/share/fonts/dejavu-lgc/DejaVuLGCSansCondensed-Bold.ttf"
sans16 = ImageFont.truetype ( fontPath, 16 )
im = Image.new ( "RGB", (20... | 2010/04/28 | [
"https://Stackoverflow.com/questions/2726171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | Just do this
```
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
def image_char(char,image_size, font_size):
img = Image.new("RGB", (image_size, image_size), (255,255,255))
print img.getpixel((0,0))
draw = ImageDraw.Draw(img)
font_path = "/Users/admin/Library/... | You could scale the image down, draw the text and then scale the image up again:
```
im = ImageOps.scale(im, 0.5)
draw = ImageDraw.Draw(im)
draw.text((0, 0),"MyText",(0,0,0))
im = ImageOps.scale(im, 2)
```
This effectively increases the font size by a factor of 2. |
24,701,171 | I want to stream an "infinite" (i.e. continuous) amount of data using HTTP Post. Basically, I want to send the POST request header and then stream the content (where the content length is unknown). I looked through <http://docs.python-requests.org/en/latest/user/advanced/> and it seems to have the facility. The one que... | 2014/07/11 | [
"https://Stackoverflow.com/questions/24701171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2932861/"
] | Just wanted to give you an answer so you could close your question:
It sounds like what you're really looking for is python websockets. Internally, you make a HTTP request to upgrade the connection to a websocket, and after the handshake you are free to stream data both ways. Python makes this easy, [for example](http... | A file-like object is an object with a "read" method that accept a size and returns a binary data buffer for the next chunk of data.
One example that looks like that is indeed, the file object, if you want to read from the filesystem.
Another common case is the [StringIO](https://docs.python.org/2/library/stringio.ht... |
36,270,161 | I want to get every value of 'Lemma' in this json:
```
{'sentences':
[{'indexeddependencies': [], 'words':
[
['Cinnamomum', {'CharacterOffsetBegin': '0', 'CharacterOffsetEnd': '10', 'Lemma': 'Cinnamomum', 'PartOfSpeech': 'NNP', 'NamedEntityTag': 'O'}],
['.', {'CharacterOffsetBegin': '14', 'C... | 2016/03/28 | [
"https://Stackoverflow.com/questions/36270161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6125957/"
] | I'm not sure why do you have this data structure - assuming you cannot change/reshape it to better suit your queries and use cases and that `Lemma` key would always be present:
```
>>> [word[1]['Lemma']
for sentence in data['sentences']
for word in sentence['words']]
['Cinnamomum', '.', 'specific', 'immuno... | this simple code traverses everything and finds all Lemma values (btw. your json should have " instead of ' as string quotes, I guess:
```
import json
with open('lemma.json') as f:
data = json.load(f)
def traverse(node):
for key in node:
if isinstance(node, list):
traverse(key)
el... |
36,270,161 | I want to get every value of 'Lemma' in this json:
```
{'sentences':
[{'indexeddependencies': [], 'words':
[
['Cinnamomum', {'CharacterOffsetBegin': '0', 'CharacterOffsetEnd': '10', 'Lemma': 'Cinnamomum', 'PartOfSpeech': 'NNP', 'NamedEntityTag': 'O'}],
['.', {'CharacterOffsetBegin': '14', 'C... | 2016/03/28 | [
"https://Stackoverflow.com/questions/36270161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6125957/"
] | I'm not sure why do you have this data structure - assuming you cannot change/reshape it to better suit your queries and use cases and that `Lemma` key would always be present:
```
>>> [word[1]['Lemma']
for sentence in data['sentences']
for word in sentence['words']]
['Cinnamomum', '.', 'specific', 'immuno... | You can use the [JSON encoder and decoder library](https://docs.python.org/2/library/json.html)
If you use that library you write:
`import json
json.loads(result)`
Anyway, i try put your json in a validator and i obtain a error |
36,270,161 | I want to get every value of 'Lemma' in this json:
```
{'sentences':
[{'indexeddependencies': [], 'words':
[
['Cinnamomum', {'CharacterOffsetBegin': '0', 'CharacterOffsetEnd': '10', 'Lemma': 'Cinnamomum', 'PartOfSpeech': 'NNP', 'NamedEntityTag': 'O'}],
['.', {'CharacterOffsetBegin': '14', 'C... | 2016/03/28 | [
"https://Stackoverflow.com/questions/36270161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6125957/"
] | 1. change single quotes to double quotes by `sed -i 's/\'/\"/g' sample.json`
2. convert to json object and parse it by module `json`
`import json
with open('sample.json', encoding='utf-8') as data_file:
data = json.loads(data_file.read())
for sentence in data['sentences']:
for word in sentence['words']:
print(word[1]... | this simple code traverses everything and finds all Lemma values (btw. your json should have " instead of ' as string quotes, I guess:
```
import json
with open('lemma.json') as f:
data = json.load(f)
def traverse(node):
for key in node:
if isinstance(node, list):
traverse(key)
el... |
36,270,161 | I want to get every value of 'Lemma' in this json:
```
{'sentences':
[{'indexeddependencies': [], 'words':
[
['Cinnamomum', {'CharacterOffsetBegin': '0', 'CharacterOffsetEnd': '10', 'Lemma': 'Cinnamomum', 'PartOfSpeech': 'NNP', 'NamedEntityTag': 'O'}],
['.', {'CharacterOffsetBegin': '14', 'C... | 2016/03/28 | [
"https://Stackoverflow.com/questions/36270161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6125957/"
] | 1. change single quotes to double quotes by `sed -i 's/\'/\"/g' sample.json`
2. convert to json object and parse it by module `json`
`import json
with open('sample.json', encoding='utf-8') as data_file:
data = json.loads(data_file.read())
for sentence in data['sentences']:
for word in sentence['words']:
print(word[1]... | You can use the [JSON encoder and decoder library](https://docs.python.org/2/library/json.html)
If you use that library you write:
`import json
json.loads(result)`
Anyway, i try put your json in a validator and i obtain a error |
48,409,243 | I tried to install google cloud module on Ubuntu 16.04 for python 3 but it shows `permission error 13`
this error is shown many times during installations for my python environment `PermissionError: [Errno 13] Permission denied: /usr/lib/python3/dist-packages/httplib2-0.9.1.egg-info` | 2018/01/23 | [
"https://Stackoverflow.com/questions/48409243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9177827/"
] | These are documented well enough in the common literature:
[location](https://en.wikipedia.org/wiki/Location_parameter), [mu](https://en.wikipedia.org/wiki/Poisson_distribution), and the page you cited -- "well enough" is assuming that you're familiar enough with the field's vocabulary to work your way through the tech... | UHXW is asking what do these arguments mean in simple terms. Prune's answers could be simplified.
The loc is like the lowest x value of your distribution the mu is like the middle of your distribution. Look at
<https://www.datacamp.com/community/tutorials/probability-distributions-python>
The uniform function genera... |
18,478,287 | The regular way of JSON-serializing custom non-serializable objects is to subclass `json.JSONEncoder` and then pass a custom encoder to `json.dumps()`.
It usually looks like this:
```
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Foo):
return obj.to_json()
... | 2013/08/28 | [
"https://Stackoverflow.com/questions/18478287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845169/"
] | I suggest putting the hack into the class definition. This way, once the class is defined, it supports JSON. Example:
```
import json
class MyClass( object ):
def _jsonSupport( *args ):
def default( self, xObject ):
return { 'type': 'MyClass', 'name': xObject.name() }
def objectHook(... | For production environment, prepare rather own module of `json` with your own custom encoder, to make it clear that you overrides something.
Monkey-patch is not recommended, but you can do monkey patch in your testenv.
For example,
```
class JSONDatetimeAndPhonesEncoder(json.JSONEncoder):
def default(self, obj):
... |
18,478,287 | The regular way of JSON-serializing custom non-serializable objects is to subclass `json.JSONEncoder` and then pass a custom encoder to `json.dumps()`.
It usually looks like this:
```
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Foo):
return obj.to_json()
... | 2013/08/28 | [
"https://Stackoverflow.com/questions/18478287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845169/"
] | As I said in a comment to your question, after looking at the `json` module's source code, it does not appear to lend itself to doing what you want. However the goal could be achieved by what is known as [*monkey-patching*](https://en.wikipedia.org/wiki/Monkey-patch)
(see question [*What is a monkey patch?*](https://st... | For production environment, prepare rather own module of `json` with your own custom encoder, to make it clear that you overrides something.
Monkey-patch is not recommended, but you can do monkey patch in your testenv.
For example,
```
class JSONDatetimeAndPhonesEncoder(json.JSONEncoder):
def default(self, obj):
... |
18,478,287 | The regular way of JSON-serializing custom non-serializable objects is to subclass `json.JSONEncoder` and then pass a custom encoder to `json.dumps()`.
It usually looks like this:
```
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Foo):
return obj.to_json()
... | 2013/08/28 | [
"https://Stackoverflow.com/questions/18478287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845169/"
] | You can extend the dict class like so:
```
#!/usr/local/bin/python3
import json
class Serializable(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# hack to fix _json.so make_encoder serialize properly
self.__setitem__('dummy', 1)
def _myattrs(self):
... | I suggest putting the hack into the class definition. This way, once the class is defined, it supports JSON. Example:
```
import json
class MyClass( object ):
def _jsonSupport( *args ):
def default( self, xObject ):
return { 'type': 'MyClass', 'name': xObject.name() }
def objectHook(... |
18,478,287 | The regular way of JSON-serializing custom non-serializable objects is to subclass `json.JSONEncoder` and then pass a custom encoder to `json.dumps()`.
It usually looks like this:
```
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Foo):
return obj.to_json()
... | 2013/08/28 | [
"https://Stackoverflow.com/questions/18478287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845169/"
] | You can extend the dict class like so:
```
#!/usr/local/bin/python3
import json
class Serializable(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# hack to fix _json.so make_encoder serialize properly
self.__setitem__('dummy', 1)
def _myattrs(self):
... | The problem with overriding `JSONEncoder().default` is that you can do it only once. If you stumble upon anything a special data type that does not work with that pattern (like if you use a strange encoding). With the pattern below, you can always make your class JSON serializable, provided that the class field you wan... |
18,478,287 | The regular way of JSON-serializing custom non-serializable objects is to subclass `json.JSONEncoder` and then pass a custom encoder to `json.dumps()`.
It usually looks like this:
```
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Foo):
return obj.to_json()
... | 2013/08/28 | [
"https://Stackoverflow.com/questions/18478287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845169/"
] | As I said in a comment to your question, after looking at the `json` module's source code, it does not appear to lend itself to doing what you want. However the goal could be achieved by what is known as [*monkey-patching*](https://en.wikipedia.org/wiki/Monkey-patch)
(see question [*What is a monkey patch?*](https://st... | You can extend the dict class like so:
```
#!/usr/local/bin/python3
import json
class Serializable(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# hack to fix _json.so make_encoder serialize properly
self.__setitem__('dummy', 1)
def _myattrs(self):
... |
18,478,287 | The regular way of JSON-serializing custom non-serializable objects is to subclass `json.JSONEncoder` and then pass a custom encoder to `json.dumps()`.
It usually looks like this:
```
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Foo):
return obj.to_json()
... | 2013/08/28 | [
"https://Stackoverflow.com/questions/18478287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845169/"
] | You can extend the dict class like so:
```
#!/usr/local/bin/python3
import json
class Serializable(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# hack to fix _json.so make_encoder serialize properly
self.__setitem__('dummy', 1)
def _myattrs(self):
... | For production environment, prepare rather own module of `json` with your own custom encoder, to make it clear that you overrides something.
Monkey-patch is not recommended, but you can do monkey patch in your testenv.
For example,
```
class JSONDatetimeAndPhonesEncoder(json.JSONEncoder):
def default(self, obj):
... |
18,478,287 | The regular way of JSON-serializing custom non-serializable objects is to subclass `json.JSONEncoder` and then pass a custom encoder to `json.dumps()`.
It usually looks like this:
```
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Foo):
return obj.to_json()
... | 2013/08/28 | [
"https://Stackoverflow.com/questions/18478287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845169/"
] | You can extend the dict class like so:
```
#!/usr/local/bin/python3
import json
class Serializable(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# hack to fix _json.so make_encoder serialize properly
self.__setitem__('dummy', 1)
def _myattrs(self):
... | I don't understand why you can't write a `serialize` function for your own class? You implement the custom encoder inside the class itself and allow "people" to call the serialize function that will essentially return `self.__dict__` with functions stripped out.
edit:
[This question](https://stackoverflow.com/questio... |
18,478,287 | The regular way of JSON-serializing custom non-serializable objects is to subclass `json.JSONEncoder` and then pass a custom encoder to `json.dumps()`.
It usually looks like this:
```
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Foo):
return obj.to_json()
... | 2013/08/28 | [
"https://Stackoverflow.com/questions/18478287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845169/"
] | I suggest putting the hack into the class definition. This way, once the class is defined, it supports JSON. Example:
```
import json
class MyClass( object ):
def _jsonSupport( *args ):
def default( self, xObject ):
return { 'type': 'MyClass', 'name': xObject.name() }
def objectHook(... | I don't understand why you can't write a `serialize` function for your own class? You implement the custom encoder inside the class itself and allow "people" to call the serialize function that will essentially return `self.__dict__` with functions stripped out.
edit:
[This question](https://stackoverflow.com/questio... |
18,478,287 | The regular way of JSON-serializing custom non-serializable objects is to subclass `json.JSONEncoder` and then pass a custom encoder to `json.dumps()`.
It usually looks like this:
```
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Foo):
return obj.to_json()
... | 2013/08/28 | [
"https://Stackoverflow.com/questions/18478287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845169/"
] | The problem with overriding `JSONEncoder().default` is that you can do it only once. If you stumble upon anything a special data type that does not work with that pattern (like if you use a strange encoding). With the pattern below, you can always make your class JSON serializable, provided that the class field you wan... | For production environment, prepare rather own module of `json` with your own custom encoder, to make it clear that you overrides something.
Monkey-patch is not recommended, but you can do monkey patch in your testenv.
For example,
```
class JSONDatetimeAndPhonesEncoder(json.JSONEncoder):
def default(self, obj):
... |
18,478,287 | The regular way of JSON-serializing custom non-serializable objects is to subclass `json.JSONEncoder` and then pass a custom encoder to `json.dumps()`.
It usually looks like this:
```
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Foo):
return obj.to_json()
... | 2013/08/28 | [
"https://Stackoverflow.com/questions/18478287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845169/"
] | As I said in a comment to your question, after looking at the `json` module's source code, it does not appear to lend itself to doing what you want. However the goal could be achieved by what is known as [*monkey-patching*](https://en.wikipedia.org/wiki/Monkey-patch)
(see question [*What is a monkey patch?*](https://st... | The problem with overriding `JSONEncoder().default` is that you can do it only once. If you stumble upon anything a special data type that does not work with that pattern (like if you use a strange encoding). With the pattern below, you can always make your class JSON serializable, provided that the class field you wan... |
55,200,708 | I am getting started on using Zappa. However, I already had installed python 3.7 on my computer while Zappa uses 3.6. I installed python 3.6.8, but when I try to use zappa in the cmd (zappa init) it uses python 3.7 by default. How can I direct zappa to use 3.6 instead? | 2019/03/16 | [
"https://Stackoverflow.com/questions/55200708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11116762/"
] | As mentioned in Zappa [README](https://github.com/Miserlou/Zappa#installation-and-configuration):
>
> Please note that Zappa must be installed into your project's virtual environment.
>
>
>
You should use something like `virtualenv` to create a virtual environment, which makes it easy to switch Python version.
... | I don't know about Zappa, but if you want use a specific version of python can do:
```
python3.6 my_program.py
```
and if whant use the command *python* with a specific version permanently, in **linux** modify the file */home/[user\_name]/.bashrc* and add the next line:
```
alias python=python3.6
``` |
55,200,708 | I am getting started on using Zappa. However, I already had installed python 3.7 on my computer while Zappa uses 3.6. I installed python 3.6.8, but when I try to use zappa in the cmd (zappa init) it uses python 3.7 by default. How can I direct zappa to use 3.6 instead? | 2019/03/16 | [
"https://Stackoverflow.com/questions/55200708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11116762/"
] | As mentioned in Zappa [README](https://github.com/Miserlou/Zappa#installation-and-configuration):
>
> Please note that Zappa must be installed into your project's virtual environment.
>
>
>
You should use something like `virtualenv` to create a virtual environment, which makes it easy to switch Python version.
... | You can use `virtualenv` to setup an environment using a specific Python version by:
```
% pip install virtualenv
% virtualenv -p python3.6 .venv
```
You can also use an absolute path to the Python executable if it's named the same but located in different folders.
Then switch to use the environment:
```
% source ... |
69,654,700 | So I'm trying to achieve something like this
```
from enum import Enum
tabulate_formats = ['fancy_grid', 'fancy_outline', 'github', 'grid']
class TableFormat(str, Enum):
for item in tabulate_formats:
exec(f"{item} = '{item}'")
```
Though i get this error
```
Traceback (most recent call last):
File "... | 2021/10/21 | [
"https://Stackoverflow.com/questions/69654700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3709060/"
] | What you want to do doesn't involve editing an array, only editing the property of that array. [Array.prototype.push](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) and [Array.prototype.splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects... | You can work with append `parking` property to object as below:
```js
this.houseList.splice(i, 0, {
...this.houseList[i],
parking: this.ParkingIsTrue,
});
```
[Sample Solution on StackBlitz](https://stackblitz.com/edit/angular-ivy-zggwz7?file=src/app/app.component.html)
---
References
----------
[JavaScript E... |
39,517,921 | So I'm using tkinter python and I have an entry widget with Name text in it. I want to delete the text only when the widget is clicked on. This is what I have so far:
```
#Import tkinter to make gui
from tkinter import *
from tkinter import ttk#Sets title and creates gui
root = Tk()
root.title("Identity Form")
#Confi... | 2016/09/15 | [
"https://Stackoverflow.com/questions/39517921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6570334/"
] | If you're expecting a socket to stay open for minutes at a time, you're in for a world of hurt. That might work on Wi-Fi, but on cellular, there's a high probability of the connection glitching because of tower switching or some other random event outside your control. When that happens, the connection drops, and there... | I faced this issue and spend more than 1 week to fix this. AND i just solved this issue by changing Wifi connection. |
39,517,921 | So I'm using tkinter python and I have an entry widget with Name text in it. I want to delete the text only when the widget is clicked on. This is what I have so far:
```
#Import tkinter to make gui
from tkinter import *
from tkinter import ttk#Sets title and creates gui
root = Tk()
root.title("Identity Form")
#Confi... | 2016/09/15 | [
"https://Stackoverflow.com/questions/39517921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6570334/"
] | If you're expecting a socket to stay open for minutes at a time, you're in for a world of hurt. That might work on Wi-Fi, but on cellular, there's a high probability of the connection glitching because of tower switching or some other random event outside your control. When that happens, the connection drops, and there... | I faced the same issue and I am attaching a screenshot of the resolution to show how I resolved the issue.
In my case, the issue was that the API requests are blocked from the server Sucuri/Cloudproxy (Or you can say firewall service). Disabling the firewall resolved the issue
[
root.title("Identity Form")
#Confi... | 2016/09/15 | [
"https://Stackoverflow.com/questions/39517921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6570334/"
] | If you're expecting a socket to stay open for minutes at a time, you're in for a world of hurt. That might work on Wi-Fi, but on cellular, there's a high probability of the connection glitching because of tower switching or some other random event outside your control. When that happens, the connection drops, and there... | I don't why but it's works when I add sleep before my request:
```
sleep(10000)
AF.request(ViewController.URL_SYSTEM+"/rest,get_profile", method: .post, parameters: params, encoding: JSONEncoding.default , headers: headers).responseJSON { (response) in
}
``` |
39,517,921 | So I'm using tkinter python and I have an entry widget with Name text in it. I want to delete the text only when the widget is clicked on. This is what I have so far:
```
#Import tkinter to make gui
from tkinter import *
from tkinter import ttk#Sets title and creates gui
root = Tk()
root.title("Identity Form")
#Confi... | 2016/09/15 | [
"https://Stackoverflow.com/questions/39517921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6570334/"
] | I faced the same issue and I am attaching a screenshot of the resolution to show how I resolved the issue.
In my case, the issue was that the API requests are blocked from the server Sucuri/Cloudproxy (Or you can say firewall service). Disabling the firewall resolved the issue
[
root.title("Identity Form")
#Confi... | 2016/09/15 | [
"https://Stackoverflow.com/questions/39517921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6570334/"
] | I don't why but it's works when I add sleep before my request:
```
sleep(10000)
AF.request(ViewController.URL_SYSTEM+"/rest,get_profile", method: .post, parameters: params, encoding: JSONEncoding.default , headers: headers).responseJSON { (response) in
}
``` | I faced this issue and spend more than 1 week to fix this. AND i just solved this issue by changing Wifi connection. |
39,517,921 | So I'm using tkinter python and I have an entry widget with Name text in it. I want to delete the text only when the widget is clicked on. This is what I have so far:
```
#Import tkinter to make gui
from tkinter import *
from tkinter import ttk#Sets title and creates gui
root = Tk()
root.title("Identity Form")
#Confi... | 2016/09/15 | [
"https://Stackoverflow.com/questions/39517921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6570334/"
] | I faced the same issue and I am attaching a screenshot of the resolution to show how I resolved the issue.
In my case, the issue was that the API requests are blocked from the server Sucuri/Cloudproxy (Or you can say firewall service). Disabling the firewall resolved the issue
[
AF.request(ViewController.URL_SYSTEM+"/rest,get_profile", method: .post, parameters: params, encoding: JSONEncoding.default , headers: headers).responseJSON { (response) in
}
``` |
40,009,358 | I'm a 1st year CS student been struggling over the past few days on this lab task I received for python(2.7):
---
Write a Python script named higher-lower.py which:
first reads exactly one integer from standard input (10, in the example below),
then reads exactly five more integers from standard input and
for each of... | 2016/10/12 | [
"https://Stackoverflow.com/questions/40009358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7010470/"
] | Given your description, I suspect that the validation program wants to see a single result after each additional input. Have you tried that?
```
while s <= 5:
curr = input()
if prev < curr:
print "higher"
elif curr < prev:
print "lower"
else:
print "equal"
s = s + 1
prev = curr
`... | ```
magic_number = 3
# Your code here...
while True:
guess = int(input("Guess my number: "))
if guess == magic_number:
print "Correct!"
break
elif guess > magic_number:
print "Too high!"
else:
print "Too low!"
print "Great job guessing my number!"
``` |
53,881,731 | How can I define an xpath command in python (scrapy) to accept any number at the place indicated in the code. I have already tried to put an `*` or `any()` at the position.
```
table = response.xpath('//*[@id="olnof_**here I want to accept any value**_altlinesodd"]/tr[1]/TD[1]/A[1]')
``` | 2018/12/21 | [
"https://Stackoverflow.com/questions/53881731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10819357/"
] | You can do this using [regular expressions](https://doc.scrapy.org/en/latest/topics/selectors.html#regular-expressions):
```
table = response.xpath('//*[re:test(@id, "^olnof_.+_altlinesodd$")]/tr[1]/TD[1]/A[1]')
``` | You can try below workaround:
```
'//*[starts-with(@id, "olnof_") and contains(@id, "_altlinesodd")]/tr[1]/TD[1]/A[1]'
```
`ends-with(@id, "_altlinesodd")` suites better in this case, but Scrapy doesn't support `ends-with` syntax, so `contains` used instead |
53,881,731 | How can I define an xpath command in python (scrapy) to accept any number at the place indicated in the code. I have already tried to put an `*` or `any()` at the position.
```
table = response.xpath('//*[@id="olnof_**here I want to accept any value**_altlinesodd"]/tr[1]/TD[1]/A[1]')
``` | 2018/12/21 | [
"https://Stackoverflow.com/questions/53881731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10819357/"
] | Now assuming your any as like ANY, so you can try this.
`x_path = '//*[@id="olnof_{}_altlinesodd"]/tr[1]/TD[1]/A[1]'`
`x_path.format("put your any here, may b from rand function or extracting the value from somewhere else.")`
Then,
`table = response.xpath(x_path)` this will do the work. | You can try below workaround:
```
'//*[starts-with(@id, "olnof_") and contains(@id, "_altlinesodd")]/tr[1]/TD[1]/A[1]'
```
`ends-with(@id, "_altlinesodd")` suites better in this case, but Scrapy doesn't support `ends-with` syntax, so `contains` used instead |
53,881,731 | How can I define an xpath command in python (scrapy) to accept any number at the place indicated in the code. I have already tried to put an `*` or `any()` at the position.
```
table = response.xpath('//*[@id="olnof_**here I want to accept any value**_altlinesodd"]/tr[1]/TD[1]/A[1]')
``` | 2018/12/21 | [
"https://Stackoverflow.com/questions/53881731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10819357/"
] | You can do this using [regular expressions](https://doc.scrapy.org/en/latest/topics/selectors.html#regular-expressions):
```
table = response.xpath('//*[re:test(@id, "^olnof_.+_altlinesodd$")]/tr[1]/TD[1]/A[1]')
``` | Now assuming your any as like ANY, so you can try this.
`x_path = '//*[@id="olnof_{}_altlinesodd"]/tr[1]/TD[1]/A[1]'`
`x_path.format("put your any here, may b from rand function or extracting the value from somewhere else.")`
Then,
`table = response.xpath(x_path)` this will do the work. |
22,291,337 | I know this one has been covered before, and perhaps isn't the most pythonic way of constructing a class, but I have a lot of different maya node classes with a lot @properties for retrieving/setting node data, and I want to see if procedurally building the attributes cuts down on overhead/mantinence.
I need to re-imp... | 2014/03/10 | [
"https://Stackoverflow.com/questions/22291337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3395409/"
] | This worked for me:
```
class Transform(object):
def __getattribute__(self, name):
if name in attrKeys:
return externalData[name]
return super(Transform, self).__getattribute__(name)
def __setattr__(self, name, value):
if name in attrKeys:
externalData[name] = val... | Why not also do the same thing in `__getattribute__`?
```
def __getattribute__(self, name):
print 'Getting --->', name
if name in attrKeys:
return externalData[name]
else:
# raise AttributeError("No attribute named [%s]" %name)
return super(Transform, sel... |
22,291,337 | I know this one has been covered before, and perhaps isn't the most pythonic way of constructing a class, but I have a lot of different maya node classes with a lot @properties for retrieving/setting node data, and I want to see if procedurally building the attributes cuts down on overhead/mantinence.
I need to re-imp... | 2014/03/10 | [
"https://Stackoverflow.com/questions/22291337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3395409/"
] | I have decided to go with @theodox s and use descriptors
This seems to work nicely:
```
class Transform(object):
def __init__(self, name):
self.name = name
for key in ['translateX','translateY','translateZ']:
buildNodeAttr(self.__class__, '%s.%s' % (self.name, key))
def buildNodeAttr(... | Why not also do the same thing in `__getattribute__`?
```
def __getattribute__(self, name):
print 'Getting --->', name
if name in attrKeys:
return externalData[name]
else:
# raise AttributeError("No attribute named [%s]" %name)
return super(Transform, sel... |
22,291,337 | I know this one has been covered before, and perhaps isn't the most pythonic way of constructing a class, but I have a lot of different maya node classes with a lot @properties for retrieving/setting node data, and I want to see if procedurally building the attributes cuts down on overhead/mantinence.
I need to re-imp... | 2014/03/10 | [
"https://Stackoverflow.com/questions/22291337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3395409/"
] | This worked for me:
```
class Transform(object):
def __getattribute__(self, name):
if name in attrKeys:
return externalData[name]
return super(Transform, self).__getattribute__(name)
def __setattr__(self, name, value):
if name in attrKeys:
externalData[name] = val... | Here in your snippet:
```
class Transform(object):
def __getattribute__(self, name):
print 'Getting --->', name
if name in attrKeys:
return externalData[name]
else:
raise AttributeError("No attribute named [%s]" %name)
def __setattr__(self, name, value):
... |
22,291,337 | I know this one has been covered before, and perhaps isn't the most pythonic way of constructing a class, but I have a lot of different maya node classes with a lot @properties for retrieving/setting node data, and I want to see if procedurally building the attributes cuts down on overhead/mantinence.
I need to re-imp... | 2014/03/10 | [
"https://Stackoverflow.com/questions/22291337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3395409/"
] | I have decided to go with @theodox s and use descriptors
This seems to work nicely:
```
class Transform(object):
def __init__(self, name):
self.name = name
for key in ['translateX','translateY','translateZ']:
buildNodeAttr(self.__class__, '%s.%s' % (self.name, key))
def buildNodeAttr(... | Here in your snippet:
```
class Transform(object):
def __getattribute__(self, name):
print 'Getting --->', name
if name in attrKeys:
return externalData[name]
else:
raise AttributeError("No attribute named [%s]" %name)
def __setattr__(self, name, value):
... |
22,291,337 | I know this one has been covered before, and perhaps isn't the most pythonic way of constructing a class, but I have a lot of different maya node classes with a lot @properties for retrieving/setting node data, and I want to see if procedurally building the attributes cuts down on overhead/mantinence.
I need to re-imp... | 2014/03/10 | [
"https://Stackoverflow.com/questions/22291337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3395409/"
] | This worked for me:
```
class Transform(object):
def __getattribute__(self, name):
if name in attrKeys:
return externalData[name]
return super(Transform, self).__getattribute__(name)
def __setattr__(self, name, value):
if name in attrKeys:
externalData[name] = val... | I have decided to go with @theodox s and use descriptors
This seems to work nicely:
```
class Transform(object):
def __init__(self, name):
self.name = name
for key in ['translateX','translateY','translateZ']:
buildNodeAttr(self.__class__, '%s.%s' % (self.name, key))
def buildNodeAttr(... |
52,458,158 | I am dealing with the dataset **titanic** from [*seaborn*].
```
titanic = seaborn.load_dataset('titanic')
```
I cut the age column into categorical bins.
```
age = pd.cut(titanic['age'], [0, 18, 80])
```
Then the problem comes, the groupby and pivot\_table give totally different results:
```
titanic.groupby(['se... | 2018/09/22 | [
"https://Stackoverflow.com/questions/52458158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10401026/"
] | It seems to work best when the object's key is a single class.
You can instead do something like this:
```
class="fa" [ngClass]="{'fa-paper-plane': true, 'fa-spinner': false, 'fa-spin': false }"
```
Because the `fa` class should always apply, it's being done in a normal `class` attribute | When a expression is evaluated to true the classes passed in ngClass are added to the classList for the element and when expression is evaluated to false the classes passed in ngClass are removed from the classList for the element. Example :
```
<div>
<p>
<i [ngClass]="{'fa fa-spinner fa-spin': false, 'fa fa-tel... |
45,619,018 | I'm trying to use OpenCV to segment a bent rod from it's background then find the bends in it and calculate the angle between each bend.
The first part luckily is trivial with a enough contrast between the foreground and background.
A bit of erosion/dilation takes care of reflections/highlights when segmenting.
The s... | 2017/08/10 | [
"https://Stackoverflow.com/questions/45619018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89766/"
] | It may be convenient to use curvature to find line segments. Here [example](http://www.morethantechnical.com/2012/12/07/resampling-smoothing-and-interest-points-of-curves-via-css-in-opencv-w-code/) of splitting contour by minimal curvature points, it may be better to use maximal curvature points in your case. B You can... | Once you have the contour, you can analyze it using a method like the one proposed in this paper: <https://link.springer.com/article/10.1007/s10032-011-0175-3>
Basically, the contour is tracked calculating the curvature at each point.
Then you can use a curvature threshold to segment the contour into straight and curv... |
45,619,018 | I'm trying to use OpenCV to segment a bent rod from it's background then find the bends in it and calculate the angle between each bend.
The first part luckily is trivial with a enough contrast between the foreground and background.
A bit of erosion/dilation takes care of reflections/highlights when segmenting.
The s... | 2017/08/10 | [
"https://Stackoverflow.com/questions/45619018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89766/"
] | I know this is old but I found this after having a similar problem
The method I used (after finding binary image) was along the lines of:
1. Find ends (points with fewest neighbors)
2. [skeletonize](https://scikit-image.org/docs/stable/auto_examples/edges/plot_skeleton.html) (optional)
3. Starting at one end find a fe... | Once you have the contour, you can analyze it using a method like the one proposed in this paper: <https://link.springer.com/article/10.1007/s10032-011-0175-3>
Basically, the contour is tracked calculating the curvature at each point.
Then you can use a curvature threshold to segment the contour into straight and curv... |
21,889,795 | I couldn't find the right search terms for this question, so please apologize if this question has already been asked before.
Basically, I want to create a python function that allows you to name the columns (as a function parameter) that you will do certain kinds of analyses on.
For instance see below. Obviously thi... | 2014/02/19 | [
"https://Stackoverflow.com/questions/21889795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314418/"
] | If I understand you, `df[yearattribute].unique()` should work. You can index into DataFrame columns like a dictionary.
Aside #1: `totaldf = df` only makes `totaldf` a new name for `df`, it doesn't make a copy, and you don't use it anyway.
Aside #2: you're not returning anything. | You can use [`getattr`](http://docs.python.org/3/library/functions.html#getattr) here:
```
yearlist = list(np.unique(getattr(df, yearattribute)))
```
`getattr` allows you to access an attribute via a string representation of its name.
Below is a demonstration:
```
>>> class Foo:
... def __init__(self):
... ... |
2,492,508 | is there a python library for supporting OpenType features? where can i get it?
please do not guide to fontforge, i live in Iran , so i can not download anything from them. | 2010/03/22 | [
"https://Stackoverflow.com/questions/2492508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/275221/"
] | The [Python Imaging Library (PIL)](http://www.pythonware.com/products/pil/) supports OpenType. | If you refer OpenType Fonts, there is python library for fontforge
<http://fontforge.sourceforge.net/python.html> |
2,492,508 | is there a python library for supporting OpenType features? where can i get it?
please do not guide to fontforge, i live in Iran , so i can not download anything from them. | 2010/03/22 | [
"https://Stackoverflow.com/questions/2492508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/275221/"
] | If you refer OpenType Fonts, there is python library for fontforge
<http://fontforge.sourceforge.net/python.html> | You can use [Pango](http://www.pango.org) and [Cairo](http://cairographics.org) and then its python binding 'pycairo' available in the last site too.
You can access to some (not all) OpenType features with these libraries. |
2,492,508 | is there a python library for supporting OpenType features? where can i get it?
please do not guide to fontforge, i live in Iran , so i can not download anything from them. | 2010/03/22 | [
"https://Stackoverflow.com/questions/2492508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/275221/"
] | The [Python Imaging Library (PIL)](http://www.pythonware.com/products/pil/) supports OpenType. | You can use [Pango](http://www.pango.org) and [Cairo](http://cairographics.org) and then its python binding 'pycairo' available in the last site too.
You can access to some (not all) OpenType features with these libraries. |
70,422,733 | Suppose you have a string:
```
text = "coding in python is a lot of fun"
```
And character positions:
```
positions = [(0,6),(10,16),(29,32)]
```
These are intervals, which cover certain words within text, i.e. coding, python and fun, respectively.
Using the character positions, how could you split the text on t... | 2021/12/20 | [
"https://Stackoverflow.com/questions/70422733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6515530/"
] | I'd flatten `positions` to be `[0,6,10,16,29,32]` and then do something like
```py
positions.append(-1)
prev_positions = [0] + positions
words = []
for begin, end in zip(prev_positions, positions):
words.append(text[begin:end])
```
This exact code produces `['', 'coding', ' in ', 'python', ' is a lot of ', 'fun'... | Below code works as expected
```
text = "coding in python is a lot of fun"
positions = [(0,6),(10,16),(29,32)]
textList = []
lastIndex = 0
for indexes in positions:
s = slice(indexes[0], indexes[1])
if positions.index(indexes) > 0:
print(lastIndex)
textList.append(text[lastIndex: indexes[0]])
... |
63,842,868 | ```
import pyautogui as py
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import keyboard
driver = webdriver.Chrome()
driver.get('https://www.youtube.com/watch?v=pcel9QTPx_g&list=RDpcel9QTPx_g&start_radio=1&t=11&ab_channel=%E5%BE%AE%E7%B3%96%E9%80%A2')
elem = driver.find_elements_by_id('... | 2020/09/11 | [
"https://Stackoverflow.com/questions/63842868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13781869/"
] | ```
import pyautogui as py
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import keyboard
driver = webdriver.Chrome()
driver.get('https://www.youtube.com/watch?v=pcel9QTPx_g&list=RDpcel9QTPx_g&start_radio=1&t=11&ab_channel=%E5%BE%AE%E7%B3%96%E9%80%A2')
elem = driver.find_elements_by_id('... | I would also suggest you to use another key instead of f12 because it will disrupt your code when you are running it from chrome, it will open developer mode! |
39,845,636 | I have the latest version of pip 8.1.1 on my ubuntu 16.
But I am not able to install any modules via pip as I get this error all the time.
```
File "/usr/local/bin/pip", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2927, in <... | 2016/10/04 | [
"https://Stackoverflow.com/questions/39845636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5474316/"
] | I repaired mine this with command:
>
> easy\_install pip
>
>
> | Delete all of the pip/pip3 stuff under .local including the packages.
```
sudo apt-get purge python-pip python3-pip
```
Now remove all pip3 files from local
```
sudo rm -rf /usr/local/bin/pip3
```
you can check which pip is installed other wise execute below one to remove all (No worries)
```
sudo rm -rf /usr/lo... |
39,845,636 | I have the latest version of pip 8.1.1 on my ubuntu 16.
But I am not able to install any modules via pip as I get this error all the time.
```
File "/usr/local/bin/pip", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2927, in <... | 2016/10/04 | [
"https://Stackoverflow.com/questions/39845636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5474316/"
] | Just relink to resolve it. Find which python : `ls -l /usr/local/bin/python`
```
ln -sf /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/bin/pip /usr/local/bin/pip
```
Or reinstall pip: <https://pip.pypa.io/en/stable/installing/> | After a large upgrade in Mint -> 19, my system was a bit weird and I came across this problem too.
I checked the answer from @amangpt777 that may be the one to try
```
/usr/local/bin/pip # -> actually had a shebang calling python3
~/.local/bin/pip* # files were duplicated with the "sudo installed" /usr/local/bin/pip... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.