qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
62,463,565 | I have three csv dataframes of tweets, each ~5M tweets. The following code for concatenating them exists with low memory error. My machine has 32GB memory. How can I assign more memory for this task in pandas?
```
df1 = pd.read_csv('tweets.csv')
df2 = pd.read_csv('tweets2.csv')
df3 = pd.read_csv('tweets3.csv')
frames... | 2020/06/19 | [
"https://Stackoverflow.com/questions/62463565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2414957/"
] | I think this is problem with malformed data (some data not structure properly in `tweets2.csv`) for that you can use `error_bad_lines=False` and try to chnage engine from c to python like `engine='python'`
ex : `df2 = pd.read_csv('tweets2.csv', error_bad_lines=False)`
or
ex : `df2 = pd.read_csv('tweets2.csv', engine=... | Specify `dtype` option on import or set `low_memory=False` | 5,646 |
61,390,586 | I am currently working on a schoolproject, and im trying to import data from a CSV file to MySQL using python. This is my code so far:
```
import mysql.connector
import csv
mydb = mysql.connector.connect(host='127.0.0.1', user='root', password='abc123!', db='jd_university')
cursor = mydb.cursor()
with open('C:/User... | 2020/04/23 | [
"https://Stackoverflow.com/questions/61390586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13391817/"
] | * You don't need to quote the `%s` placeholders.
* Since you're using `DictReader`, you will need to name the columns in your `row` expression (or not use DictReader and hope for the correct order, which I'd not do).
Try this:
```py
import mysql.connector
import csv
mydb = mysql.connector.connect(
host="127.0.0.... | Validate the datatype for DOB field in your data file and database column. Could be a data issue or table definition issue. | 5,647 |
25,608,078 | I am trying to create an SVG font, so I need to create some paths. One of the letters is defined by the following path:

Which I created with [svgwrite](https://pypi.python.org/pypi/svgwrite), by creating two `circles` and a `rect`, and then using inkscape to take the differenc... | 2014/09/01 | [
"https://Stackoverflow.com/questions/25608078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/218558/"
] | The first arc has a negative (0) draw angle, the second must have a positive (1) draw angle and drawn from the opposite side to achieve the desired effect.
```py
#--------------------------N-----------βββ-βββ-------------P-βββ-βββββ----------------------------------------------
d="M 0 128 A 128 128 1 1 0 0 127.9 Z M ... | following @martineau's suggestion and [this](https://stackoverflow.com/questions/5737975/circle-drawing-with-svgs-arc-path) SO question, I came to this solution:
* Create a circle made of two halfs
* Creates two smaller half circles (not quite circular)
* then use [`fill-rule: evenodd`](http://www.w3.org/TR/SVG/painti... | 5,648 |
44,430,246 | I have list of dictionaries and in each one of them the key `site` exists.
So in other words, this code returns `True`:
```
all('site' in site for site in summary)
```
Question is, what will be the pythonic way to iterate over the list of dictionaries and return `True` if a key different from `site` exists in any of... | 2017/06/08 | [
"https://Stackoverflow.com/questions/44430246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5517847/"
] | If all dictionaries have the key `site`, the dictionaries have a length of at least 1. The presence of *any other key* would increase the dictionary size to be greater than 1, test for that:
```
any(len(d) > 1 for d in summary)
``` | You could just check, for each dictionary `dct`:
```
any(key != "site" for key in dct)
```
If you want to check this for a list of dictionaries `dcts`, shove another `any` around that: `any(any(key != "site" for key in dct) for dct in dcts)`
This also makes it easily extensible to allowing multiple different keys. ... | 5,650 |
71,184,380 | I have two lists. I want to create a `Literal` using both these lists
```python
category1 = ["image/jpeg", "image/png"]
category2 = ["application/pdf"]
SUPPORTED_TYPES = typing.Literal[category1 + category2]
```
Is there any way to do this?
I have seen the question [typing: Dynamically Create Literal Alias from Li... | 2022/02/19 | [
"https://Stackoverflow.com/questions/71184380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14595305/"
] | Use the same technique as in the question you linked: build the lists from the literal types, instead of the other way around:
```
SUPPORTED_IMAGE_TYPES = typing.Literal["image/jpeg", "image/png"]
SUPPORTED_OTHER_TYPES = typing.Literal["application/pdf"]
SUPPORTED_TYPES = typing.Literal[SUPPORTED_IMAGE_TYPES, SUPPORT... | I got an answer to this -
Create a literal for both the lists, and then create a combined literal
```python
category1 = Literal["image/jpeg", "image/png"]
category2 = Literal["application/pdf"]
SUPPORTED_TYPES = Literal[category1, category2]
```
Sorry: hadnt seen that monica answered the question | 5,653 |
74,214,700 | i wrote this code:
```
admitted_List = [1, 5, 10, 50, 100, 500, 1000]
tempString = ""
finalList = []
for i in range(len(xkcd)-1):
if int(xkcd[i] + xkcd[i+1]) in admitted_List:
tempString += xkcd[i]
continue
else:
tempString += xkcd[i]
finalList.append(int(tempString))
te... | 2022/10/26 | [
"https://Stackoverflow.com/questions/74214700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18943770/"
] | >
>
> ```
> nodejs test.js
>
> ```
>
>
>
>
> ```
> nodejs -v
> v10.19.0
>
> ```
>
>
You are running this with Node 10 which is beyond end of life and does not support ECMAScript modules (with provide `import`) except as an experimental feature locked behind a flag.
Use the other version of Node.js you ha... | What worked for me:
1. Install **curl**:
`sudo apt install curl`
2. Install **NVM**:
`sudo curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash`
```
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ]... | 5,654 |
66,166,103 | How do I turn these numbers into a list using python?
16 3 2 13 -> ["16","3","2","13"] | 2021/02/12 | [
"https://Stackoverflow.com/questions/66166103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15195153/"
] | You can divide it by using [split](https://docs.python.org/3/library/stdtypes.html?highlight=split#str.split):
```
"16 3 2 13".split()
```
Output:
```
["16","3","2","13"]
``` | ```
a = '16 3 2 13'
b = ['']
print(type(b))
print(len(b))
j = 0
for i in range(len(a)):
if a[i] != ' ':
b[j] = b[j] + a[i]
else:
j = j+1
b.append('')
print(b)
``` | 5,657 |
72,726,621 | I have two lists.
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
```
If I look closely, L1 has `'not worry'` and `'good very'` which are exact reversed repetitio... | 2022/06/23 | [
"https://Stackoverflow.com/questions/72726621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6803114/"
] | ```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
def solution(lst):
res = []
for item in lst:
if " ".join(item.split()[::-1]) not in res:
... | This is a possible solution (the complexity is linear with respect to the number of strings):
```
from collections import defaultdict
from operator import itemgetter
d = defaultdict(list)
for s in L2:
d[max(s, reversed(s.split()))].append(s)
result = list(map(itemgetter(0), d.values()))
```
Here are the result... | 5,659 |
63,145,924 | Let say I have something like this :
```
--module1
def called():
if caller.class.attrX == 1 : ...
--module2
class ABC:
attrX = 1
def method():
called()
```
I want to access caller Class-attribute ?
I know I have to use inspect somehow but can figure how exactly.
python3 | 2020/07/29 | [
"https://Stackoverflow.com/questions/63145924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1019129/"
] | The code works perfectly fine for me in python 3.7.3.
`The number is: 2825302`
`['28', '82', '253', '2530', '5302']`
this is the output I have received | I don't get the error. Better practice is to pass mutable objects as parameters to functions. Changed `find_ten_substring()` to take additional parameter
```
def find_sum(num_str):
sum1 = 0
for i in num_str:
sum1 += int(i)
return sum1
def find_ten_substring(num_str, dict1):
list1 = []
for... | 5,669 |
1,223,927 | I have django running through WSGI like this :
```
<VirtualHost *:80>
WSGIScriptAlias / /home/ptarjan/django/django.wsgi
WSGIDaemonProcess ptarjan processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup ptarjan
Alias /media /home/ptarjan/django/mysite/media/
</VirtualHost>
```
But if in python ... | 2009/08/03 | [
"https://Stackoverflow.com/questions/1223927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | It is not 'deadlock-timeout' you want as specified by another, that is for a very special purpose which will not help in this case.
As far as trying to use mod\_wsgi features, you instead want the 'inactivity-timeout' option for WSGIDaemonProcess directive.
Even then, this is not a complete solution. This is because ... | If I understand well the question, you want to protect apache from locking up when running some random scripts from people. Well, if you're running untrusted code, I think you have other things to worry about that are worst than apache.
That said, you can use some configuration directives to adjust a *safer* environme... | 5,670 |
44,746,078 | I have some exception handling code in `python` where two exceptions can be raised, the first one being a "superset" of the second one.
I.e. the following code summarizes what I need to do (and works fine)
```
try:
normal_execution_path()
except FirstError:
handle_first_error()
handle_second_error()
excep... | 2017/06/25 | [
"https://Stackoverflow.com/questions/44746078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3246191/"
] | If you wish to manually throw the second error to be handled, you can use nested try-catch blocks like these:
```
try:
normal_execution_path()
except FirstError:
try:
handle_first_error()
raise SecondError
except SecondError:
handle_second_error()
except SecondError:
handle_... | Perhaps it is worth reviewing the code architecture. But for your particular case:
Create a generic class that handles this type of error. To inherit from it for the first and second error cases. Create a handler for this type of error. In the handler, check the first or second special case and process it with a water... | 5,671 |
39,902,759 | I have a cube of size `N * N * N`, say `N=8`. Each dimension of the cube is discretised to 1, so that I have labelled points `(0,0,0), (0,0,1)..(N,N,N)`. At each labelled points, I would like to assign a random value, and thus produce an array which stores value at each vertex. For example `val[0,0,0]=1, val[0,0,1]=1.2... | 2016/10/06 | [
"https://Stackoverflow.com/questions/39902759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6700176/"
] | You could simply generate lists of lists. While not in any way efficient, it would allow you to access your cube like `val[0][0][0]`.
```
arr = [[[] for _ in range(8)] for _ in range(8)]
arr[0][0].append(1)
``` | For large matrices, look into using `numpy`. This is the problem that it's designed to solve | 5,672 |
53,480,515 | Note: I am quite new to Python so the problem could be anything.
* Python: 3.6
* MySQL: 8
I have a MySQL database setup and can successfully query from it through Python, so I am sure my connection is OK. I can insert records inside MySQL Workbench, so I am fairly sure the DB is OK. However, when I run the following ... | 2018/11/26 | [
"https://Stackoverflow.com/questions/53480515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/546813/"
] | I thin you should close your cursor. And your connection is autocommited?
Plese check it, and you should commit it! | I don't see anything obvious, though I have a suggestion.
The same way you created the query above before executing it,
do the same below and print it before execution so you can be sure
what you are executing. As a general rule I don't construct query
strings within the execute function. I don't see a close which mig... | 5,674 |
36,490,093 | Can anyone tell me how to use if statement in python for the difference between the two nos is 1..??
I have written like below and I am getting error
if num1 = num2 + 1:
what should be the content with if? | 2016/04/08 | [
"https://Stackoverflow.com/questions/36490093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6174977/"
] | Your guess was mostly correct. It's not that the passing of references was a problem, is that after all the references got passed around, here, and there, and everywhere, the object that was referenced went out of scope and got destroyed, with the reference left hanging around. Using the reference at that point becomes... | I changed the line:
const vector >& \_cycles;
to
const vector > \_cycles;
and everything worked fine! | 5,675 |
44,933,326 | I am having problems connecting to my database through postgreSQL3 version 9.5. However, after running the code below:
```
import psycopg2 as p
con = p.connect("dbname ='dvdrental' user = 'myusername' host ='localhost' password ='somepassword'")
cur = con.cursor()
cur.execute("select * from title")
rows = cur.fetchal... | 2017/07/05 | [
"https://Stackoverflow.com/questions/44933326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7620397/"
] | Check the listen adresses of postgres, using `netstat` (from the shell):
---
```
plasser@pisbak$ netstat -nl |grep 5432
tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN
tcp6 0 0 :::5432 :::* LISTEN
unix 2 [ ACC ] STREAM LI... | what if you add `port = '5433'` to your `p.connect` line?
```
import psycopg2 as p
con = p.connect("dbname ='dvdrental' user = 'myusername' host ='localhost' password ='somepassword' port='5433'")
cur = con.cursor()
cur.execute("select * from title")
rows = cur.fetchall()
``` | 5,678 |
34,936,039 | Env: Windows 10 Pro
I installed python 2.7.9 and using `pip` installed `robotframework` and `robotframework-selenium2library` and it all worked fine with no errors.
Then I was doing some research and found that unless there is a reason for me to use 2.x versions of Python, I should stick with 3.x versions. Since 3.4 ... | 2016/01/21 | [
"https://Stackoverflow.com/questions/34936039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4496252/"
] | You need to assign `heroclass.toLowerCase();` to the original value of `heroclass`:
```
heroclass = heroclass.toLowerCase();
```
If you do not do this, the lowercase version of heroclass is not saved. | Put your loop in a labeled block:
```
myblock: {
while (true) {
//code
heroclass = heroclass.toLowerCase();
switch(heroclass)
{
case "slayer": A = "text";
break myblock;
//repeat with other cases
}
}
}
//goes to here when you say ... | 5,679 |
73,616,000 | I want to hide this warning `UserWarning: pandas only support SQLAlchemy connectable(engine/connection) ordatabase string URI or sqlite3 DBAPI2 connectionother DBAPI2 objects are not tested, please consider using SQLAlchemy` and I've tried
```
import warnings
warnings.simplefilter(action='ignore', category=UserWarning... | 2022/09/06 | [
"https://Stackoverflow.com/questions/73616000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8089312/"
] | It seems I cannot disable the pandas warning, so I used SQLAlchemy (as the warning message wants me to do so) to wrap the psycopg2 connection.
I followed the instruction here: [SQLAlchemy for psycopg2 documentation](https://docs.sqlalchemy.org/en/14/dialects/postgresql.html#module-sqlalchemy.dialects.postgresql.psycop... | The warnings that you're filtering right now are warnings of type `FutureWarning`. The warning that you're getting is of type `UserWarning`, so you should change the warning category to `UserWarning`. I hope [this](https://stackoverflow.com/a/71083448/8293793) answers your question regarding why pandas is giving that w... | 5,684 |
6,595,673 | I'm trying to read a column oriented csv file into R as a data frame.
the first line of the file is like so:
`sDATE, sTIME,iGPS_ALT, ...`
and then each additional line is a measurement:
`4/10/2011,2:15,78, ...`
when I try to read this into R, via
`d = read.csv('filename')`
I get a duplicate row.names error since... | 2011/07/06 | [
"https://Stackoverflow.com/questions/6595673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3926/"
] | `read.csv` only assumes there are any row names if there are less values in the header than in the other rows. So somehow you are either missing a column name or have an extra column you don't want. | You probably DO have an extra column.
But it probably arises from a stray formatted cell (or column of cells) that is actually empty, to the right of your data in your original spreadsheet.
Here is the key: Excel will save empty fields in the CSV file for any empty cells that are formatted in your sheet.
Here is ... | 5,685 |
43,882,498 | The following code is my pipeline for reading images and labels from files:
```
import tensorflow as tf
import numpy as np
import tflearn.data_utils
from tensorflow.python.framework import ops
from tensorflow.python.framework import dtypes
import sys
#process labels in the input file
def process_label(label):
inf... | 2017/05/10 | [
"https://Stackoverflow.com/questions/43882498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332289/"
] | `tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)` is called by the table view each time it needs a new cell.
If only 12 cells are visible at a time then the table view initially needs only 12 cells so will ask for only 12 cells. You'd have to scroll before it would need to ask for more. It won't... | So interestingly, even though the table is displaying correctly, the printout only reaches 12, and that happens regardless of how many cells you scroll to. Is that what you are finding? This is because you have 12 rows in a view, and the cells are reused, so you are not creating more cells but you are just reusing the ... | 5,690 |
23,271,575 | I'm trying to get text to display as bold, or in colors, or possibly in italics, in ipython's qtconsole.
I found this link: [How do I print bold text in Python?](https://stackoverflow.com/questions/8924173/python-print-bold-text), and used the first and second answers, but in qtconsole, only the underlining option wor... | 2014/04/24 | [
"https://Stackoverflow.com/questions/23271575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3566002/"
] | Those are ANSI escapes, special sequences of characters which terminals process to switch font styles. The Qt console interprets some of them, but not all of the ones that serious terminals do. This sequence works to print in red, for instance:
```
print('\x1b[1;31m'+'Hello world'+'\x1b[0m')
```
However, if you're t... | If you mean the body text of the iPython notebook (Markdowns), you can put 2 underline characters directly before and after your text to make it **BOLD**:
`__BOLD TEXT__` => **BOLD TEXT**
if you put a backslash before that, it will be counteracted:
`\__BOLD TEXT__` => \_\_BOLD TEXT\_\_ | 5,691 |
17,128,878 | I was trying to install `autoclose.vim` to Vim. I noticed I didn't have a `~/.vim/plugin` folder, so I accidentally made a `~/.vim/plugins` folder (notice the extra 's' in plugins). I then added `au FileType python set rtp += ~/.vim/plugins` to my .vimrc, because from what I've read, that will allow me to automatically... | 2013/06/15 | [
"https://Stackoverflow.com/questions/17128878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2467761/"
] | [:help load-plugins](http://vimdoc.sourceforge.net/htmldoc/starting.html#load-plugins) outlines how plugins are loaded.
Adding a folder to your `rtp` alone does not suffice; it must have a `plugin` subdirectory. For example, given `:set rtp+=/tmp/foo`, a file `/tmp/foo/plugin/bar.vim` would be detected and loaded, but... | You are on the right track with `set rtp+=...` but there's a bit more to it (`rtp` is non-recursive, help indexing, many corner cases) than what meets the eye so it is not a very good idea to do it by yourself. Unless you are ready for a months-long drop in productivity.
If you want to store all your plugins in a spec... | 5,699 |
53,494,097 | I am trying to get hands on with selenium and webdriver with python.
```
from selenium import webdriver
PROXY = "119.82.253.95:61853"
url = 'http://google.co.in/search?q=book+flights'
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % PROXY)
driver = webdriver.Chrome(options... | 2018/11/27 | [
"https://Stackoverflow.com/questions/53494097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954789/"
] | `fscanf` is a non-starter. The only way to read empty fields would be to use `"%c"` to read delimiters (and that would require you to know which fields were empty beforehand -- not very useful) Otherwise, depending on the *format specifier* used, `fscanf` would simply consume the `tabs` as leading whitespace or experie... | >
> I wanna use fscanf to read consecutive tabs as empty fields and store them in a structure.
>
>
>
Ideally, code should read a *line*, as with `fgets()` and then parse the *string*.
Yet staying with `fscanf()`, this can be done in a loop.
---
The main idea is to use `"%[^/t/n]"` to read one token. If the next... | 5,704 |
63,322,884 | I have a python script that is responsible for verifying the existence of a process with its respective name, I am using the pip module `pgrep`, the problem is that it does not allow me to kill the processes with the kill module of pip or with the of `os.kill` because there are several processes that I want to kill and... | 2020/08/09 | [
"https://Stackoverflow.com/questions/63322884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14063362/"
] | You would loop over processes using a `for` loop. Ideally you should send a `SIGTERM` before resorting to `SIGKILL`, because it can allow processes to exit more gracefully.
```
import time
import os
import signal
# send all the processes a SIGTERM
for p in pid:
os.kill(p, signal.SIGTERM)
# give them a short time... | Try this it may work
```
processes = {'pro1', 'pro2', 'pro3'}
for proc in psutil.process_iter():
if proc.name() in processes:
proc.kill()
```
For more information you can refer [here](https://psutil.readthedocs.io/en/latest/) | 5,705 |
53,546,396 | How to reduce numbers in python after comma without rounding
Example : I have x = 2.97656
I want it to be 2.9 not 3.0
Thank you | 2018/11/29 | [
"https://Stackoverflow.com/questions/53546396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9705031/"
] | If you don't want to use `math.round()` you can use `math.floor()`:
```
import math
x = 2.97656
print(math.floor(x * 10) / 10)
#Output = 2.9
``` | you can use round(var , number precision )
see this link please to more info
**<https://www.geeksforgeeks.org/precision-handling-python/>** | 5,706 |
64,575,636 | I'm trying to convert json data into a dict by using load() but I'm unable to do so if I have more than one object. For example, the code below works perfectly, I can dump 'dog' into a json file and then I can load 'dog' and print it out as a dict.
```
import json
dog = {
"name":"Sally",
"color": "yel... | 2020/10/28 | [
"https://Stackoverflow.com/questions/64575636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14209856/"
] | You should only have one json thing you dump to a file. `json.load` will try to load the whole file, it doesn't find the first instance of a valid json object
You could combine them into an array
```
j_obj = [dog, cat]
```
Or create a new dict
```
j_obj = {'dog': dog, 'cat': cat}
```
Then `j_obj` can be dumped t... | The JSON module doesn't append it automatically.
If you want your JSON to contain a number of objects use an array as insert your dictionaries into it. the dump the array | 5,707 |
63,074,629 | I am a newbie to a python dictionary. Excume me for my mistakes.
I want to create a list of **all** the keys which have a Maximum and Minimum values from Python Dictionary. I searched it about on Google but didn't get any answer.
I have written the following code:
```
a = {1:1, 2:3, 4:3, 3:2, 5:1, 6:3}
maxi = [keys ... | 2020/07/24 | [
"https://Stackoverflow.com/questions/63074629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13285566/"
] | The `ngModel` binding might have precedence here. You could ignore the `value` attribute and set `updatedStockValue` in it's definition.
Try the following
```js
@Component({
selector: 'app-stock-status',
template:`
<input type="number" min="0" required [(ngModel)]="updatedStockValue"/>
<button class="btn btn-... | You can initialize a variable in the template with ng-init if you don't want to do it in the controller.
```
<input type="number" min='0' required [(ngModel)]='updatedStockValue'
ng-init="updatedStockValue=0"/>
``` | 5,709 |
68,500,403 | I am using Pandas to analyze a dataset which includes a column named "Age on Intake" (floating numbers). I had been trying to further categorize the data into a few small age buckets using the function I wrote. However, I keep getting the error **"*'<=' not supported between instances of 'str' and 'int'*"**. How could ... | 2021/07/23 | [
"https://Stackoverflow.com/questions/68500403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16494766/"
] | `for` loops in Rust act on iterators, so if you want succinct semantics, change your code to use them. There's not really that much other choice - what's ergonomic in C isn't necessarily ergonomic in Rust, and vice versa.
If your `next` functions follow a common pattern, you can create a structure that implements `Ite... | It would be most idiomatic to convert the code to use an `Iterator`, but that is "non-trivial" in this case due to how next works. The simplest version I could create was to create that was similar to the C code yet IMO reasonably idiomatic was to create an `on_each` style function that accepts a closure.
```
#[derive... | 5,710 |
55,639,746 | I am new to python and Jupyter Notebook
The objective of the code I am writing is to request the user to introduce 10 different integers. The program is supposed to return the highest odd number introduced previously by the user.
My code is as followws:
```
i=1
c=1
y=1
while i<=10:
c=int(input('Enter an i... | 2019/04/11 | [
"https://Stackoverflow.com/questions/55639746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10023598/"
] | You have `elif c > y`, you should just need to add a colon there so it's `elif c > y:` | Yup.
```
i=1
c=1
y=1
while i<=10:
c=int(input('Enter an integer number: ')) # This line was off
if c%2==0:
print('The number is even')
elif c> y: # Need also ':'
y=c
print('y')
i=i+1
``` | 5,711 |
32,893,568 | I'm trying to parse json string with an escape character (Of some sort I guess)
```
{
"publisher": "\"O'Reilly Media, Inc.\""
}
```
Parser parses well if I remove the character `\"` from the string,
the exceptions raised by different parsers are,
**json**
```
File "/usr/lib/python2.7/json/__init__.py", line... | 2015/10/01 | [
"https://Stackoverflow.com/questions/32893568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4597501/"
] | You almost certainly did not define properly escaped backslashes. If you define the string properly the JSON parses *just fine*:
```
>>> import json
>>> json_str = r'''
... {
... "publisher": "\"O'Reilly Media, Inc.\""
... }
... ''' # raw string to prevent the \" from being interpreted by Python
>>> json.loads(js... | Your JSON is invalid. If you have questions about your JSON objects, you can always validate them with [JSONlint](http://jsonlint.com). In your case you have an object
```
{
"publisher": "\"O'Reilly Media, Inc.\"",
}
```
and you have an extra comma indicating that something else should be coming. So JSONlint yields
... | 5,713 |
35,901,517 | I get the following error when I run my code which has been annotated with @profile:
```
Wrote profile results to monthly_spi_gamma.py.prof
Traceback (most recent call last):
File "/home/james.adams/anaconda2/lib/python2.7/site-packages/kernprof.py", line 233, in <module>
sys.exit(main(sys.argv))
File "/home/j... | 2016/03/09 | [
"https://Stackoverflow.com/questions/35901517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85248/"
] | I worked this out by using the -l option, i.e.
```
$ kernprof.py -l my_code.py
``` | ```
kernprof -l -b web_app.py
```
This worked for me, if we see
```
kernprof --help
```
we see an option to include in builtin namespace
```
usage: kernprof [-h] [-V] [-l] [-b] [-o OUTFILE] [-s SETUP] [-v] [-u UNIT]
[-z]
script ...
Run and profile a python script.
positional argu... | 5,714 |
32,838,802 | Say that I have a color image, and naturally this will be represented by a 3-dimensional array in python, say of shape (n x m x 3) and call it img.
I want a new 2-d array, call it "narray" to have a shape (3,nxm), such that each row of this array contains the "flattened" version of R,G,and B channel respectively. More... | 2015/09/29 | [
"https://Stackoverflow.com/questions/32838802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4929035/"
] | You need to use [`np.transpose`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html) to rearrange dimensions. Now, `n x m x 3` is to be converted to `3 x (n*m)`, so send the last axis to the front and shift right the order of the remaining axes `(0,1)`. Finally , reshape to have `3` rows. Thus, th... | [ORIGINAL ANSWER]
Let's say we have an array `img` of size `m x n x 3` to transform into an array `new_img` of size `3 x (m*n)`
Initial Solution:
```
new_img = img.reshape((img.shape[0]*img.shape[1]), img.shape[2])
new_img = new_img.transpose()
```
[EDITED ANSWER]
**Flaw**: The reshape starts from the first dimen... | 5,715 |
71,140,438 | I am a beginner in Python and would really appreciate if someone could help me with the following:
I would like to run this script 10 times and for that change for every run the sub-batch (from 0-9):
E.g. the first run would be:
```
python $GWAS_TOOLS/gwas_summary_imputation.py \
-by_region_file $DATA/eur_ld.bed.gz \... | 2022/02/16 | [
"https://Stackoverflow.com/questions/71140438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18222525/"
] | While we can't show you how to retrofit a loop to the python code without actually seeing the python code, you could just use a shell loop to accomplish what you want without touching the python code.
For bash shell, it would look like this:
```
for sub_batch in {0..9}; do \
python $GWAS_TOOLS/gwas_summary_imputatio... | a loop in python from 0 to 10 is very easy.
```py
for i in range(0, 10):
do stuff
``` | 5,718 |
36,680,407 | I on RHEL6 with Python 2.6 and need to install rrdtool with python. I have to upload and install packages manually as network admin blocks yum and pip outgoing traffic for security reason. During installation I encounter missing error missing rrdtoolmodule.c, where can I locate the file? or I missing something?
```
[u... | 2016/04/17 | [
"https://Stackoverflow.com/questions/36680407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/79311/"
] | The one-hour difference is due to Daylight Savings Time, which by definition is not reflected in Unix timestamps.
You may want to consider [moment-timezone.js](http://momentjs.com/timezone/docs/) to cope with DST in time conversions. | You can use [Date.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) in javascript.
```js
const isoDate = new Date();
const convertToUnix = Date.parse(isoDate.toISOString());
``` | 5,720 |
8,198,162 | I have a script for deleting images older than a date.
Can I pass this date as an argument when I call to run the script?
Example: This script `delete_images.py` deletes images older than a date (YYYY-MM-DD)
```
python delete_images.py 2010-12-31
```
Script (works with a fixed date (xDate variable))
```
import os... | 2011/11/19 | [
"https://Stackoverflow.com/questions/8198162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/871976/"
] | The quick but crude way is to use `sys.argv`.
```
import sys
xDate = sys.argv[1]
```
A more robust, extendable way is to use the [argparse](http://docs.python.org/library/argparse.html#module-argparse) module:
```
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('xDate')
args=parser.parse_args(... | The command line options can be accessed via the list `sys.argv`. So you can simply use
```
xDate = sys.argv[1]
```
(`sys.argv[0]` is the name of the current script.) | 5,721 |
47,555,613 | It appears, based on a [urwid example](http://urwid.org/tutorial/#horizontal-menu) that `u'\N{HYPHEN BULLET}` will create a unicode character that is a hyphen intended for a bullet.
The names for unicode characters seem to be defined at [fileformat.info](http://www.fileformat.info/info/unicode/char/b.htm) and some el... | 2017/11/29 | [
"https://Stackoverflow.com/questions/47555613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4360746/"
] | Not every gory detail can be found in a how-to. The [table of escape sequences](https://docs.python.org/2/reference/lexical_analysis.html#string-literals) in the reference manual includes:
Escape Sequence: `\N{name}`
Meaning: Character named `name` in the Unicode database (Unicode only) | The `\N{}` syntax is documented in the [Unicode HOWTO](https://docs.python.org/3/howto/unicode.html?highlight=unicode%20howto#the-string-type), at least.
The names are documented in the Unicode standard, such as:
```
http://www.unicode.org/Public/UCD/latest/ucd/NamesList.txt
```
The `unicodedata` module can look up... | 5,726 |
55,837,477 | convert all txt files delimiter '|' from dir path and convert to csv and save in a location using python?
i have tried this code which is hardcoded.
```
import csv
txt_file = r"SentiWS_v1.8c_Positive.txt"
csv_file = r"NewProcessedDoc.csv"
with open(txt_file, "r") as in_text:
in_reader = csv.reader(in_text, deli... | 2019/04/24 | [
"https://Stackoverflow.com/questions/55837477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11186737/"
] | You are trying to instantiate a typealias and are getting `interface doesn't have a constructor` error. To my understanding, typealias with function types work with three steps:
1. Define the typealias itself
```
typealias MyHandler = (Int, String) -> Unit
```
2. declare an action of that type
```
val myHandler: My... | `typealias` are just an alias for the type :) in other words, it's just another name for the type.
Imagine having to write all the time `(Int, String) -> Unit`. With `typealias` you can define something like you did to help out and write less,i.e. instead of:
```
fun Foo(handler: (Int, String) -> Unit)
```
You can... | 5,728 |
50,279,728 | I have a code like this:
```
x = []
for fitur in self.fiturs:
x.append(fitur[0])
a = [x , rpxy_list]
join = zip(*a)
print join
```
and in the self.fiturs is:
```
F1,1,1,1,1,0,1,1,0,0,1
F2,1,0,0,0,0,0,1,0,1,1
F3,1,0,0,0,0,0,1,1,1,1
F4,1,0,0,0,0,0,1,1,1,0
F5,14,24,22,22,22,16,18,19,26,22
F6,8.0625,6.2,6.2609,6.68... | 2018/05/10 | [
"https://Stackoverflow.com/questions/50279728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9665999/"
] | It look okay for the most part,
With Spark 2 you can try something like this by eliminating extra values there,
```
case class Rating(name:Int, product:Int, rating:Int)
val spark:SparkSession = ???
val df = spark.read.csv("/path/to/file")
.map({
case Row(u: Int, p: Int, r:Int) => Rating(u, p, r)
})
```
Hope this ... | my problem was related with NaN values down the road.
I got it fixed using this:
predictions.select([to\_null(c).alias(c) for c in predictions.columns]).na.drop()
also I had to import "from pyspark.sql.functions import col, isnan, when, trim" | 5,731 |
45,690,043 | I have a str like
`rjg[]u[ur"fur[ufrng[]"gree`,
and i want to replace "[" and "]" between "" with #οΌthe result is
`rjg[]u[ur"fur[ufrng[]"gree` => `rjg[]u[ur"fur#ufrng##"gree`,
how can i get this in python? | 2017/08/15 | [
"https://Stackoverflow.com/questions/45690043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6298732/"
] | One liner solution:
```
import re
text = 'rjg[]u[ur"fur[ufrng[]"gree'
text = re.sub(r'(")([^"]+)(")', lambda pat: pat.group(1)+pat.group(2).replace(']', '#').replace('[', '#')+pat.group(3), text)
print text
```
Output:
```
rjg[]u[ur"fur#ufrng##"gree
``` | I would try
```
L = data.split('"')
for i in range(1, len(L), 2):
L[i] = re.sub(r'[\[\]]', '#', L[i])
result = '"'.join(L)
``` | 5,732 |
49,638,674 | I have a string `s`, and I want to remove `'.mainlog'` from it. I tried:
```
>>> s = 'ntm_MonMar26_16_59_41_2018.mainlog'
>>> s.strip('.mainlog')
'tm_MonMar26_16_59_41_2018'
```
Why did the `n` get removed from `'ntm...'`?
Similarly, I had another issue:
```
>>> s = 'MonMar26_16_59_41_2018_rerun.mainlog'
>>> s.str... | 2018/04/03 | [
"https://Stackoverflow.com/questions/49638674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/868546/"
] | From Python documentation:
<https://docs.python.org/2/library/string.html#string.strip>
Currently, it tries to strip all the characters which you mentioned ('.', 'm', 'a', 'i'...)
You can use string.replace instead.
```
s.replace('.mainlog', '')
``` | You are using the wrong function. `strip` removes characters from the beginning and end of the string. By default spaces, but you can give a list of characters to remove.
You should use instead:
```
s.replace('.mainlog', '')
```
Or:
```
import os.path
os.path.splitext(s)[0]
``` | 5,737 |
44,218,387 | This is what I encountered when trying to import thread package:
`>>> import thread
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packag
es/thread.py", line 3
print('This is ultran00b's package - thread')`
I tried u... | 2017/05/27 | [
"https://Stackoverflow.com/questions/44218387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7074612/"
] | thread module was deprecated in python 3. Try threading instead:
```
import threading
``` | You are trying to import the thread class ?
Use :
```
from threading import Thread
``` | 5,742 |
2,990,819 | I'm looking for the templates engine for Java with syntax like in Django templates or Twig (PHP). Does it exists?
Update:
The target is to have same templates files for different languages.
```
<html>
{{head}}
{{ var|escape }}
{{body}}
</html>
```
can be rendered from python (Django) code as well as from PHP, using... | 2010/06/07 | [
"https://Stackoverflow.com/questions/2990819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108826/"
] | * <http://www.jangod.org/> (There is now also <https://github.com/HubSpot/jinjava>)
* run django via jython on jvm
* use <http://mustache.github.com/> | Sure, there are all sorts of template engines for Java. I've used FreeMarker, Velocity and StringTemplate. I'm not sure what you mean by Django-like syntax; each engine has it's own variations on a templating approach.
For a comparison of some different engines check out [here](http://java-source.net/open-source/templ... | 5,743 |
55,656,522 | I installed Python 3.7.3 on windows 10, but I can't install Python packages via PIP in Gitbash (Git SCM), due to my company's internet proxy.
I tryed to create environment variables for the proxy via the following, but it didn't work:
* export http\_proxy='proxy.com:8080'
* export https\_proxy='proxy.com:8080'
I fou... | 2019/04/12 | [
"https://Stackoverflow.com/questions/55656522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8691122/"
] | One approach here would be to use lookarounds to ensure that you match *only* islands of exactly two sixes:
```
String regex = "(?<!6)66(?!6)";
String text = "6678793346666786784966";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
```
This finds a count of two, for the input stri... | You need to use
```
String regex = "(?<!6)66(?!6)";
```
See the [regex demo](https://regex101.com/r/3QHER6/2).
[](https://i.stack.imgur.com/6b4St.png)
**Details**
* `(?<!6)` - no `6` right before the current location
* `66` - `66` substring
* `(?... | 5,751 |
19,838,976 | What's the most pythonic way of joining a list so that there are commas between each item, except for the last which uses "and"?
```
["foo"] --> "foo"
["foo","bar"] --> "foo and bar"
["foo","bar","baz"] --> "foo, bar and baz"
["foo","bar","baz","bah"] --> "foo, bar, baz and bah"
``` | 2013/11/07 | [
"https://Stackoverflow.com/questions/19838976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1277170/"
] | The fix based on the comment led to this fun way. It assumes no commas occur in the string entries of the list to be joined (which would be problematic anyway, so is a reasonable assumption.)
```
def special_join(my_list):
return ", ".join(my_list)[::-1].replace(",", "dna ", 1)[::-1]
In [50]: def special_join(my_... | In case you need a solution where negative indexing isn't supported (i.e. Django QuerySet)
```
def oxford_join(string_list):
if len(string_list) < 1:
text = ''
elif len(string_list) == 1:
text = string_list[0]
elif len(string_list) == 2:
text = ' and '.join(string_list)
else:
... | 5,753 |
13,555,386 | I try to start a Celery worker server from a command line:
```
celery -A tasks worker --loglevel=info
```
The code in tasks.py:
```
import os
os.environ[ 'DJANGO_SETTINGS_MODULE' ] = "proj.settings"
from celery import task
@task()
def add_photos_task( lad_id ):
...
```
I get the next error:
```
Traceback (most... | 2012/11/25 | [
"https://Stackoverflow.com/questions/13555386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/749288/"
] | I forgot to create a celery object in tasks.py:
```
from celery import Celery
from celery import task
celery = Celery('tasks', broker='amqp://guest@localhost//') #!
import os
os.environ[ 'DJANGO_SETTINGS_MODULE' ] = "proj.settings"
@task()
def add_photos_task( lad_id ):
...
```
After that we could normally sta... | When you run `celery -A tasks worker --loglevel=info`, your celery app should be exposed in the module `tasks`. It shouldn't be wrapped in a function or an `if` statements that.
If you `make_celery` in another file, you should import the celery app in to your the file you are passing to celery. | 5,763 |
31,800,998 | Issue: Remove the hyperlinks, numbers and signs like `^&*$ etc` from twitter text. The tweet file is in CSV tabulated format as shown below:
```
s.No. username tweetText
1. @abc This is a test #abc example.com
2. @bcd This is another test #bcd example.com
```
Being a novice at python, I search and ... | 2015/08/04 | [
"https://Stackoverflow.com/questions/31800998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4195053/"
] | To remove `&` from string you can use [html\_entity\_decode](http://php.net/manual/en/function.html-entity-decode.php)
```
while ($row = mysql_fetch_array($result)) {
$row['value'] = html_entity_decode($row['value']);
$row['id'] = (int) $row['client_id'];
$row_set[] = $row;
}
``` | Change this `htmlentities` to this `html_entity_decode()`
So **final Code will** be
```
$term = trim(strip_tags($_GET['term']));
$term = str_replace(' ', '%', $term);
$qstring = "SELECT name as value, client_id FROM goa WHERE name LIKE '" . $term . "%' limit 0,5000";
$result = mysql_query($qstring);
$qcount = 0;
if (... | 5,773 |
58,926,146 | I trained a model with RBF kernel-based support vector machine regression. I want to know the features that are very important or major contributing features for the RBF kernel-based support vector machine. I know there is a method to know the most contributing features for linear support vector regression based on wei... | 2019/11/19 | [
"https://Stackoverflow.com/questions/58926146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8739662/"
] | Let me sort the comments as an answer:
As you can read [here](https://stackoverflow.com/questions/52640386/how-do-i-solve-the-future-warning-min-groups-self-n-splits-warning-in):
>
> Weights asigned to the features (coefficients in the primal
> problem). This is only available in the case of linear kernel.
>
>
> ... | In relation with the inspection of non linear SVM models (e.g. using RBF kernel), here I share an answer posted in another thread which might be useful for this purpose.
The method is based on "[sklearn.inspection.permutation\_importance](https://stackoverflow.com/a/67910281/13670156)".
And here, a compressive discus... | 5,774 |
42,149,079 | I've managed to install pymol on windows following the instructions [here](https://stackoverflow.com/questions/27885397/how-do-i-install-a-python-package-with-a-whl-file) and using the file Pmwβ2.0.1βpy2βnoneβany.whl from [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymol)
Various folders have appeared in `C:\Use... | 2017/02/09 | [
"https://Stackoverflow.com/questions/42149079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2923519/"
] | Try changing
```
lastRow44 = Cells(Rows.Count, "A").End(xlUp).Row
LastRow3 = Worksheets("Temp").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).Row
```
to
```
lastRow44 = Sheets("Temp").Cells(Rows.Count, 1).End(xlUp).Row
LastRow3 = Worksheets("Temp").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
```
Also, I am n... | How about something like that:
```
lastRow44 = Cells(Rows.Count, "A").End(xlUp).Row
For x = 50 To LastRow3
Range("A" & x).Formula = "=Sum(""M""" & x & "": M "" & lastRow44 & ")"
Next x
``` | 5,775 |
40,687,397 | I am trying to update my chromedriver.exe file as outlined here.
[Python selenium webdriver "Session not created" exception when opening Chrome](https://stackoverflow.com/questions/40373801/python-selenium-webdriver-session-not-created-exception-when-opening-chrome)
The problem is, I do not know the location of the o... | 2016/11/18 | [
"https://Stackoverflow.com/questions/40687397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5960274/"
] | If you don't want to expose your constructors for some reasons, you can easily hide them behind a factory method based on templates and perfect forwarding:
```
class Foo {
// defined somewhere
Foo( Param1, Param2 );
Foo( Param1, Param3, Param4 );
Foo( Param1, Param4 );
Foo( Param1, Param2, Param4 )... | As an user, I prefer
```
Foo* CreateFoo(Param1* P1, Param2* P2, Param3* P3, Param4* P4);
```
Why should I construc a `struct` just to pass some (maybe NULL) parameters? | 5,776 |
72,173,142 | I need to create a fΓ³rmula that when it is dragged down it jumps a certain pre defined number of cells. For example, I have this column:
[](https://i.stack.imgur.com/y7c78.png)
However I want a formula that when I drag down it jumps 6 rows, something... | 2022/05/09 | [
"https://Stackoverflow.com/questions/72173142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5606352/"
] | Try in B2
```
=offset($A$1;5*row(A2)-10;)
``` | try instead:
```
=QUERY(A1:A; "skipping 5"; 0)
```
[](https://i.stack.imgur.com/09MiK.png) | 5,777 |
41,131,038 | Given an interactive python script
```
#!/usr/bin/python
import sys
name = raw_input("Please enter your name: ")
age = raw_input("Please enter your age: ")
print("Happy %s.th birthday %s!" % (age, name))
while 1:
r = raw_input("q for quit: ")
if r == "q":
sys.exit()
```
I want to interact with it f... | 2016/12/13 | [
"https://Stackoverflow.com/questions/41131038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1922202/"
] | Storing an unsigned integer straight *in* a pointer portably isn't allowed, but you can:
* do the reverse: you can store your pointer in an unsigned integer; specifically, `uintptr_t` is explicitly guaranteed by the standard to be big enough to let pointers survive the roundtrip;
* use a `union`:
```
union NodePtr {
... | Well, you can store int as a pointer with casts:
```
uint32_t i = 123;
Octree* ptr = reinterpret_cast<Octree*>(i);
uint32_t ii = reinterpret_cast<uint32_t>(ptr);
std::cout << ii << std::endl; //Prints 123
```
But if you do it this way I can't see how you detect that a given Octree\* actually stores data and is not a... | 5,778 |
12,569,356 | I'm a very beginner with Python classes and JSON and I'm not sure I'm going in the right direction.
Basically, I have a web service that accepts a JSON request in a POST body like this:
```
{ "item" :
{
"thing" : "foo",
"flag" : true,
"language" : "en_us"
},
"numresults" : 3
}
```
I st... | 2012/09/24 | [
"https://Stackoverflow.com/questions/12569356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/476638/"
] | just add one method to your class that returns a dictionary
```
def jsonify(self):
return { 'Class Whatever':{
'data1':self.data1,
'data2':self.data2,
...
}
}
```
and call your tojson function on the result ... or call it before you... | Take a look at the [`colander` project](http://docs.pylonsproject.org/projects/colander/en/latest/); it let's you define an object-oriented 'schema' that is easily serializable to and from JSON.
```
import colander
class Item(colander.MappingSchema):
thing = colander.SchemaNode(colander.String(),
... | 5,779 |
6,800,280 | This is a follow-up to this previous question: [Complicated COUNT query in MySQL](https://stackoverflow.com/questions/6580684/complicated-count-query-in-mysql). None of the answers worked under all conditions, and I have had trouble figuring out a solution as well. I will be awarding a 75 point bounty to the first pers... | 2011/07/23 | [
"https://Stackoverflow.com/questions/6800280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/651174/"
] | Couldn't there be problem with `<Files .*>`? I think this is a wildcard pattern so you should use just `<Files *>`. | The order of your htaccess, should be...
```
RewriteEngine On
<Files .*>
Order allow,deny
Allow from all
</Files>
Options FollowSymLinks
RewriteRule ^photos.+$ thumbs.php [L,QSA]
RewriteRule ^[a-zA-Z0-9\-_]*$ index.php [L,QSA]
RewriteRule ^[a-zA-Z0-9\-_]+\.html$ index.php [L,QSA]
``` | 5,782 |
44,732,839 | I am trying to process txt file using pandas.
However, I get following error at read\_csv
>
> CParserError Traceback (most recent call
> last) in ()
> 22 Col.append(elm)
> 23
> ---> 24 revised=pd.read\_csv(Path+file,skiprows=Header+1,header=None,delim\_whitespace=True)
> 25
> 26 TimeSeries.append(revised)... | 2017/06/24 | [
"https://Stackoverflow.com/questions/44732839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7124344/"
] | It fails because the part of the file you're reading looks like this:
```
Timestamp Trend Flags Status Value (ΒΊC)
------------------------- ----------- ------ ----------
20-Oct-12 8:00:00 PM HKT {start} {ok} 15.310 ΒΊC
21-Oct-12 12:00:00 AM HKT { } {ok} 15.130 ΒΊC
```
But... | Include This line before
========================
```
file_name = Path+file #change below line to given
```
>
> revised=pd.read\_csv(Path+file,skiprows=Header+1,header=None,delim\_whitespace=True)
> revised=pd.read\_csv(file\_name,skiprows=Header+1,header=None,sep=" ")
>
>
> | 5,784 |
27,647,922 | I'm working on my python script as I'm created a list to stored the elements in the arrays.
I have got a problem with the if statement. I'm trying to find the elements if I have the values `375` but it won't let me to get pass on the if statement.
Here is the code:
```
program_X = list()
#create the rows to count f... | 2014/12/25 | [
"https://Stackoverflow.com/questions/27647922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4275381/"
] | As the `program_x` contains string elements :
```
program_X = map(str, program_X)
^
```
you need to change the following :
```
if pos_X == 375
```
to
```
if pos_X == '375'
``` | If you are storing strings in list that way,
```
program_X = ['14:08:55 T:1260 NOTICE: 8081.35', ...]
```
Then use `in` keyword to check the word
```
for pos_X in programs_X:
#find the position with 375
if '375' in pos_X:
print pos_X
``` | 5,785 |
45,692,894 | Problem
-------
Some reoccurring events, that don't really end at some point (like club meetings?), depend on other conditions (like holiday season). However, manually adding these exceptions would be necessary every year, as the dates might differ.
**Research**
* I have found out about `exdate` (see the image of... | 2017/08/15 | [
"https://Stackoverflow.com/questions/45692894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4550784/"
] | [RFC2445 defines an `EXRULE`](https://www.rfc-editor.org/rfc/rfc2445#section-4.8.5.2) (exception rule) property. You can use that in addition to the `RRULE` to define recurring exceptions.
However, RFC2445 was superseded by [RFC5545, which unfortunately deprecates the `EXRULE`](https://www.rfc-editor.org/rfc/rfc5545#a... | `BYMONTH` would be another possibility, e.g. here's a rule for a club meeting that occurs the first Wednesday of every month except December (which is their Christmas party, so no business meeting)
```
RRULE:FREQ=MONTHLY;BYDAY=1WE;BYMONTH=1,2,3,4,5,6,7,8,9,10,11
``` | 5,786 |
42,519,094 | I am trying to start a Python 3.6 project by creating a virtualenv to keep the dependencies. I currently have both Python 2.7 and 3.6 installed on my machine, as I have been coding in 2.7 up until now and I wish to try out 3.6. I am running into a problem with the different versions of Python not detecting modules I am... | 2017/02/28 | [
"https://Stackoverflow.com/questions/42519094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4588188/"
] | You have to select the interpreter when you create the virtualenv.
```
virtualenv --python=PYTHON36_EXE my_venv
```
Substitute the path to your Python 3.6 installation in place of `PYTHON36_EXE`. Then after you've activated, `python` executable will be bound to 3.6 and you can just `pip install Django` as usual. | The key is that `pip` installs things for a specific version of Python, and to a very specific location. Basically, the `pip` command in your virtual environment is set up specifically for the interpreter that your virtual environment is using. So even if you explicitly call another interpreter with that environment ac... | 5,787 |
21,426,329 | I followed mbrochh's instruction <https://github.com/mbrochh/vim-as-a-python-ide> to build my vim as a python IDE. But things go wrong when openning the vim after I put `jedi-vim` into `~/.vim/bundle`. The following is the warnings
```
Error detected while processing CursorMovedI Auto commands for "buffer=1":
Tracebac... | 2014/01/29 | [
"https://Stackoverflow.com/questions/21426329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1263069/"
] | If youβre trying to use Vundle to install the jedi-vim plugin, I donβt think you should have to place it under `~/.vim/bundle`. Instead, make sure you have Vundle set up correctly, as [described in its βQuick startβ](https://github.com/gmarik/vundle#quick-start), and then try adding this line to your `~/.vimrc` after t... | make sure that you have install jedi,
I solved my problem with below command..
```
cd ~/.vim/bundle/jedi-vim
git submodule update --init
``` | 5,789 |
47,972,811 | I am on CentOs7. I installed tk, tk-devel, tkinter through yum. I can import tkinter in Python 3, but not in Python 2.7. Any ideas?
Success in Python 3 (Anaconda):
```
Python 3.6.3 |Anaconda custom (64-bit)| (default, Oct 13 2017, 12:02:49)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for mo... | 2017/12/25 | [
"https://Stackoverflow.com/questions/47972811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9139945/"
] | For python 3 use:
```
import tkinter
```
For python 2 use:
```
import Tkinter
```
If these do not work install with, for python 3:
```
sudo apt-get install python3-tk
```
or, for python 2:
```
sudo apt-get install python-tk
```
you can find more details [here](https://www.techinfected.net/2015/09/how-to-in... | For python2.7 try
```
import Tkinter
```
With a capital T. It should already be pre-installed in default centos 7 python setup, if not do `yum install tkinter` | 5,794 |
17,273,393 | In my python code I have global `requests.session` instance:
```
import requests
session = requests.session()
```
How can I mock it with `Mock`? Is there any decorator for this kind of operations? I tried following:
```
session.get = mock.Mock(side_effect=self.side_effects)
```
but (as expected) this code doesn't... | 2013/06/24 | [
"https://Stackoverflow.com/questions/17273393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1325846/"
] | Use `mock.patch` to patch session in your module. Here you go, a complete working example <https://gist.github.com/k-bx/5861641> | With some inspiration from the previous answer and :
[mock-attributes-in-python-mock](https://stackoverflow.com/questions/16867509/mock-attributes-in-python-mock)
I was able to mock a session defined like this:
```
class MyClient(object):
"""
"""
def __init__(self):
self.session = requests.sessio... | 5,795 |
68,660,419 | I don't have a lot of experience with Selenium but I am trying to run a code which search for an element in HTML with chromedriver. I keep getting an error as below. The first thing I would like to confirm is that this error cannot be due to the connection with Chromedriver to the web but is because of the way the pyth... | 2021/08/05 | [
"https://Stackoverflow.com/questions/68660419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8867871/"
] | Using `repr` or raw string on a target string is a bad idea!
By doing that newline characters are treated as literal '`\n`'.
This is likely to cause unexpected behavior on other test cases.
The real problem is that `.` matches any character **EXCEPT** newline.
If you want to match everything, replace `.` with... | You could add it as an or, but make sure you `\` in the regex string, so regex actually gets the `\n` and not a actual newline.
Something like this:
```
regex = '.*match(.|\\n)*fail.*'
```
This would match anything from the last `\n` to `match`, then any mix or number of `\n` until `testfail`. You can change this h... | 5,800 |
4,561,113 | hi
how to convert a = ['1', '2', '3', '4']
into a = [1, 2, 3, 4] in one line in python ? | 2010/12/30 | [
"https://Stackoverflow.com/questions/4561113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557854/"
] | With a list comprehension.
```
a[:] = [int(x) for x in a]
``` | With a **generator**:
```
a[:] = (int(x) for x in a)
```
... list comprehensions are so ummmmm, 2.1, don't you know?
but please be wary of replacing the contents in situ; compare this:
```
>>> a = b = ['1', '2', '3', '4']
>>> a[:] = [int(x) for x in a]
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]
```
with this:
```
>>... | 5,801 |
14,007,784 | I'm trying to create a scheduled task using the Unix `at` command. I wanted to run a python script, but quickly realized that `at` is configured to use run whatever file I give it with `sh`. In an attempt to circumvent this, I created a file that contained the command `python mypythonscript.py` and passed that to `at` ... | 2012/12/23 | [
"https://Stackoverflow.com/questions/14007784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/599391/"
] | You can use a `LEFT JOIN`, but it would be so much easier to do that if you started off by using the cleaner and more modern `JOIN` syntax:
```
SELECT c.*, d.username, d.email, e.country_name
FROM user_profiles c
JOIN users d ON d.id = c.id
JOIN country e ON e.country_id = c.country_id
WHERE c.user_id = 42
```
Now... | Before I even start thinking about your current problem, can I just point out that your current query is a mess. Really bad. It might work, it might even work efficiently - but it's still a mess:
```
SELECT c.*, d.username, d.email, e.country_name
FROM user_profiles c, users d, country e
WHERE d.id = ".$id."
AND d.id... | 5,806 |
47,891,644 | I am doing a python project, with the SikuliX feature. I want to make an Automatic Mail sending system, but I import the TO, CC/BCC, and so on.. trough a BAT file, which sends then its data to a txt, python imports the txt and then it uses to do the job. But my problem is that when I leave a variable in Batch empty, it... | 2017/12/19 | [
"https://Stackoverflow.com/questions/47891644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8961515/"
] | Use the command line:
```
>>userdata.txt echo/%to%
```
Now environment variable `to` can be not defined and **ECHO** does nevertheless not output current state of **ECHO** mode because of forward slash `/` in command line.
The output redirection is specified on this command line for safety at beginning to make it p... | So it looks like it's working now.
The problem was that I haven't used the **.** between echo and the variables.
So it looks like this after edited:
```
@echo Off
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2,3 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
... | 5,807 |
57,408,736 | I canβt figure out how to give my R packageβs shared libraryβs debug symbols source line information. What am I missing?
1. I create the following `src/Makevars` file:
```
PKG_CXXFLAGS=-O0 -ggdb
PKG_LIBS=-O0 -ggdb
```
2. I compile the package using `R CMD INSTALL --no-multiarch --with-keep.source`:
```
* installing... | 2019/08/08 | [
"https://Stackoverflow.com/questions/57408736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247482/"
] | Changing the Makevars doesnβt prompt recompilation.
I needed to `rm -f src/*.o src/*.so` before the object files get recompiled. | This is specifically for Windows. The simplest way to do it is to set the R\_MAKEVARS\_USER environment to point to the Makevars.win file. That seems to work. However, debug break points have stopped working!!!! | 5,808 |
20,201,562 | I have a list where each element is a letter. Like this:
```
myList = ['L', 'H', 'V', 'M']
```
However, I want to reverse these letters and store them as a string. Like this:
```
myString = 'MVHL'
```
is there an easy way to do this in python? is there a .reverse I could call on my list and then just loop through... | 2013/11/25 | [
"https://Stackoverflow.com/questions/20201562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1110590/"
] | There is a [`reversed()` function](http://docs.python.org/2/library/functions.html#reversed), as well as the `[::-1]` negative-stride slice:
```
>>> myList = ['L', 'H', 'V', 'M']
>>> ''.join(reversed(myList))
'MVHL'
>>> ''.join(myList[::-1])
'MVHL'
```
Both get the job done admirably when combined with the [`str.joi... | You can use `reversed` (or `[::-1]`) and `str.join`:
```
>>> myList = ['L', 'H', 'V', 'M']
>>> "".join(reversed(myList))
'MVHL'
``` | 5,809 |
34,493,535 | I am using **pymongo** driver to work with Mongodb using Python. Every time when I run a query in python shell, it returns me some output which is very difficult to understand. I have used the `.pretty()` option with mongo shell, which gives the output in a structured way.
I want to know whether there is any method l... | 2015/12/28 | [
"https://Stackoverflow.com/questions/34493535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4138764/"
] | There is no direct method to print output of pymongo in a structured way.
as the output of pymongo is a `dict`
```
print(json.dumps('variable with out of pymongo query'))
```
this will serve your purpose i think | It probably depends on your IDE, not the pymongo itself. the pymongo is responsible for manipulating data and communicating with the mongodb. I am using Visual Studio with PTVS and I have such options provided from the Visual Studio. The PyCharm is also a good option for IDE that will allow you to watch your code varia... | 5,810 |
42,162,985 | **Use Case**
I am making a factory type script in Python that consumes XML and based on that XML, returns information from a specific factory. I have created a file that I call FactoryMap.json that stores the mapping between the location an item can be found in XML and the appropriate factory.
**Issue**
The JSON in ... | 2017/02/10 | [
"https://Stackoverflow.com/questions/42162985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7127136/"
] | You could use `eval`:
```
eval( "configDict"+path )
``` | You can use the `eval()` function to evaluate your path into an actual dict object vs a string. Something like this is what I'm referring to:
```
path="['project']['builders']['hudson.tasks.Shell']" #this is taken from the JSON
d = eval("configDict%s" % path)
for k,v in d.iteritems():
#call the appropriate factory
``... | 5,819 |
25,109,445 | I am developing a client-server software in which server is developed by python. I want to call a group of methods from a java program in python. All the java methods exists in one jar file. It means I do not need to load different jars.
For this purpose, I used jpype. For each request from client, I invoke a function... | 2014/08/03 | [
"https://Stackoverflow.com/questions/25109445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Check `isJVMStarted()` before `startJVM()`.
If JVM is running, it will return `True`, otherwise `False`.
```
def init_jvm(jvmpath=None):
if jpype.isJVMStarted():
return
jpype.startJVM(jpype.getDefaultJVMPath())
```
For a real example, see [here](https://github.com/e9t/konlpy/blob/master/konlpy/jvm... | This issue is not resolved by et9's answer above.
The problem is explained [here](https://sourceforge.net/p/jpype/discussion/379372/thread/8dab696c/).
Effectively you need to start/stop the JVM at the server/module level.
I have had success with multiple calls using this method in unit tests. | 5,820 |
41,795,116 | While `frozendict` [was rejected](https://www.python.org/dev/peps/pep-0416/#rejection-notice), a related class `types.MappingProxyType` was added to public API in python 3.3.
I understand `MappingProxyType` is just a wrapper around the underlying `dict`, but despite that isn't it functionally equivalent to `frozendict... | 2017/01/22 | [
"https://Stackoverflow.com/questions/41795116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/336527/"
] | TL;DR
-----
`MappingProxyType` is a read only proxy for mapping (e.g. dict) objects.
`frozendict` is an immutable dict
Answer
------
The proxy pattern is (quoting [wikipedia](https://en.wikipedia.org/wiki/Proxy_pattern)):
>
> A proxy, in its most general form, is a class functioning as an
> interface to somethin... | One thing I've noticed is that `frozendict.copy` supports add/replace (limited to string keys), whereas `MappingProxyType.copy` does not. For instance:
```py
d = {'a': 1, 'b': 2}
from frozendict import frozendict
fd = frozendict(d)
fd2 = fd.copy(b=3, c=5)
from types import MappingProxyType
mp = MappingProxyType(d)
... | 5,823 |
49,217,962 | I tend to write a lot of command line utility programs and was wondering if
there is a standard way of messaging the user in Python. Specifically, I would like to print error and warning messages, as well as other more conversational output in a manner that is consistent with Unix conventions. I could produce these my... | 2018/03/11 | [
"https://Stackoverflow.com/questions/49217962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8323360/"
] | I can recommend [Inform](https://inform.readthedocs.io). It is the only package I have seen that seems to address this need. It provides a variety of print functions that print in different circumstances or with different headers. For example:
```
log() -- prints to log file, no header
comment() -- prints if v... | ```
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')
```
`level` specified above controls the verbosity of the output.
You can attach handlers (this is where the complexity outweighs the benefit in my case) to the logging to send output to different places (<ht... | 5,829 |
32,604,558 | I looked but i didn't found the answer (and I'm pretty new to python).
The question is pretty simple. I have a list made of sublists:
```
ll
[[1,2,3], [4,5,6], [7,8,9]]
```
What I'm trying to do is to create a dictionary that has as key the first element of each sublist and as values the values of the coorrespondin... | 2015/09/16 | [
"https://Stackoverflow.com/questions/32604558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2509085/"
] | Using dictionary comprehension (For Python 2.7 +) and slicing -
```
d = {e[0] : e[1:] for e in ll}
```
Demo -
```
>>> ll = [[1,2,3], [4,5,6], [7,8,9]]
>>> d = {e[0] : e[1:] for e in ll}
>>> d
{1: [2, 3], 4: [5, 6], 7: [8, 9]}
``` | you could do it this way:
```
ll = [[1,2,3], [4,5,6], [7,8,9]]
dct = dict( (item[0], item[1:]) for item in ll)
# or even: dct = { item[0]: item[1:] for item in ll }
print(dct)
# {1: [2, 3], 4: [5, 6], 7: [8, 9]}
``` | 5,830 |
24,151,563 | I've got a presentation running with reveal.js and everything is working. I am writing some sample code and highlight.js is working well within my presentation. But, I want to incrementally display code. E.g., imagine that I'm explaining a function to you, and I show you the first step, and then want to show the subseq... | 2014/06/10 | [
"https://Stackoverflow.com/questions/24151563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2423506/"
] | I got this to work. I had to change the init for the highlight.js dependency:
```
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() {
[].forEach.call( document.querySelectorAll( '.highlight' ), function( v, i) {
hljs.highlightBlock(v);
});
} },
```
Then I authored the section... | I would try to use multiple `<pre class="fragment">`and change manually `.reveal pre` to `margin: 0 auto;` and `box-shadow: none;` so they will look like one block of code.
OR
Have you tried `<code class="fragment">`? If you use negative vertical margin to remove space between individual fragments and add the same ba... | 5,839 |
37,020,181 | I am trying to pull a `change` of a `gerrit` project into my local repository using `gitpython`. This can be done using the following command,
```
git pull origin refs/changes/25/225/1
```
Here, `refs/changes/25/225/1` is the change that has not been submitted in `gerrit`. I have cloned the `gerrit` project into a d... | 2016/05/04 | [
"https://Stackoverflow.com/questions/37020181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6164440/"
] | well, it's a simple as giving the branch as [`refspec` parameter to the pull method](http://gitpython.readthedocs.io/en/stable/reference.html#git.remote.Remote.pull) :
```
import git
repo = git.Repo('/home/user/gitRepo')
o = repo.remotes.origin
o.pull('refs/changes/25/225/1')
``` | ```
import git
import os, os.path
g = git.Git(os.path.expanduser("/home/user/gitRepo"))
result = g.execute(["git", "pull", "origin", "refs/changes/25/225/1"])
```
Could do the same using `execute()`. | 5,841 |
17,209,397 | This is the code, its quite simple, it just looks like a lot of code:
```
from collections import namedtuple
# make a basic Link class
Link = namedtuple('Link', ['id', 'submitter_id', 'submitted_time', 'votes',
'title', 'url'])
# list of Links to work with
links = [
Link(0, 60398, 1334... | 2013/06/20 | [
"https://Stackoverflow.com/questions/17209397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1624921/"
] | `.sort` is an in-place method that sorts an existing list and returns `None`.
`sorted` is its counter part the returns a new sorted list.
```
return_list = sorted((link for link in links if link.submitter_id == 62443),
key=lambda var: var.submitted_time)
```
On a side note I would use `operator.... | If you are bent on using `.sort`, you need a temporary reference to the unsorted list
```
return_list = [link for link in links if link.submitter_id == 62443]
return_list.sort(key=lambda var: var.submitted_time)
```
again, it's nice to use attrgetter instead of the lambda | 5,842 |
61,546,785 | I'm fairly experienced with python as a tool for datascience, no CS background (but eager to learn).
I've inherited a 3K line python script (simulates thermal effects on a part of a machine). It was built *organically* by physics people used to matlab. I've cleaned it up and modularized it (put it into a class and fun... | 2020/05/01 | [
"https://Stackoverflow.com/questions/61546785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8559356/"
] | Hope everything is alright with you!
`pytest` is good for simple cases like yours (1 file script).
It's really simple to get started. Just install it using pip:
```
pip install -U pytest
```
Then create a test file (`pytest` will run all files of the form test\_\*.py or \*\_test.py in the current directory and its... | No matter how hard you test a program, it is always fairly reasonable to assume that there will always still be bugs left unfound, in other words, it is impossible to check for everything. To start, I recommend that you thoroughly understand how the program works; thus, you will know what the expected and important val... | 5,843 |
38,228,593 | I have the followng dict in python:
```
d = {'ABC': ["DEF", "ASD"], 'DEF': ["AFS", "UAP"]}
```
Now I want to delete the value "DEF" but leave it as a Key.
so it will be:
```
d = {'ABC': [ "ASD"], 'DEF': ["AFS", "UAP"]}
``` | 2016/07/06 | [
"https://Stackoverflow.com/questions/38228593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6171823/"
] | The solution was simple. I installed Mirosoft.NETCore.UniversalWindowsPlatform package via the Package Manager Console:
`PM> Install-Package Microsoft.NETCore.UniversalWindowsPlatform` | If you have the newest version of NETCore.UniversalWindowsPlatform installed and it still isn't working, make sure that you're using the newest nuget.
We had it working in Visual Studio, but failing in command line. The reason was that we were using old version of nuget.exe, and this caused our F# fake script to use m... | 5,851 |
47,301,581 | I'm building genetic algorithm to feature selection in python. I have extracted features from my datas, then I divided into two dataframe, 'train' and 'test' dataframe.
How can I multiple the values for each row in 'population' dataframe (each individu) and 'train' dataframe?
'train' dataframe:
```
feature0 feat... | 2017/11/15 | [
"https://Stackoverflow.com/questions/47301581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4093535/"
] | If need loop (slow if large data):
```
for i, x in population.iterrows():
print (train * x.values)
feature0 feature1 feature2 feature3 feature4 feature5
0 18.279579 -3.921346 0.0 -0.0 -0.0 -18.265003
1 17.899545 -15.503942 -0.0 -0.0 -0.0 4.398419
4 16.432750 -22.490... | Once you set the columns of `population` to match `train` you can use `*`:
```
In [11]: population.columns = train.columns
In [12]: train * population.iloc[0]
Out[12]:
feature0 feature1 feature2 feature3 feature4 feature5
0 18.279579 -3.921346 0.0 -0.0 -0.0 -18.265003
1 17.899545 -15.503... | 5,852 |
45,657,365 | I just started python like a week ago and now I am stuck at the question about rolling dice. This is a question that my friend sent to me yesterday and I have just no idea how to solve it myself.
>
> Imagine you are playing a board game. You roll a 6-faced dice and move forward the same number of spaces that you roll... | 2017/08/13 | [
"https://Stackoverflow.com/questions/45657365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6891099/"
] | This is one way to compute the result that is exact, and uses neither iteration nor recursion:
```
def ways(n):
A = 3**(n+6)
M = A**6 - A**5 - A**4 - A**3 - A**2 - A - 1
return pow(A, n+6, M) % A
for i in xrange(20):
print i, '->', ways(i)
```
The output is in agreement with <https://oeis.org/A00159... | Sorry i'm not expert in python but Java can solve this, you can easily transform it to language you want :
**First idea using recursion :**
The idea is to create all possible combinaisons in a GameTree after calculate the sum requested and increment out counter.
```
public class GameTree {
public int value;
public G... | 5,854 |
64,507,361 | I am trying to write a SQL query that helps me find out the unique amount of "Numbers" that show up in a specific column. Example, in a select \* query, the column I want can look like this
```
Num_Option
9000
9001
9000,9001,9002
8080
8080,8000,8553
```
I then have another field of "date\_available" which is a date/... | 2020/10/23 | [
"https://Stackoverflow.com/questions/64507361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3973837/"
] | In Postgres, you can use `regexp_split_to_table()` in a lateral join to turn the csv elements to rows, then `string_agg()` to aggregate by date:
```
select string_agg(x.num, ',') num_option, t.date_available
from mytable t
cross join lateral regexp_split_to_table(t.num_option, ',') x(num)
group by date_available
```
... | You may just be able to use `string_agg()`:
```
select date_available, string_agg(num_option, ',')
from t
group by date_available;
``` | 5,859 |
8,560,320 | ```
>>> False in [0]
True
>>> type(False) == type(0)
False
```
The reason I stumbled upon this:
For my unit-testing I created lists of valid and invalid example values for each of my types. (with 'my types' I mean, they are not 100% equal to the python types)
So I want to iterate the list of all values and expect th... | 2011/12/19 | [
"https://Stackoverflow.com/questions/8560320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/532373/"
] | The problem is not the missing type checking, but because in Python `bool` is a subclass of `int`. Try this:
```
>>> False == 0
True
>>> isinstance(False, int)
True
``` | According to the [documentation](http://docs.python.org/reference/datamodel.html#object.__contains__), `__contains__` is done by iterating over the collection and testing elements by `==`. Hence the actual problem is caused by the fact, that `False == 0` is `True`. | 5,861 |
15,371,643 | I am receiving this error when authenticating users for vsftpd with pam\_python on Ubuntu (13.04 development branch) in the auth.log file,
```
vsftpd[1]: PAM audit_log_acct_message() failed: Operation not permitted
```
and then vsftpd says the password is wrong when attempting to connect.
Here is the full section fr... | 2013/03/12 | [
"https://Stackoverflow.com/questions/15371643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2112652/"
] | Protected fields can be inherited, but cannot be shown like `echo $q->protectedQ;`
Private fields cannot be neither displayed nor inherited. | Protected functions make your class more flexible.
Think of a class that somewhere has to load some data. It has a default implementation, which reads the data from a file. If you want to use the same class, but want to change the way it gets its data, you can create a subclass and override the getData() funciton. | 5,866 |
67,728,723 | There is a really old thread on stackoverflow here [Getting 'DatabaseOperations' object has no attribute 'geo\_db\_type' error when doing a syncdb](https://stackoverflow.com/questions/12538510/getting-databaseoperations-object-has-no-attribute-geo-db-type-error-when-do)
but the difference that I have with their issue ... | 2021/05/27 | [
"https://Stackoverflow.com/questions/67728723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6046858/"
] | >
> Process exited ... with return value 3221225620
>
>
>
3221225620 is the numeric code for a `STATUS_INTEGER_DIVIDE_BY_ZERO` (0xC0000094) exception, which means your code is crashing before it has a chance to print out its messages.
On this line:
```cpp
avg=sum/n;
```
`n` is 0 at this point, because the `whi... | you're dividing by 0, since you're modifying n until it reaches 0 and then use it to divide, it's better if you iterate with another variable instead of reducing the value of n. so the problem isn't that it's not printing, it's that the program dies before reaching that | 5,873 |
3,788,208 | I'm running this simple code:
```
import threading, time
class reqthread(threading.Thread):
def run(self):
for i in range(0, 10):
time.sleep(1)
print('.')
try:
thread = reqthread()
thread.start()
except (KeyboardInterrupt, SystemExit):
print('\n! Received keyboard ... | 2010/09/24 | [
"https://Stackoverflow.com/questions/3788208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39796/"
] | Try
```
try:
thread=reqthread()
thread.daemon=True
thread.start()
while True: time.sleep(100)
except (KeyboardInterrupt, SystemExit):
print '\n! Received keyboard interrupt, quitting threads.\n'
```
Without the call to `time.sleep`, the main process is jumping out of the `try...except` block too early, so... | To summarize the changes recommended in [the](https://stackoverflow.com/questions/3788208/python-threading-ignores-keyboardinterrupt-exception#comment16625542_3788243) [comments](https://stackoverflow.com/questions/3788208/python-threading-ignores-keyboardinterrupt-exception#comment28203538_3788243), the following work... | 5,874 |
25,888,396 | I am trying to retrieve the longitude & latitude of a physical address ,through the below script .But I am getting the error. I have already installed googlemaps .
kindly reply
Thanks In Advance
```
#!/usr/bin/env python
import urllib,urllib2
"""This Programs Fetch The Address"""
from googlemaps import GoogleMaps
a... | 2014/09/17 | [
"https://Stackoverflow.com/questions/25888396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3008712/"
] | googlemaps package you are using is not an official one and does not use google maps API v3 which is the latest one from google.
You can use google's [geocode REST api](https://developers.google.com/maps/documentation/geocoding/) to fetch coordinates from address. Here's an example.
```
import requests
response = re... | For a Python script that does not require an API key nor external libraries you can query the Nominatim service which in turn queries the Open Street Map database.
For more information on how to use it see <https://nominatim.org/release-docs/develop/api/Search/>
A simple example is below:
```
import requests
import... | 5,883 |
40,616,527 | I'm trying to build caffe with python but it keep saying this
```
CXX/LD -o python/caffe/_caffe.so python/caffe/_caffe.cpp
/usr/bin/ld: cannot find -lboost_python3
collect2: error: ld returned 1 exit status
make: *** [python/caffe/_caffe.so] Error 1
```
This is what I get when I try to locate `boost_python`
```
$ s... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40616527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4258576/"
] | I've found the problem. it turned out that it tries to look for something with that name of `libboost_python3.so` after changing the name in Makefile.config from `boost_python3` to `boost_python-py34`, it worked just fine! | I know this thread is quite old, but :
```
dnf install boost-python3-devel
```
may help ! | 5,893 |
47,966,556 | I'm getting confused groups of Regex which from a book:γAutomate the Boring Stuff with Python: Practical Programming for Total Beginners γγThe Regex as follow:
```
#! python3
# phoneAndEmail.py - Finds phone numbers and email addresses on the clipboard
# The data of paste from: https://www.nostarch.com/contactus.html
... | 2017/12/25 | [
"https://Stackoverflow.com/questions/47966556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9135962/"
] | Regexes can have *groups*. They are denoted by `()`. Groups can be used to extract a part of the match which might be useful.
In the phone number regex for example, there are 9 groups:
```
Group Subpattern
1 ((\d{3}|\(\d{3}\))?(\s|-|\.) (\d{3}) (\s|-|\.)(\d{4})(\s*(ext|x|ext.)\s*(\d{2,,5}))?)
2 (\d{3}|\(\d... | In a regex, parenthesis `()` create what is called a **capturing group**. Each group is assigned a number, starting with 1.
For example:
```
In [1]: import re
In [2]: m = re.match('([0-9]+)([a-z]+)', '123xyz')
In [3]: m.group(1)
Out[3]: '123'
In [4]: m.group(2)
Out[4]: 'xyz'
```
Here, `([0-9]+)` is the first cap... | 5,895 |
59,591,632 | I am currently trying to use the [dynamodb](https://www.npmjs.com/package/dynamodb) extension in python to get the position\rank in a descending query on an index, the following is what I have come up with:
```
router.get('/'+USER_ROUTE+'/top', (req, res) => {
POST.query()
.usingIndex('likecount')
.attribu... | 2020/01/04 | [
"https://Stackoverflow.com/questions/59591632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4134377/"
] | It is not possible in Delta Lake up to and including 0.5.0.
There's an issue to track this at <https://github.com/delta-io/delta/issues/294>. Feel free to upvote that to help get it prioritized.
---
Just a day after Google posted [Getting started with new table formats on Dataproc](https://cloud.google.com/blog/prod... | It's possible.
Here's a sample code and the libraries that you need:
Make sure to set first your credential, you can either part of the code or as environment:
```
export GOOGLE_APPLICATION_CREDENTIALS={gcs-key-path.json}
```
```
import org.apache.spark.sql.{SparkSession, DataFrame}
import com.google.cloud.spark.bi... | 5,896 |
48,464,693 | So, I created a python program. Converted to exe using Py2Exe, and tried with PyInstaller and cx\_freeze as well. All these trigger the program to be detected as virus by avast, avg, and others on virustotal and on my local machine.
I tried changing to a Hello World script to see if the problem is there but the result... | 2018/01/26 | [
"https://Stackoverflow.com/questions/48464693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9273160/"
] | You can try nuitka.
```
pip install -U nuitka
```
Example:
```
nuitka --recurse-all --icon=app.ico --portable helloworld.py
```
Website:
<http://nuitka.net/>
Maybe you need to install Visual C++ 2015 Build Tools for compile.
<http://landinghub.visualstudio.com/visual-cpp-build-tools> | If you download Nuitka package, you will find a Trojan files in the folder.
If you use this library, you will create a exe file with a Trojan embedded in the exe file.
It converts files much faster than other similar libraries with no errors. | 5,897 |
60,421,328 | I am trying to import a python dictionary from moodels and manipulate/print it's properties in Javascript. However nothing seems to print out and I don't receive any error warnings.
**Views.py**
```
from chesssite.models import Chess_board
import json
def chess(request):
board = Chess_board()
data = json.dum... | 2020/02/26 | [
"https://Stackoverflow.com/questions/60421328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12315848/"
] | You can utilize the [z algorithm](https://codeforces.com/blog/entry/3107), a linear time (***O***(n)) algorithm that:
>
> Given a string *S* of length n, the Z Algorithm produces an array *Z*
> where *Z[i]* is the length of the longest substring starting from *S[i]*
> which is also a prefix of *S*
>
>
>
You nee... | For O(n) time/space complexity, the trick is to evaluate hashes for each subsequence. Consider the array `b`:
```
[b1 b2 b3 ... bn]
```
Using [Horner's method](https://en.wikipedia.org/wiki/Horner%27s_method), you can evaluate all the possible hashes for each subsequence. Pick a base value `B` (bigger than any value... | 5,898 |
8,997,431 | A common pattern in python is to catch an error in an upstream module and re-raise that error as something more useful.
```
try:
config_file = open('config.ini', 'r')
except IOError:
raise ConfigError('Give me my config, user!')
```
This will generate a stack trace of the form
```
Traceback (most recent ca... | 2012/01/25 | [
"https://Stackoverflow.com/questions/8997431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234254/"
] | This is known as *Exception Chaining* and is suported in Python 3.
PEP 3134: <http://www.python.org/dev/peps/pep-3134/>
In Python 2, the old exception is lost when you raise a new one, unless you save it in the `except` block. | Use the `traceback` [module](http://docs.python.org/library/traceback.html). It will allow you to access the most recent traceback and store it in a string. For example,
```
import traceback
try:
config_file = open('config.ini', 'r')
except OSError:
tb = traceback.format_exc()
raise ConfigError('Give me my... | 5,900 |
51,247,566 | It looks like I can only change the value of mutable variables using a function, but is it possible to change immutable
### Code
```
def f(a, b):
a += 1
b.append('hi')
x = 1
y = ['hello']
f(x, y)
print(x, y) #x didn't change, but y did
```
### Result
```
1 [10, 1]
```
So, my question is that is it poss... | 2018/07/09 | [
"https://Stackoverflow.com/questions/51247566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9273687/"
] | In python, the list is passed by **object-reference**. Actually, everything in python is an object but when you pass a single variable to function it creates a local copy of that if a value is changed but in case of a list if it creates a local copy even than the reference remains to the previous list object. Hence the... | Y is not value its just some bindings to memory. When You pass it to function its memory address is passed to function (call by reference). On the other hand x is value and when you pass it to function new local variable is created with same value. (At the assembly level all parameters of function are passed via stack ... | 5,903 |
8,933,380 | I'm developing a web application in python for which each user request makes an API call to an external service and takes about **20 seconds** to receive response. As a result, in the event of several concurrent requests being made, the CPU load goes crazy (>95%) with several idle processes.
The server consists of a 1... | 2012/01/19 | [
"https://Stackoverflow.com/questions/8933380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1159455/"
] | You can't create an object like that - the "key" in an object literal must be a constant, not a variable or expression.
If the key is a variable you need the array-like syntax instead:
```
myArray[key] = value;
```
Hence you need:
```
var data = {}; // empty object
data[$(this).attr('id')] = $(this).val();
```
... | You can't build property names dynamically like that.
```
function ArrayPush($group) {
var arr = new Array();
$group.find('input[type=text],textarea').each(function () {
var data = {};
data [$(this).attr('id')] = $(this).val();
arr.push(data);
});
return arr;
}
``` | 5,904 |
61,388,487 | Was trying to learn itertools from the python docs. I was going through `count` function and replicated
the example given. However, I did not get any output to view.
```
def count(start=0, step=1):
n = start
while True:
yield n
n += step
```
output was :
```
>>> print(count(2.5,0.5))
<gener... | 2020/04/23 | [
"https://Stackoverflow.com/questions/61388487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13146477/"
] | if u want set the icon size small then u can do like that
```
Tab(
text: "Category List",
icon: Icon(Icons.home,size: 15,),
),
Tab(
text: "Product List",
icon: Icon(Icons.view_list,size: 15,),
),
Tab(
... | You gotta make custom TabBar for customization. Something like this.
**CustomTabbar**
```
import 'package:flutter/material.dart';
class ChangeTextSizeTabbar extends StatefulWidget {
@override
ChangeTextSizeTabbarState createState() {
return new ChangeTextSizeTabbarState();
}
}
class ChangeTextSizeTabbar... | 5,911 |
31,715,184 | I want to calculate 6 month before date in python.So is there any problem occurs at dates (example 31 august).Can we solve this problem using timedelta() function.can we pass months like *date=now - timedelta(days=days)* instead of argument days. | 2015/07/30 | [
"https://Stackoverflow.com/questions/31715184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4947801/"
] | `timedelta` does not support months, but you can try using [`dateutil.relativedelta`](http://dateutil.readthedocs.org/en/latest/relativedelta.html#dateutil.relativedelta.relativedelta) for your calculations , which do support months.
Example -
```
>>> from dateutil import relativedelta
>>> from datetime import dateti... | If you are only interested in what the month was 6 months ago then try this:
```
import datetime
month = datetime.datetime.now().month - 6
if month < 1:
month = 12 + month # At this point month is 0 or a negative number so we add
``` | 5,912 |
52,805,041 | Say im having scrapper\_1.py , scrapper\_2.py, scrapper\_3.py.
The way i run it now its from pycharm run/execute each in separate, this way i can see the 3 python.exe in execution at task manager.
Now im trying to write a master script say scrapper\_runner.py that imports this scrappers as modules and run them all in... | 2018/10/14 | [
"https://Stackoverflow.com/questions/52805041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/662409/"
] | A subprocess in python may or may not show up as a separate process, depending on your OS and your task manager. `htop` in linux, for example, will display subprocesses under the parent process in tree-view.
I recommend taking a look at this in depth tutorial on the `multiprocessing` module in python: <https://pymotw.... | Your problem is in how you setup the processes. You are not running the processes in parallel, even though you think you are. You are actually running them, when you add them to the `runners_list` and then you are running the result of each runner in parallel as multiprocesses.
What you want to do, is to add the funct... | 5,915 |
52,902,158 | I have the following list:
```
o_dict_list = [(OrderedDict([('StreetNamePreType', 'ROAD'), ('StreetName', 'Coffee')]), 'Ambiguous'),
(OrderedDict([('StreetNamePreType', 'AVENUE'), ('StreetName', 'Washington')]), 'Ambiguous'),
(OrderedDict([('StreetNamePreType', 'ROAD'), ('StreetName', 'Quartz')])... | 2018/10/20 | [
"https://Stackoverflow.com/questions/52902158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6930132/"
] | I would use list comprehension to do this as follows.
```
pd.DataFrame([o_dict_list[i][0] for i, j in enumerate(o_dict_list)])
```
>
>
> >
> > See the output below.
> >
> >
> >
>
>
>
```
StreetNamePreType StreetName
0 ROAD Coffee
1 AVENUE Washington
2 ROAD Quartz
``` | extracting the `OrderedDict` objects from your list and then use `pd.Dataframe` should work
```
values= []
for i in range(len(o_dict_list)):
values.append(o_dict_list[i][0])
pd.DataFrame(values)
StreetNamePreType StreetName
0 ROAD Coffee
1 AVENUE Washington
2 ROAD Quartz
``` | 5,916 |
5,980,863 | In my django app I call `location.reload();` in an Ajax routine in some rare circumstances. That works well with Chrome, but with Firefox4 I get an `error: [Errno 32] Broken pipe` twice on my development server (Django 1.2.5, Python 2.7), which takes about 10 sec.
And the error seems to eat the message I'm trying to... | 2011/05/12 | [
"https://Stackoverflow.com/questions/5980863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/526169/"
] | First of all, that's an issue with some specific browsers (and, probably, long processing on the server side) not a problem in django.
From the [bug report](http://code.djangoproject.com/ticket/4444#comment:14) on django:
>
> This is common error which happens whenever your browser closes the connection while the de... | The broken pipe error can also be down to lack of support for certain functionality in the Django debug server - one notable issue is Django's lack of support for [`Range` HTTP requests](https://www.rfc-editor.org/rfc/rfc7233) (see here for details: [Byte Ranges in Django](https://stackoverflow.com/questions/14324250/b... | 5,918 |
50,014,265 | I'm trying to write a python script that can echo whatever a user types when running the script
Right now, the code I have is (version\_msg and usage\_msg don't matter right now)
```
from optparse import OptionParser
version_msg = ""
usage_msg = ""
parser = OptionParser(version=version_msg, usage=usage_msg)
parser.... | 2018/04/25 | [
"https://Stackoverflow.com/questions/50014265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6642021/"
] | A slightly hacky way of doing it:
```
from optparse import OptionParser
version_msg = ""
usage_msg = ""
parser = OptionParser(version=version_msg, usage=usage_msg)
parser.add_option("-e", "--echo", action="append", dest="input_lines", default=[])
options, arguments = parser.parse_args()
print(options.input_lines + ... | I think this is best accomplished by quoting the argument ie hello world becomes 'hello world' this ensures that the -e option consumes the entire string.
If you really need the string to be broken up into pieces ie ['hello', 'world'] instead of ['hello world'] you could easily call split() on options.e[0]
```
string... | 5,919 |
14,404,744 | I'm trying to read a CSV file using `numpy.recfromcsv(...)` where some of the fields have commas in them. The fields that have commas in them are surrounded by quotes i.e., `"value1, value2"`. Numpy see's the quoted field as two different fields and it doesn't work very well. The command I'm using right now is
```
... | 2013/01/18 | [
"https://Stackoverflow.com/questions/14404744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/633318/"
] | It is possible to do this with [pandas](http://pandas.pydata.org/):
```
np_array = pandas.io.parsers.read_csv("file_with_comma_fields_quoted.csv").as_matrix()
``` | If you consider using native Python csv reader, with Python doc [here](http://docs.python.org/2/library/csv.html#csv-fmt-params):
Python csv reader defines some optional `Dialect.quotechar` options, which defaults to `'"'`. In the csv format standard, quotechar is another field delimiter, and the delimiter (comma in ... | 5,921 |
25,426,447 | I was trying to understand how non-blocking sockets work ,so I wrote this simple server in python .
```
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1',1000))
s.listen(5)
s.setblocking(0)
while True:
try:
conn, addr = s.accept()
print ('connection f... | 2014/08/21 | [
"https://Stackoverflow.com/questions/25426447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2789669/"
] | `setblocking` only affects the socket you use it on. So you have to add `conn.setblocking(0)` to see an effect: The `recv` will then return immediately if there is no data available. | You just need to call `setblocking(0)` on the *connected* socket, i.e. `conn`.
```
import socket
s = socket.socket()
s.bind(('127.0.0.1', 12345))
s.listen(5)
s.setblocking(0)
>>> conn, addr = s.accept()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/socket.py", l... | 5,923 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.