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 |
|---|---|---|---|---|---|---|
63,940,481 | I know that my view is correct, however, when I put `{% url 'sub_detail' subc.id %}`in index.html it suddenly gives an error of no reverse match. Once I remove it index works fine. I tried changing id, but it did not change anything as it still gives the same error.
Thanks in advance.
views.py:
```
from django.shortc... | 2020/09/17 | [
"https://Stackoverflow.com/questions/63940481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14294805/"
] | Rather than many `if` statements, I just reproduced the `match` statement
with a repetition `$( ... )*` for all the available branches.
It seems to behave like the extensive `match` expression.
```rust
macro_rules! run_questions {
( $chosen_question: expr, $( $question_num: expr, $question_mod: expr ), * ) => {
... | The error message explained:
```
macro_rules! run_questions {
($chosen_question: expr, $($question_num: expr, $question_mod: expr),*) => {{
```
In the above pattern you have a repetition with the `*` operator that involves variables `$question_num` and `$question_mod`
```
if $chosen_question == $questio... | 16,256 |
70,699,537 | Given two arrays:
```
import numpy as np
array1 = np.array([7, 2, 4, 1, 20], dtype = "int")
array2 = np.array([2, 4, 4, 3, 10], dtype = "int")
```
and WITHOUT the use of any loop or if-else statement; I am trying to create a third array that will take the value equal to the sum of the
(corresponding) elements from a... | 2022/01/13 | [
"https://Stackoverflow.com/questions/70699537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12256590/"
] | You can use three mask arrays, like so:
```
>>> array3 = np.zeros(array1.shape, dtype=array1.dtype)
>>> a1_gt = array1 > array2 # for when element at array 1 is greater
>>> a2_gt = array1 < array2 # for when element at array 2 is greater
>>> a1_eq_a2 = array1 == array2 # for when elements at array 1 and array 2 ... | I renamed your arrays to `a` and `b`
```
print((a>b)*(a+b)+(a==b)*(a*b)+(a<b)*(b-a))
```
direct comparison between arrays give you boolean reasults that you can interpret as `0` or `1`. That means a simple multiplication can turn an element "on" or "off". So we can just piece everything together. | 16,257 |
39,372,494 | ```
#!/usr/bin/python
# -*- coding: utf-8 -*-
def to_weird_case(string):
lines = string.split()
new_word = ''
new_line = ''
for word in lines:
for item in word:
if word.index(item) %2 ==0:
item = item.upper()
new_word += item
else:
... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39372494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6511336/"
] | First, you overwrite `new_line` with every iteration. Second, `new_word` is getting longer because you never "clear" it. Third, you add space to the end of the entire `new_line` and not after every new word (because of *Second*).
*See comments*
```
def to_weird_case(string):
lines = string.split()
new_line =... | It is correct that your code did not reset the value of `new_word` and you overwrote the `new_line` within the loop, but I'd like to share a next to one-liner solution with a regex:
```
import re
def to_weird_case(string):
return re.sub(r'(\S)(\S?)', lambda m: "{0}{1}".format(m.group(1).upper(), m.group(2)), strin... | 16,262 |
26,650,057 | I am working on a simple python script for retrieving information from a mysql database.
Here are my two examples which are almost IDENTICAL and the first successfully compiles while the second returns:
```
File "dbconnection.py", line 17
print ip
^
SyntaxError: invalid syntax
```
I have tried ... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26650057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210196/"
] | You used:
```
from __future__ import print_function
```
at the top of your module. This *disables* the `print` statement for that module so you can use the [`print()` **function**](https://docs.python.org/2/library/functions.html#print) instead:
```
print(id)
```
From the function documentation:
>
> **Note**: T... | from **future** import print\_function, division require Python 2.6 or later. **print\_function** will allow you to use print as a function. So you can't use it as **print ip**.
```
>>> from __future__ import print_function
>>>print('# of entries', len(dictionary), file=sys.stderr)
``` | 16,263 |
58,048,079 | Upon attempting to compile python 3.7 I hit `Could not import runpy module`:
```
jeremyr@b88:$ wget https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tar.xz
....
jeremyr@b88:~/Python-3.7.3$ ./configure --enable-optimizations
jeremyr@b88:~/Python-3.7.3$ make clean
jeremyr@b88:~/Python-3.7.3$ make -j32
....
g... | 2019/09/22 | [
"https://Stackoverflow.com/questions/58048079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3817456/"
] | It seems the enable-optimizations was the problem,
```
jeremyr@b88:~/Python-3.7.3$ ./configure
jeremyr@b88:~/Python-3.7.3$ make clean
```
takes care of it in my case. | In case others come across this question: I encountered the same problem on Centos 7. I also had `--enable-optimizations` but didn't want to remove that flag. Updating my build dependencies and then re-running solved the problem. To do that I ran:
```
sudo yum groupinstall "Development Tools" -y
```
In case the yum ... | 16,264 |
50,685,300 | I want to upload a flask server to bluemix. The structure of my project is something like this
* Classes
+ functions.py
* Watson
+ bot.py
* requirements.txt
* runtime.txt
* Procfile
* manifest.yml
my bot.py has this dependency:
```
from classes import functions
```
I have tried to include it in the manifest usi... | 2018/06/04 | [
"https://Stackoverflow.com/questions/50685300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4590839/"
] | You don't need to include it into the manifest file. Your entire app directory and its subdirectories are uploaded as part of the `push` command. Thereafter, it is possible to reference the file as shown.
This imports a file in the current directory:
```
import myfile
```
This should work for your `functions.py`:
... | Thanks a lot, this finally worked for me, the answered you pointed me to gave me the solution, thanks a lot again!
```
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
``` | 16,267 |
14,594,402 | I have 3 files a.py, b.py, c.py
I am trying to dynamically import a class called "C" defined in c.py from within a.py
and have the evaluated name available in b.py
python a.py is currently catching the NameError. I'm trying to avoid this and create an
instance in b.py which calls C.do\_int(10)
a.py
```
import b
#o... | 2013/01/30 | [
"https://Stackoverflow.com/questions/14594402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/566741/"
] | One way would be to use indexOf() to see if /admin is at pos 0.
```
var msg = "/admin this is a message";
var n = msg.indexOf("/admin");
```
If n = 0, then you know /admin was at the start of the message.
If the string does not exist in the message, n would equal -1. | You could use [`Array.slice(beg, end)`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice):
```javascript
var message = '/admin this is a message';
if (message.slice(0, 6) === '/admin') {
var adminMessage = message.slice(6).trim();
// Now do something with the "adminMessage".... | 16,268 |
25,395,915 | I'm after a threadsafe queue that can be pickled or serialized to disk. Are there any datastructures in python that do this. The standard python Queue could not be pickled. | 2014/08/20 | [
"https://Stackoverflow.com/questions/25395915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3716723/"
] | This can be done using the [`copy_reg`](https://docs.python.org/2/library/copy_reg.html) module, but it's not the most elegant thing in the world:
```
import copy_reg
import threading
import pickle
from Queue import Queue as _Queue
# Make Queue a new-style class, so it can be used with copy_reg
class Queue(_Queue, ob... | There are modules like `dill` and `cloudpickle` that already know how to serialize a `Queue`.
They already have done the `copy_reg` for you.
```
>>> from Queue import Queue
>>> q = Queue()
>>> q.put('hey')
>>> import dill as pickle
>>> d = pickle.dumps(q)
>>> _q = pickle.loads(d)
>>> print _q.get()
hey
>>>
```
It's... | 16,273 |
45,447,325 | I am using service workers to create an offline page for my website.
At the moment I am saving `offline.html` into cache so that the browser can show this file if there is no interent connection.
In the `fetch` event of my service worker I attempt to load `index.html`, and if this fails (no internet connection) I loa... | 2017/08/01 | [
"https://Stackoverflow.com/questions/45447325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541397/"
] | I think we have all forgotten how the network request works from a browser's point of view.
The issue here is, `index.html` is served from the disk cache when the service worker intercepts requests.
**browser** ===> **Service Worker** ===>**fetch event**
>
> inside the fetch event, we have ,
>
>
> * Check If there... | David, you have two errors in one line.
Your line
```
return catches.match(event.request.url + OFFLINE_URL);
```
should be
```
return caches.match('offline.html');
```
It's `catches` and you haven't defined `OFFLINE_URL` and you don't need event request url | 16,274 |
73,558,009 | I am attempting to run celery on it's own container from my Flask app. Right now I am just setting up a simple email app. The container CMD is
>
> "["celery", "worker", "--loglevel=info"]"
>
>
>
The message gets sent to the redis broker and celery picks it up, but celery gives me the error.
>
> "Received unregi... | 2022/08/31 | [
"https://Stackoverflow.com/questions/73558009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2236794/"
] | You need to pass the celery app to the worker with `--app` or `-A` flag (see my answer/example [here](https://stackoverflow.com/a/45908901/1011253)).
I would recommend to refactor a bit and extract this snippet:
```
celery = Celery(views.name,
broker='redis://redis:6379/0',
include=["v... | I finally figured it out. I used <https://blog.miguelgrinberg.com/post/celery-and-the-flask-application-factory-pattern>
as a reference. Now I can register new blueprints without touching the celery config. It is a work in progress, but now the containers are all up and running.
```
.
├── Docker
│ ├── celery
│ │ ... | 16,276 |
69,776,068 | I created a list of files in a directory using os.listdir(), and I'm trying to move percentages of the files(which are images) to different folders. So, I'm trying to move 70%, 15%, and 15% of the files to three different target folders.
Here is a slice of the file list:
```
print(cnv_list[0:5])
['CNV-9890872-5.jpeg'... | 2021/10/30 | [
"https://Stackoverflow.com/questions/69776068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7248794/"
] | If you can partition a list 70/30, and partition a list 50/50, then you can get 70/15/15 just by partitioning twice (once 70/30, once 50/50).
```
def partition_pct(lst, point):
idx = int(len(lst) * point)
return lst[:idx], lst[idx:]
l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
l_70, l_30 = partiti... | Don't know if there's a better way but that's what i have:
```
def split(lst, weights):
sizes = []
fractions = []
for i in weights:
sizes.append(round(i * len(lst)))
fractions.append((i * len(lst)) % 1)
if sum(sizes) < len(lst):
i = max(range(len(fractions)), key=fractions.__get... | 16,277 |
54,758,444 | We have 32 V-CPUs with 28 GB ram with `Local Executor` but still airflow is utilizing all the resources and this is resulting in over-utilization of resources which ultimately breaks the system execution.
Below is the output for ps -aux ordered by memory usage.
```
PID %CPU %MEM VSZ RSS TTY STAT START ... | 2019/02/19 | [
"https://Stackoverflow.com/questions/54758444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6823560/"
] | [The size shown in `RSS` field is in `KB`](http://man7.org/linux/man-pages/man1/ps.1.html). The first process is using about 265 MB, not something over 10 GB.
The `MEM` field shows the memory usage in *percentage*, not GB. 0.9% of 28 GB is 252 MB. You can see stats about memory with the `free` command.
See <http://ma... | A recommended method is to set the CPUQuota of Airflow to max 80%. This will ensure that Airflow process does not eat up all the CPU resources which sometimes cause the system to hang.
You can use a ready-made AMI (namely, LightningFLow) from AWS Marketplace which is pre-configured with the recommended configurations.... | 16,278 |
56,791,917 | In the shell:
```
$ date
Do 27. Jun 15:13:13 CEST 2019
```
In python:
```
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2019, 6, 27, 15, 14, 51, 314560)
>>> a = datetime.now()
>>> a.strftime("%Y%m%d")
'20190627'
```
What is the format specifier needed to get the *exactly same output* as `... | 2019/06/27 | [
"https://Stackoverflow.com/questions/56791917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10895273/"
] | Looks like you need to use the [locale](https://docs.python.org/2/library/locale.html) module
Playing in the shell:
```
$ date
Thu Jun 27 10:01:03 EDT 2019
$ LC_ALL=fr_FR.UTF-8 date
jeu. juin 27 10:01:12 EDT 2019
```
In python
```
$ LC_ALL=fr_FR.UTF-8 python
Python 2.7.5 (default, Jun 20 2019, 20:27:34)
[GCC 4.8.... | you can use [`.strftime`](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) to get your own string format.
in your case you want:
```py
from datetime import datetime
now = datetime.now()
print(now.strftime("%a %d. %b %H:%M:%S %Z %Y"))
```
**NOTE:** how the day/month name are printed will... | 16,279 |
34,636,391 | I've been searching for the last few hours and cannot find a library that allows me to add hyperlinks to a word document using python. In my ideal world I'd be able to manipulate a word doc using python to add hyperlinks to footnotes which link to internal documents. Python-docx doesn't seem to have this feature.
It b... | 2016/01/06 | [
"https://Stackoverflow.com/questions/34636391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3368835/"
] | Hyperlinks can be added using the win32com package:
```
import win32com.client
#connect to Word (start it if it isn't already running)
wordapp = win32com.client.Dispatch("Word.Application")
#add a new document
doc = wordapp.Documents.Add()
#add some text and turn it into a hyperlink
para = doc.Paragraphs.Add()
para... | ```
# How to insert hyperlinks into an existing MS Word document using win32com:
# Use the same call as in the example above to connect to Word:
wordapp = win32com.client.Dispatch("Word.Application")
# Open the input file where you want to insert the hyperlinks:
wordapp.Documents.Open("my_input_file.docx")
# Select ... | 16,282 |
27,310,426 | I am trying to create an application which can detect heartbeat using your computer webcam. I am working on the code since 2 weeks and developed this code and here I got so far
How does it works? Illustrated below ...
1. Detecting face using opencv
2. Getting image of forehead
3. Applying filter to convert it into gr... | 2014/12/05 | [
"https://Stackoverflow.com/questions/27310426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3789164/"
] | The FFT is applied in a window with 128 samples.
```
int bufferSize = 128;
```
During the draw method the samples are stored in a array until fill the buffer for the FFT to be applied. Then after that the buffer is keep full. To insert a new sample the oldest is removed. gavg is the average gray channel color.
```
... | After you get samples size 128 that is bufferSize value or greater than that, forward the fft with the samples array and then get the peak value of the spectrum which would be our heartBeatRate
Following Papers explains the same :
1. Measuring Heart Rate from Video - *Isabel Bush* - Stanford - [link](https://web.stanf... | 16,283 |
53,477,114 | When i run `sudo docker-compose build` i get
```
Building web
Step 1/8 : FROM python:3.7-alpine
ERROR: Service 'web' failed to build: error parsing HTTP 403 response body: invalid character '<' looking for beginning of value: "<html><body><h1>403 Forbidden</h1>\nSince Docker is a US company, we must comply with US exp... | 2018/11/26 | [
"https://Stackoverflow.com/questions/53477114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4626485/"
] | You must be from restricted countries which are banned by docker (from [403](https://httpstatuses.com/403) status code). only way is to use proxies in your docker service.
>
> [Service]
>
>
> ...
>
>
> Environment="HTTP\_PROXY=http://proxy.example.com:80/
> HTTPS\_PROXY=http://proxy.example.com:80/"
>
>
> ...
>... | Include proxy details for each service in docker-compose.yml file, the sample configuration looks as below mentioned. Restart the docker and then run "docker-compose build" again. You might also run "docker-compose ps" to see if all the services mentioned in the compose file running successfully.
```
services:
<serv... | 16,284 |
27,058,171 | I am fairly new to python coding, I am getting this error when i try to run my python script, can anyone tell me what i am doing wrong here?
I am trying to make a maths competition program, it should first ask for both player's names, then continue on to give each player a question until both players have answered 10 q... | 2014/11/21 | [
"https://Stackoverflow.com/questions/27058171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4277883/"
] | ```
num2 = random.randrange(35)
```
can give you zero and will lead to a division by zero in this line:
```
ans2 = num1 / num2
```
you probably want something like:
```
random.randrange(start = 1, stop = 35 + 1)
```
which will generate numbers between 1 and 35 (both inclusive).
---
A side remark: unless yo... | Andre Holzner is correct. Here is some Examples of basic usage:
`>>> random.random() # Random float x, 0.0 <= x < 1.0
0.37444887175646646`
`>>> random.uniform(1, 10) # Random float x, 1.0 <= x < 10.0
1.1800146073117523`
`>>> random.randint(1, 10) # Integer from 1 to 10, endpoints included
7`
`>>> random.randrange(0... | 16,289 |
41,241,005 | I am new to python and pandas. Trying to implement below condition but getting below error:
```
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
```
Below is my code:
```
df['col2'].fillna('.', inplace=True)
import copy
dict_YM = {}
for yearmonth in [201104, 201105,... | 2016/12/20 | [
"https://Stackoverflow.com/questions/41241005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7320512/"
] | You are printing `result` to `stdout`. The objects in this list are of type `Person`. That is the `Person.toString()` method is used to get a string representation of `result`.
As mentioned in the comments either change the `toString` method of Person to just return the value of `age` or iterate over the result and wr... | The method `public static <T> List<T> searchIn( List<T> list , Matcher<T> m )` returns `List<T>`, in your case Person if you want to get person age
try `result.stream().map(Person::getAge).forEach(System.out::println);` | 16,290 |
39,800,524 | The below function retains the values in its list every time it is run. I recently learned about this issue as a Python ['gotcha'](http://docs.python-guide.org/en/latest/writing/gotchas/) due to using a mutable default argument.
How do I fix it? Creating a global variable outside the function causes the same issue. P... | 2016/09/30 | [
"https://Stackoverflow.com/questions/39800524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827174/"
] | There is no need to pass the list inside the recursive function, just concatenate the results of the subsequent calls to the current list:
```
def build_category_list(categories, depth=0):
'''Builds category data for parent select field'''
items = []
for category in categories:
items.append((catego... | Passing the list in or by checking a null value would solve the issue. But you need to pass the list down the recursion:
```
def build_category_list(categories, depth=0, items=None):
if not items:
items = []
'''Builds category data for parent select field'''
for category in categories:
item... | 16,291 |
48,621,360 | I was browsing the python `asyncio` module documentation this night looking for some ideas for one of my course projects, but I soon find that there might be a lack of feature in python's standard `aysncio` module.
If you look through the documentation, you'll find that there's a callback based API and a coroutine bas... | 2018/02/05 | [
"https://Stackoverflow.com/questions/48621360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1548129/"
] | The reason a stream-based API is not provided is because streams offer *ordering* on top of the callbacks, and UDP communication is inherently unordered, so the two are fundamentally incompatible.
But none of that means you can't invoke coroutines from your callbacks - it's in fact quite easy! Starting from the [`Echo... | You might be interested in [this module providing high-level UDP endpoints for asyncio](https://gist.github.com/vxgmichel/e47bff34b68adb3cf6bd4845c4bed448):
```
async def main():
# Create a local UDP enpoint
local = await open_local_endpoint('localhost', 8888)
# Create a remote UDP enpoint, pointing to th... | 16,292 |
31,221,586 | I was wondering if anyone could give me a hand with this...
Basically I am trying to modernize the news system of my site but I can't seem to limit the amount of posts showing in the foreach loop that is on my blog part of the site. I need to skip the first instance as it is already promoted at the top of the page. I'v... | 2015/07/04 | [
"https://Stackoverflow.com/questions/31221586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3925360/"
] | I assume that the $articles array has keys starting with 0. How about modifying the loop like this:
```
foreach ($articles as $key => $article)
```
and checking if $key is 0 at the beginning?
```
if($key == 0)
continue;
```
If the array keys are different: Create a new variable $i, set it to 0 and increase th... | To remove the first instance you can manually unset the item ($articles[0]) after making a copy of it or printing it as a featured news.
To limit the number of post you can use the mysql LIMIT Clause;
Or you can do something like this
```
foreach($articles as $key => $article){
if($key===0)
continue;
... | 16,295 |
56,513,918 | I have created a python script with a single function in it. Is there a way to call the function from the python terminal to test some arguments?
```py
import time
import random
def string_teletyper(string):
'''Prints out each character in a string with time delay'''
for chr in string:
print(chr, end... | 2019/06/09 | [
"https://Stackoverflow.com/questions/56513918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9906064/"
] | You can use `itertools.count()` to make infinite loop and `itertools.filterfalse` to filter values you don't need:
```
from random import randint
from itertools import count, filterfalse
f = filterfalse(lambda i: i % 2 == 0, [(yield randint(1, 99)) for i in count()])
for i in f:
print(i)
```
Prints:
```
...
6... | Do this: (Python 3)
```py
stream = (lambda min_, max_: type("randint_stream", (), {'__next__': (lambda self: 1+2*__import__('random').randint(min_-1,max_//2))}))(1,99)()
```
Get randint with `next(stream)`.
Change min and max by changing the `(1,99)`.
Real 1 line! Can change min & max!
```
... | 16,297 |
11,254,763 | I am making a script to test some software that is always running and I want to test it's recovery from a BSOD. Is there a way to throw a bsod from python without calling an external script or executable like OSR's BANG! | 2012/06/29 | [
"https://Stackoverflow.com/questions/11254763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1470373/"
] | Funny thing. There is Windows kernel function that does just that.
I'm assuming that this is intended behaviour as the function has been ther
The following python code will crash any windows computer from usermode without any additional setup.
```
from ctypes import windll
from ctypes import c_int
from ctypes import... | i hope this helps (:
```
import ctypes
ntdll = ctypes.windll.ntdll
prev_value = ctypes.c_bool()
res = ctypes.c_ulong()
ntdll.RtlAdjustPrivilege(19, True, False, ctypes.byref(prev_value))
if not ntdll.NtRaiseHardError(0xDEADDEAD, 0, 0, 0, 6, ctypes.byref(res)):
print("BSOD Successfull!")
else:
print("BSOD Faile... | 16,299 |
60,577,610 | I have a Post object with comments and I am trying to send ajax requests in a while loop to check if there have been new comments created, and if there were, add them to the DOM.
How can you achieve that in django?
Here are my models:
```py
class Post(models.Model):
name = models.CharField(max_length=255)
da... | 2020/03/07 | [
"https://Stackoverflow.com/questions/60577610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11804213/"
] | The [merge function](https://www.apollographql.com/docs/react/caching/cache-field-behavior/#the-merge-function) in cache type policies is what you are looking for. It allows you to define a custom strategy for writing incoming data into the cache.
When creating the cache you can define how to write specific fields. Le... | Try this one:
```
const { loading, error, data } = useQuery(GET_COMMENTS, {
onCompleted: data => {
// Do changes here
}
});
```
You can check it here <https://www.apollographql.com/docs/react/api/react/hooks/> | 16,300 |
4,296,570 | I'm a webdeveloper and I have a django project that I need to work on.
I am running mac OSX 10.6.5 on a macbook pro. I used macports to install django and python 2.6.
I now have some sort of problem, possibly related to my PATH / PYTHONPATH that prevents me from running django.
In terminal echo $PATH gives:
```
ech... | 2010/11/28 | [
"https://Stackoverflow.com/questions/4296570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522909/"
] | First, Macports writes the file ~/.profile to set its PATH variables. If you have created a ~/.bash\_profile file then ~/.profile will be **ignored**. You will have to copy the contents over.
To see what python version Macports has selected use:
```
port select --list python
```
which will show you something like t... | Is that really the Python interpreter installed by macports? 2.6.1 smells like the Apple provided one to me (2.6.1 is quite old).
try,
```
which python
```
As an aside, I wouldn't install Django using macports.
EDIT: Macports installed 2.6.6, the problem is the apple provided python is earlier on your path.
```
... | 16,302 |
64,698,542 | The Nvidia model is showing error for strides, even if I initialize them to the default value of (1,1)
I am using 'strides' as a replacement for the 'subsample' argument in previous versions of keras can someone explain the new syntax of using them.
```
def nvidia_model():
model = Sequential()
model.add(Conv2D(24,... | 2020/11/05 | [
"https://Stackoverflow.com/questions/64698542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13301154/"
] | I never worked with `tensorflow`, but according to the documentation of [`Conv2D`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D) it's defined as
```
tf.keras.layers.Conv2D(
filters, kernel_size, strides=(1, 1), padding='valid', data_format=None,
dilation_rate=(1, 1), groups=1, activation=N... | ```
model.add(Conv2D(24,5,5, strides = (2,2), input_shape= (66,200,3), activation='relu'))
model.add(Conv2D(36,5,5, strides = (2,2), activation = 'relu'))
model.add(Conv2D(48,5,5, strides = (2,2), activation = 'relu'))
```
For these lines use parentheses like the following example
```
model.add(Conv2D(24,(5,5), stri... | 16,305 |
74,416,745 | I have been successfully using Google Build for continuous integration with Google Cloud Run for the Django Application.
However recently psycop2-binary started giving errors as below
```
Step #0 - "Buildpack": ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 202.7/202.7 kB
28.3 MB/s eta 0:00:00
Step #0 - "Buildpack": C... | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5342009/"
] | In addition to your answer @london\_utku for new feature in psycopg 2.9.5
* Add support for Python 3.11.
* Add support for rowcount in MERGE statements in binary packages
(ticket #1497).
* Wheel package compiled against OpenSSL 1.1.1r and PostgreSQL 15
libpq.
You can also review all the Release notes for [Psycopg 2.9... | Updated psycopg2-binary to 2.9.5, and the situation is resolved. | 16,306 |
34,357,513 | I love python one liners:
```
u = payload.get("actor", {}).get("username", "")
```
Problem I face is, I have no control over what 'payload' contains, other than knowing it is a dictionary. So, if 'payload' does not have "actor", or it does and actor does or doesn't have "username", this one-liner is fine.
Problem o... | 2015/12/18 | [
"https://Stackoverflow.com/questions/34357513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1222167/"
] | Why not use an Exception:
```
try:
u = payload.get("actor", {}).get("username", "")
except AttributeError:
u = ""
``` | If you really need to do it in 1 line, you'll have to implement the functionality yourself. Which is worth doing if you use this semantics many times in your program.
There are two ways to do it: function or custom dictionary-like object for `payload`.
1) Function handles the case of `actor` being not a `dict`. It ca... | 16,307 |
71,998,895 | I'm trying to setup Pipenv on Ubuntu 22.04 LTS and I used:
```
sudo apt install pipenv
```
but I get an error:
```
FileNotFoundError: [Errno 2] No such file or directory: '/home/foo/.local/share/virtualenvs/hello-JDpq8NmY/bin/python'
```
I tried to update pip with:
```
curl -sS https://bootstrap.pypa.io/get-pip.... | 2022/04/25 | [
"https://Stackoverflow.com/questions/71998895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12009223/"
] | Finally, I have caught the issue. You are editing in admin panel and I was sharing code for front end. Please try below steps for admin:
Step 1 - file classes/Address.php
```
'lastname' => ['type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 255],
```
Change this to **isAnything**... | Go to the file **classes/Address.php** file:
```
'lastname' =>array('type' => self::TYPE_STRING, 'validate' => 'isCustomerName', 'required' => true, 'size' => 32),
```
to :
```
'lastname' =>array('type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 32),
```
validate to **isAnythi... | 16,313 |
2,014,767 | I've got a python function that should loop through a tuple of coordinates and print their contents:
```
def do(coordList):
for element in coordList:
print element
y=((5,5),(4,4))
x=((5,5))
```
When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through ... | 2010/01/06 | [
"https://Stackoverflow.com/questions/2014767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/211791/"
] | Use a trailing comma for singleton tuples.
```
x = ((5, 5),)
``` | ```
x=((5,5),)
```
(*x*) is an expression (*x*,) is a singleton tuple. | 16,316 |
13,276,847 | I'm trying to add commas to floats for display to end users of my application on GAE. The numbers come from json and are part of a 10 item query with 2 times each (aka 20 numbers per page view). For eg.
```
"total_reach": 276160.0, "total_reach": 500160.0
```
I'm using the python GAE SDK 1.7.3 template system and s... | 2012/11/07 | [
"https://Stackoverflow.com/questions/13276847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807085/"
] | ```
ids = $("tr.selectON td[id]").map(function() { return this.id; }).get();
```
Documentations :
**To get elements with `id` attribute** <http://api.jquery.com/attribute-contains-prefix-selector/>
**To filter id attribute** <http://api.jquery.com/map/>
**To convert result into array** <http://api.jquery.com/get/... | You can make it simpler, cant speak to the JQuery performance though:
```
ids =[]
$('tr.selectON td[id^=""]').each( function() {
ids.push( this.id )
});
```
"this" in the function is already a dom object, so you have direct access to its id. | 16,323 |
49,561,543 | I'm interested in getting a mapping of country codes to international phone number prefixes, like so:
```
{'US': '+1', 'GB': '+44', 'DE': '+49', ...}
```
One library that probably contains this information is [`python-phonenumbers`](https://github.com/daviddrysdale/python-phonenumbers). However, after a quick perusa... | 2018/03/29 | [
"https://Stackoverflow.com/questions/49561543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/995862/"
] | You can get the mapping you want using [`pycountry`](https://pypi.python.org/pypi/pycountry) and [`phonenumbers`](https://pypi.python.org/pypi/phonenumbers), along with a simple dictionary comprehension:
```
import phonenumbers as pn
import pycountry
dct = {c.alpha_2: pn.country_code_for_region(c.alpha_2) for c in py... | I have just found a python library that must be perfect for your problem.
It's called PhoneISO3166.
This is the github link: [GitHub phoneiso3166](https://github.com/onlinecity/phone-iso3166/) | 16,324 |
47,271,662 | I would like to compute an RBF or "Gaussian" kernel for a data matrix `X` with `n` rows and `d` columns. The resulting square kernel matrix is given by:
```
K[i,j] = var * exp(-gamma * ||X[i] - X[j]||^2)
```
`var` and `gamma` are scalars.
What is the fastest way to do this in python? | 2017/11/13 | [
"https://Stackoverflow.com/questions/47271662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475712/"
] | I am going to present four different methods for computing such a kernel, followed by a comparison of their run-time.
Using pure numpy
================
Here, I use the fact that `||x-y||^2 = ||x||^2 + ||y||^2 - 2 * x^T * y`.
```py
import numpy as np
X_norm = np.sum(X ** 2, axis = -1)
K = var * np.exp(-gamma * (X_no... | In the case that you are evaluating X against a high number of gammas, it is useful to save the negative pairwise distances matrix using the tricks done by @Callidior and @Divakar.
```
from numpy import exp, matmul, power, einsum, dot
from scipy.linalg.blas import sgemm
from numexpr import evaluate
def pdist2(X):
... | 16,325 |
17,890,896 | I have 15 lines in a log file and i want to read the 4th and 10 th line for example through python and display them on output saying this string is found :
```
abc
def
aaa
aaa
aasd
dsfsfs
dssfsd
sdfsds
sfdsf
ssddfs
sdsf
f
dsf
s
d
```
please suggest through code how to achieve this in python .
just to elaborate more... | 2013/07/26 | [
"https://Stackoverflow.com/questions/17890896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2615729/"
] | Here you go (untested):
```
- (int)getRank:(NSString *passedString) {
if([passedString isEqualToString:@"randomcard"]){
return YES;
} else {
return NO;
}
}
```
I suggest you learn Objective-C first. This is a very basic question. | To begin, NSString (the iOS implementation of String) goes something like this:
```
NSString str = @"Some STR";
```
or
```
NSString = [NSString initWithFormat:@"Hello %@", "Hi there"]];
``` | 16,329 |
67,241,815 | I tried writing a simple merge and sort function in python and got stuck after getting the following error-
```
List out of range.
```
I would appreciate if you could help me fix it and figure out how to avoid it. I have added the code below-
```
def merge(lst1, lst2):
# Gets two sorted lists and returns one m... | 2021/04/24 | [
"https://Stackoverflow.com/questions/67241815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15753999/"
] | Your problem is the while condition:
```
while i < len1 or j < len2:
```
it should be `and` - if either of the conditoins are not true, you simple append the remainder of the non-empty list to your result and you are done.
Your current code still enters the while-body and checks `if lst1[i] < lst2[j]:` if one of th... | Here are the values for i, j just before that `if` condition-
```
0 0
0 1
1 1
1 2
2 2
3 2
4 2
4 3
5 3
```
When any of the lists is traversed till the end, it throws `index out of range error`.
**Solution-**
Instead of using `or` condition, use `and` condition and append the remaining list elements at the end of th... | 16,332 |
43,753,657 | I am a beginner in python and I am using an older version of anaconda which has the 3.5.2 version of python, because I would like to use tensorflow with it. I have some outdated packages that I would like to update with "conda update all". Is there a way to do this without updating python from 3.5 to 3.6, which is inco... | 2017/05/03 | [
"https://Stackoverflow.com/questions/43753657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7955849/"
] | You can either update them all manually `conda update yourpackage`
...or you could update them all `conda update --all`, and then downgrade python again with `conda install python=3.5.2`. | Another simple method: `conda update --all python=3.5.2`
Replace the python version with your currently installed version. This will update all packages, and since the target version for `python` is already installed, it will not be updated. This also works with multiple packages: `conda update all python=3.5.2 spyder... | 16,337 |
33,582,766 | I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code:
```
Process finished with exit code -1073741515 (0xC0000135)
```
I don't get any other results - not even from "print" commands at the beginning of the file.
I have... | 2015/11/07 | [
"https://Stackoverflow.com/questions/33582766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3909896/"
] | I encountered the same error when running .py in PyCharm on Windows. Inspired by <https://thenewboston.com/forum/topic.php?id=10088>, I uninstalled and reinstalled Python. When reinstalling, I checked the `ADD PYTHON TO THE PATH` Option. After recreating the virtual environment in PyCharm, the error was gone.
**Update... | I encountered this error in my code as well, in my case the problem was sharing `pickle` which produced in Unix machine one a Windows one. | 16,339 |
12,737,121 | This bit is being troublesome....
```
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//1
NSString *urlString = @"http://zaphod_beeblebrox.pythonanywhere.com/";
//2
NSURL *url = [NSURL URLWithString:urlString];
//3
NSURLRequest *... | 2012/10/04 | [
"https://Stackoverflow.com/questions/12737121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1718637/"
] | You asked this same question before, which [I answered](https://stackoverflow.com/a/12720171/1271826). I repeat the relevant portions of that answer below. If there's something that didn't make sense, just leave a comment below.
---
I'm guessing you're trying to load a html page in a `UIWebView`? You obviously need a... | ' I am trying to use a uiwebview to bring up a web app. If you know of any better way, please let me know!'
```
[theWebView loadRequest:[NSURLRequest requestWithURL:theURL]];
``` | 16,349 |
27,949,520 | how can I do this:
in python, how can I do a loop or an if statment, that to get in the loop/ the if statment, you need a function to be called.
I mean something like this:
```
if function() *is called*:
print('function() is called')
```
thanks | 2015/01/14 | [
"https://Stackoverflow.com/questions/27949520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4454553/"
] | You should use booleans to handle that:
```
def function():
function.has_been_called = True
pass
function.has_been_called = False
#Actual Code!:
if function.has_been_called:
print('function()is called')
```
The boolean will now store whether or not the fucntion has been called. | Use a decorator to wrap the function, so that any time the function is called, you get a print, without having to alter your original function
```
def is_called(func):
def wrap():
func()
print func, "is called"
return wrap
@is_called
def function():
pass
if function():
pass #do
```
would print 'fu... | 16,351 |
58,932,201 | I moved my Gem5 simulations from my system to a server. My system does not have HDF5 libraries, but the server has, and I am met with this error:
>
>
> ```
> /usr/local/lib/python2.7/config/libpython2.7.a(posixmodule.o): In function `posix_tmpnam':
> /space/src/Python-2.7/./Modules/posixmodule.c:7275: warning: the ... | 2019/11/19 | [
"https://Stackoverflow.com/questions/58932201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6346849/"
] | I don't know the root cause of this issue, some one who is working on Gem5 could possibly answer that.
But as a workaround, since I have no admin access to the server ,and even then removing a library just for the sake of one build doesn't feel right, I edited the SConstruct file in gem5/, where the environment variab... | In case you run on older system like Debian 10 or Ubuntu 16.04, the errors are due to the fact that the `hdf5` library path is not in default system library path. I solved it by manually (brutally) linking gem5 ...
The link flags added are:
`-L/usr/lib/x86_64-linux-gnu/hdf5/serial/ -lhdf5_cpp -lhdf5`
```sh
g++ -o /ge... | 16,352 |
63,056,197 | I'm writing some python code where I need to use generators inside recursive functions. Here is some code I wrote to mimic what I am trying to do. This is attempt 1.
```
def f():
def f2(i):
if i > 0:
yield i
f2(i - 1)
yield f2(10)
for x in f():
for y in x:
print(y)... | 2020/07/23 | [
"https://Stackoverflow.com/questions/63056197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5927758/"
] | You can think of `yield from` as a for loop which yields every item:
```
for i in f(10):
yield i
```
is the same as `yield from f(10)`. In other words, it *yields* the items *from* the given iteratable which in this case is another generator. | `yield from g()` will recurse inside a new generator `g` yielding from each `yield` statement at that generator
so
```
def g1():
yield from g2()
def g2()
for i in range(10):
yield i * 2
```
You can think as if `yield from` in g1 was unrolling `g2` inside of it, expanding to something like this
```... | 16,354 |
10,989,297 | I have the following PHP code, and for the life of me I can't think of a simple & elegant way to implement around the empty() function in python to check if the index is defined in a list.
```
$counter = 0;
$a = array();
for ($i=0;$i<100;$i++){
$i = ($i > 4) ? 0 : $i;
if empty($a[$i]){
$a[$i]=array();
}
$a... | 2012/06/12 | [
"https://Stackoverflow.com/questions/10989297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342553/"
] | PHP Arrays and Python lists are not equivalent. PHP Arrays are actually [associative containers](http://php.net/manual/en/language.types.array.php):
>
> An array in PHP is actually an ordered map. A map is a type that
> associates values to keys. This type is optimized for several
> different uses; it can be treate... | In the event you were trying to do it with a list, you would have to actually set that index to none, otherwise the element wouldn't be there you'd possibly be trying to check an index past the end of the list.
```
>>> i = [None]
>>> i
[None]
>>> i = [None, None]
>>> i
[None, None]
>>> i[1] is None
True
``` | 16,355 |
14,049,983 | I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element?
For an example I created a simple test webpage with this code:
```
<!DOCTYPE html... | 2012/12/27 | [
"https://Stackoverflow.com/questions/14049983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1529981/"
] | If you start an XPath expression with `//`, it begins searching from the root of document. To search relative to a particular element, you should prepend the expression with `.` instead:
```
element2 = driver.find_element_by_xpath("//div[@title='div2']")
element2.find_element_by_xpath(".//p[@class='test']").text
``` | ***Find The Child of any Elements***
```
parent = browser.find_element(by=By.XPATH,value='value of XPATH of Parents')
child=parent.find_elements(by=By.TAG_NAME,value='value of child path')
``` | 16,357 |
37,371,992 | I am trying to split the integers in a series by forward slash by using `rsplit` function of python but it does not work.
Original Data
=============
```
date
1/30/2015
1/30/2015
1/30/2015
1/30/2015
1/30/2015
1/30/2015
1/30/2015
1/30/2015
1/30/2015
1/30/2015
```
expected Data
=============
I want to split by '/'
... | 2016/05/22 | [
"https://Stackoverflow.com/questions/37371992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5157772/"
] | You can use the `str` accessor to use string methods on the series:
```
df["date"].str.rsplit("/")
```
Or to have them in different columns:
```
df["date"].str.rsplit("/", expand = True)
```
With a series, it might be better to work on datetime data:
```
import pandas as pd
pd.to_datetime(df["date"]).dt.year
Out... | IMO it would be more useful to just convert the string to a `datetime` using [`to_datetime`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html) so you can perform arithmetic operations on it and if you want the year or any other date/time component you can use the vectorised [`dt`](http://pa... | 16,367 |
72,542,852 | I'm trying to make a discord bot that can read dates from a txt file on my device.
----------------------------------------------------------------------------------
I've read the documentation and looked over similar posts, but I keep running into the same error. Just starting to learn python so please excuse any obv... | 2022/06/08 | [
"https://Stackoverflow.com/questions/72542852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19296877/"
] | So it seems like I completely mashed up python and nodejs on accident.
Not quite sure what I was thinking but that was the issue.
---
Simple answer — don't mix nodejs and Python. | First of all you should avoid to redefine "list" as this is python keyword.
Second, the command is correct and the "open" keyword is built in in native python. So it should work.
This exact line works in my python environment (even when overwriting "list").
When you look at the end of the lines of the error message yo... | 16,368 |
64,726,961 | given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given:
```
x= "a sequence of words"
x.split(" ",1)
```
I would like to get the string "a" | 2020/11/07 | [
"https://Stackoverflow.com/questions/64726961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792022/"
] | After the split a list is returned, so use indexing to get the first element:
```
x= "a sequence of words"
print(x.split(" ",1)[0])
``` | The most "pythonic" method is an opinion. However any method like split which returns a list you can simply index the list at 0 to get the first item.
`a = x.split(" ", 1)[0]` | 16,369 |
58,638,534 | I am very new to python 3(and python in general), and I have decided to try to make a cypher and decypher in my own way as a personal project. The cypher works by generating a random number and multiplying the letters number value by it. It adds all of these multiplied values into a list and then adding the random numb... | 2019/10/31 | [
"https://Stackoverflow.com/questions/58638534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12301586/"
] | When you use `list` function, it converts the string to `['[', '1', '9', '7', '6', ',', ' ', '1', '9', '9', '5', ',', ' ', '1', '9', ']']`
Use instead:
```py
dlist = eval(input('Text to be Decyphered:'))
```
`eval` function will convert it to an actual list. You can cross check it:
```py
>>>print(type(eval('[1976,... | Try json on your input:
```
import json
data = json.loads(the_string)
``` | 16,378 |
48,957,624 | I am very to new to python and trying to translate a bunch of keywords using google API. I have an excel file with 3000 keywords which are mix of english, spanish, german etc. Trying to translate everything to English.
However, every time I run my code, I get error at different values. Sometimes, my code give error a... | 2018/02/23 | [
"https://Stackoverflow.com/questions/48957624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5695920/"
] | Normally this error is due to the character limit of 15K in Googletrans API.
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Consider reducing the number of characters. | Which line of your code gives you this error? Look at error trace
Let's start with your iterators: it is declared as `i`, but then you use `j`. Then check length of your request. It shouldn't be longer than 5k symbols according to [JSONDecodeError using Google Translate API with Python3](https://stackoverflow.com/qu... | 16,381 |
62,719,063 | Using beautiful soup and python, I have undertaken some webscraping of the shown website to isolate: the rank, company name and revenue.
I would like to show, in an html table that I am rendering using flask and jinja2, the results of the top ten companies in the table, however, the code I have written is just display... | 2020/07/03 | [
"https://Stackoverflow.com/questions/62719063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5074035/"
] | ```
rank=data[0][0]
name=data[0][1]
revenue=data[0][2]
```
You're setting the rank, name and revenue from a single element (first element of data)
I suggest that you try getting changing rank, name and revenue in your html to `{{element[0]}}` and so on, to access the respective data from each element you loop on | Thank you to @mmfallacy above who suggested this answer that I am just fleshing out.
It works, but will accept the answer above as he suggested it.
Here it is for reference:
```
{% for element in data %}
<tr>
<th scope="row"></th>
<td>{{element[0]}}</td>
<td>{{element[1]}}</td>
<td>{{eleme... | 16,382 |
68,603,298 | i am following the django instructions to build a web application hello
i have done everthing after the document but this happens
Page not found (404)
Request Method: GET
Request URL: <http://127.0.0.1:8000/hello>
Using the URLconf defined in PythonWeb.urls, Django tried these URL patterns, in this order:
admin/
The c... | 2021/07/31 | [
"https://Stackoverflow.com/questions/68603298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16567727/"
] | You have made a silly mistake in `settings.py` file:
Remove `/` after `hello`.
```
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello',
]
``` | I tried your code and it worked for me. I did two edits which are:
**settings.py:**
```py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello.apps.HelloCo... | 16,383 |
39,489,089 | This is more or less a follow up question to [Two dimensional color ramp (256x256 matrix) interpolated from 4 corner colors](https://stackoverflow.com/questions/39485178/two-dimensional-color-ramp-256x256-matrix-interpolated-from-4-corner-colors?noredirect=1#comment66289716_39485178) that was profoundly answered by jad... | 2016/09/14 | [
"https://Stackoverflow.com/questions/39489089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1230358/"
] | First some questions to better clarify your problem:
* what kind of interpolation you want: linear/cubic/other ?
* What are the points constrains? for example will there be alway just single region encapsulated by these control points or there could be also points inside?
For the simple linear interpolation and arbit... | I'm here again (a bit late, sorry,I just found the question) with a fairly short solution using `griddata` from `scipy.interpolate`. That function is meant to do precisely what you want : interpolate values on a grid from just a few points. The issues being the following : with that you won't be able to use fancy weigh... | 16,384 |
21,582,358 | Trying to find how to execute ipdb (or pdb) commands such as `disable`.
Calling the `h` command on `disable` says
>
> disable bpnumber [bpnumber ...]
> Disables the breakpoints given as a space separated list of
> bp numbers.
>
>
>
So how whould I get those bp numbers? was looking through the list of commands... | 2014/02/05 | [
"https://Stackoverflow.com/questions/21582358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037251/"
] | Use the `break` command. Don't add any line numbers and it will list all instead of adding them. | >
> info breakpoints
>
>
>
or just
>
> info b
>
>
>
lists all breakpoints. | 16,385 |
5,214,814 | I have a bunch of numbers that are tab-delimited with new line characters that looks something like this:
```
104 109 105 110 126 119 97 103\n
114 129 119 130 122 106 117 128\n
```
and so on. How can I use python to write all these numbers to a file in one col... | 2011/03/07 | [
"https://Stackoverflow.com/questions/5214814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647475/"
] | ```
"\n".join("104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n".split())
``` | Replace input\_filename and output\_filename with appropriate values.
```
f = open('input_filename','r')
nums = f.read().split()
f.close()
f = open('output_filename', 'w')
f.write('\n'.join(nums))
f.close()
```
[Edit] Reworked example that doesn't load the whole file into memory. It is now very similar to Chinmay Ka... | 16,386 |
40,443,759 | I am trying to count the word fizz using python. However it is giving me an error.
```
def fizz_count(x):
count =0
for item in x :
if item== "fizz":
count=count+1
return count
item= ["fizz","cat", "fizz", "Dog", "fizz"]
example= fizz_count(item)
print example
```
i checked with indentation but sti... | 2016/11/05 | [
"https://Stackoverflow.com/questions/40443759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4186243/"
] | Your indentation seems to be incorrect, and you should not have the first `return count` (why would you return `count` as soon as you define it??).
```
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count += 1 # equivalent to count = count + 1
return count
item = ["fiz... | Well i am new to python world. What i learned is return statement should be some thing like this.
Example one :-
```
def split_train_test(data, test_ratio):
shuffled_indices = np.random.permutation(len(data))
test_set_size = int(len(data) * test_ratio)
test_indices = shuffled_indices[:test_set_size]
t... | 16,393 |
8,437,964 | I was wondering if we can print like row-wise in python.
Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise
```
print x
# currently gives
# 3
# 4
#.. and so on
```
and i am looking something like
... | 2011/12/08 | [
"https://Stackoverflow.com/questions/8437964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | In Python2:
```
data = [3, 4]
for x in data:
print x, # notice the comma at the end of the line
```
or in Python3:
```
for x in data:
print(x, end=' ')
```
prints
```
3 4
``` | Just add a `,` at the end of the item(s) you're printing.
```
print(x,)
# 3 4
```
Or in Python 2:
```
print x,
# 3 4
``` | 16,397 |
7,843,497 | I am trying to run an awk script using python, so I can process some data.
Is there any way to get an awk script to run in a python class without using the system class to invoke it as shell process? The framework where I run these python scripts does not allow the use of a subprocess call, so I am stuck either figuri... | 2011/10/20 | [
"https://Stackoverflow.com/questions/7843497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1006198/"
] | If you can't use the *subprocess* module, the best bet is to recode your AWK script in Python. To that end, the *fileinput* module is a great transition tool with and AWK-like feel. | [Python's re module](http://docs.python.org/library/re.html) can help, or, if you can't be bothered with regular expressions and just need to do some quick field seperation, you can use [the built in str `.split()`](http://docs.python.org/library/stdtypes.html#str.split) and [`.find()`](http://docs.python.org/library/... | 16,407 |
40,617,324 | So I have an assignment, and For a specific section, we are supposed to import a .py file into our program."You will need to import histogram.py into your program."
Does that simply mean to create a new python file and just copy and past whatever is in the histogram.py into the file?
This part of my assignment is to c... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40617324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7045663/"
] | With a small tweak in your Plan model, it is indeed possible to do what you want.
First of all, you'll need to change your Plan `days` field, which is probably an `IntegerField`, to [DurationField](https://docs.djangoproject.com/en/1.10/ref/models/fields/#durationfield).
Now the catch is that we have to use [Expressi... | For me you must first grab the plan object.
```
plan = Plan.objects.filter(...)
```
and then reference the days
```
Post.objects.filter(createdAt__lte=datetime.now() - timedelta(days=plan.days))
``` | 16,409 |
2,262,482 | I have made my own php MVC framework and have also written its documentation. It is about 80% complete. Now basically I am looking for a way so that other developers should be able to analyze my code and possibly join hands for its further development and improvement and also they should be able to browse through the d... | 2010/02/14 | [
"https://Stackoverflow.com/questions/2262482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139459/"
] | [**Github**](http://github.com/) comes to mind. It's free for Open Source projects, and supports a lot of "social coding" functions.
If you prefer Subversion Version Control, take a look at [**Google Code**](http://code.google.com/).
**HTML Hosting**
Github can even [**host static HTML pages**](http://github.com/blo... | [GitHub,](http://github.com) [SourceForge](http://sourceforge.com) and [Google Code](http://code.google.com) are all great places to make your project public and get others involved.
But these sites will only host your code, documentation, maybe provide you a forum, a mailing list and a bug tracker. They usually does... | 16,412 |
48,031,283 | As an extremely simple benchmark, I executed the below simple code on PHP 7.0.19-1 and Python 3.5.3 (command line) on the same Raspberry Pi 3 model B.
Python's execution time was *horrible* in comparison to PHP's (74 seconds vs 1.4 seconds). Can anyone help me understand why the execution takes so much longer on Pytho... | 2017/12/30 | [
"https://Stackoverflow.com/questions/48031283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1502289/"
] | They're both within an order of magnitude of each other, when you run them with identical cycle counts rather than having the Python counts being larger by an order of magnitude:
### PHP: <https://ideone.com/3ebkai> 2.7089s
```
<?php
function test($x)
{
$t1 = microtime(true);
$a = 0;
for($i = 0; $i < $x;... | The loop itself appears to be twice as slow in CPython 3:
<https://ideone.com/bI6jzD>
```php
<?php
function test($x)
{
$t1 = microtime(true);
$a = 0;
for($i = 0; $i < $x; ++$i)
{
//1.40s Reassign and use $a.
//$a += 1;
//1.15s Use and increment $a.
//$a++;
//0.8... | 16,415 |
19,943,977 | I am a somewhat Python/programing newbie, and I am attempting to use a python class for the first time.
In this code I am trying to create a script to backup some files. I have 6 files in total that I want to back up regularly with this script so I thought that I would try and use the python Class to save me writing ... | 2013/11/13 | [
"https://Stackoverflow.com/questions/19943977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2680443/"
] | If you just want your files backed up, may I suggest using `shutil.copy()`?
As for your program:
If you want to substitute in a string to build a filename, you can do it. But your code doesn't do it.
You have this:
```
with open('%s.txt', 'r') as f, open('{}.txt', 'w') as f2 % (self.file_name, self.back_up_file):
... | Try simplicity :)
Your line 7 is not going to parse. Split it using intermediate variables:
```
source_fname = "%s.txt" % self.file_name
target_fname = "%s.txt" % self.back_up_file
with open(source_fname) as source, open(target_fname) as target:
# do your thing
```
Also, try hard avoiding inconsistent and overly ... | 16,424 |
12,548,572 | I'm trying to make a simple derived class based on `str`, with the addition of an instance variable, `flag`. For reasons I do not understand, I get an error if I try to pass the flag to the constructor:
```
>>> class Strvalue(str):
def __init__(self, content, flag=None):
str.__init__(self, cont... | 2012/09/22 | [
"https://Stackoverflow.com/questions/12548572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699305/"
] | You need to use `__new__` instead of `__init__` when subclassing `str`, see [basic customization](http://docs.python.org/reference/datamodel.html#basic-customization).
```
>>> class Strvalue(str):
... def __new__(cls, content, flag=None):
... inst = str.__new__(cls, content)
... inst.flag = flag
..... | You need to override `__new__` instead of (or as well as) `__init__`. | 16,425 |
9,052,588 | I am new to python and new to programming. I have question how can I use variables from method1 in method too.
Example
```
class abc(self):
def method1 (self,v1):
v1 = a+b
return v1 # want to use this value in method 2
def method2(self)
v2 * v1 = v3
```
Than... | 2012/01/29 | [
"https://Stackoverflow.com/questions/9052588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1172372/"
] | let `method2` "know" it is waiting for an argument:
```
def method2(self,v1): #note v1 was added here
v2 * v1 = v3 #what does that suppse to do? [look my "third note"]
```
also note: you also need to pass `v2` to `method2()`
third note: what exactly are you trying to do in `v2 * v1 = v3` ? maybe you meant `v3 = ... | To use a value throughout a class, you need to bind that value to an attribute of its instance.
For example:
```
class Abc(object): # put object here, not self
def method1(self):
self.v1 = 3 + 7 # now v1 is an attribute
def method2(self)
return 4 * self.v1
a = Abc()
a.method1()
a.v1 ... | 16,426 |
63,894,460 | An example is something like [Desmos](https://www.desmos.com/calculator) (but as a desktop application). The function is given by the user as text, so it cannot be written at compile-time. Furthermore, the function may be reused thousands of times before it changes. However, a true example would be something where the ... | 2020/09/15 | [
"https://Stackoverflow.com/questions/63894460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10868964/"
] | The paper [“A Killer Adversary for Quicksort”](https://www.cs.dartmouth.edu/%7Edoug/mdmspe.pdf) gives an algorithm that, for any quicksort implementation that satisfies certain “reasonable” requirements and runs deterministically, produces arbitrarily long input sequences that cause the algorithm to run in quadratic ti... | the worst case of quick sort is when each time the pivot is chosen it's the max or min number/value in the array.
in this case it will run at O(n^2) for the regular version of Quick sort.
However, there's a version of Quick sort that uses the partition algorithm in order to choose better pivots. In this version of Quic... | 16,430 |
29,124,435 | So I'm having this issue where I'm trying to convert something such as
```
[0]['question']: "what is 2+2",
[0]['answers'][0]: "21",
[0]['answers'][1]: "312",
[0]['answers'][2]: "4"
```
into an actual formated json object like so
```
[
{
'question': 'what is 2+2',
'answers': ["21", "312", "4"]
}
]
```
... | 2015/03/18 | [
"https://Stackoverflow.com/questions/29124435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3254198/"
] | Something like this. You need to handle input errors.
A function to take a data structure and add stuff to it based on input
```
function add(old, input) {
var index = input[0];
var section = input[1];
if (old[index] == undefined) {
old[index] = {}
};
if (section == "question") {
old[index]['questio... | I think you should format the json as follow:
```
{
"questions": [
{
"question": "What is 2+2",
"possible_answers": [
{
"value": 1,
"correct": false
},
{
"value": 4,
... | 16,431 |
55,994,238 | I have a code to scrape hotels reviews in python (from yelp).
The code scrape the first page of reviews perfectly, but, I am struggling to scrape the next pages.
The While loop don't work, data scraped in each loop is the same (data of the first page)
```
import requests
from lxml import html
from bs4 import Beauti... | 2019/05/05 | [
"https://Stackoverflow.com/questions/55994238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5539782/"
] | The following is one of the ways you can get your job done. I've slightly modified your existing logic of traversing next pages. Give it a shot.
```
import requests
from lxml.html import fromstring
url = 'https://www.yelp.com/biz/fairmont-san-francisco-san-francisco?sort_by=rating_desc'
while True:
res = request... | You just need to be smart about looking at the URL. Most websites follow a scheme with their page progression. In this case, it seems like it changes to the following format for the next pages:
```
https://www.yelp.com/biz/fairmont-san-francisco-san-francisco?start=20&sort_by=rating_desc
```
Where the start=20 is wh... | 16,432 |
38,810,424 | I was running TensorFlow and I happen to have something yielding a NaN. I'd like to know what it is but I do not know how to do this. The main issue is that in a "normal" procedural program I would just write a print statement just before the operation is executed. The issue with TensorFlow is that I cannot do that bec... | 2016/08/07 | [
"https://Stackoverflow.com/questions/38810424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601580/"
] | There are a couple of reasons WHY you can get a NaN-result, often it is because of too high a learning rate but plenty other reasons are possible like for example corrupt data in your input-queue or a log of 0 calculation.
Anyhow, debugging with a print as you describe cannot be done by a simple print (as this would r... | I used to find it's much tougher to pinpoint where the nans and infs may occur than to fix the bug. As a complementary to @scai's answer, I'd like to add some points here:
The debug module, you can imported by:
```
from tensorflow.python import debug as tf_debug
```
is much better than any print or assert.
You ... | 16,433 |
29,298,096 | Is there any code to tap and hold on Appium? i use python , is there any command to support it ?
For double click i used click on element twice, for tap and hold i am not getting any solution | 2015/03/27 | [
"https://Stackoverflow.com/questions/29298096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4310652/"
] | Need to pass driver
```
TouchAction action = new TouchAction(driver);
action.longPress(webElement).release().perform();
``` | Here is the update for `Java Client: 5.0.4`
```
WebElement recBtn = driver.findElement(MobileBy.id("img_button"));
new TouchAction((MobileDriver) driver).press(recBtn).waitAction(Duration.ofMillis(10000)).release().perform();
``` | 16,443 |
31,321,906 | I have a string like this in Java:
`"\xd0\xb5\xd0\xbd\xd0\xb4\xd0\xbf\xd0\xbe\xd0\xb9\xd0\xbd\xd1\x82"`
How can I convert it to a human readable equivalent?
Note:
actually it is `GWT` and this string is coming from python as part of a JSON data.
The `JSONParser` transforms it to something that is totally irrelevant, ... | 2015/07/09 | [
"https://Stackoverflow.com/questions/31321906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2961166/"
] | It seems indeed that there's no endpoint voor search exists, but I think you use a simple alternative:
Use an empty "fields" array. And count the results of your query. If == 0: false. If > 0: true
```
GET /giata_index/giata_type/_search
{
"fields": [],
"query": {
"bool": {
"must": [
... | It should be possible with the [latest 2.x version](https://github.com/elastic/elasticsearch-php/blob/master/src/Elasticsearch/Endpoints/SearchExists.php).
Code sample could be something like this:
```
$clientBuilder = Elasticsearch\ClientBuilder::create();
// Additional client options, hosts, etc.
$client = $clientBu... | 16,453 |
37,293,366 | I am trying to list the instances on tag values of different tag keys
For eg> one tag key - Environment, other tag key - Role.
My code is given below :
```
import argparse
import boto3
AWS_ACCESS_KEY_ID = '<Access Key>'
AWS_SECRET_ACCESS_KEY = '<Secret Key>'
def get_ec2_instances(Env,Role):
ec2 = boto3.client("... | 2016/05/18 | [
"https://Stackoverflow.com/questions/37293366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6349605/"
] | This looks familiar, did I modify this for somebody somewhere ;-) . Actually the code I wrote is in rush and not tested properly (And I don't bother to amend the % string formating and replace it with str.format() ) . In fact,using Filters parameter is not properly documented in AWS.
Please refer to Russell Ballestri... | Fix the Env and Role, as I am not sure mine or mootmoot's answer will work because the Array for Values [expects](http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_instances) strings.
```
reservervations = ec2.describe_instances(
Filters=[
{'Name': 'tag:environmen... | 16,454 |
51,710,083 | * I am writing unit tests for a Python library using **pytest**
* I need to **specify a directory** for test files to avoid automatic test file discovery, because there is a large sub-directory structure, including many files in the library containing "\_test" or "test\_" in the name but are not intended for pytest
* S... | 2018/08/06 | [
"https://Stackoverflow.com/questions/51710083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8477566/"
] | `parse_args()` without argument reads the `sys.argv[1:]` list. That will include the 'tests' string.
`pytests` also uses that `sys.argv[1:]` with its own parser.
One way to make your parser testable is provide an optional `argv`:
```
def parse_args(argv=None):
parser = argparse.ArgumentParser(description="descri... | To add to hpaulj's answer, you can also use a library like [unittest.mock](https://docs.python.org/3/library/unittest.mock.html) to temporarily mask the value of `sys.argv`. That way your parse args command will run using the "mocked" argv but the *actual* `sys.argv` remains unchanged.
When your tests call `parse_args... | 16,459 |
59,704,959 | I'm trying to count the number of dots in an email address using Python + Pandas.
The first record is "addison.shepherd@gmail.com". It should count 2 dots. Instead, it returns 26, the length of the string.
```
import pandas as pd
url = "http://profalibania.com.br/python/EmailsDoctors.xlsx"
docs = pd.read_excel(url)
... | 2020/01/12 | [
"https://Stackoverflow.com/questions/59704959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5518389/"
] | [`pandas.Series.str.count`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.count.html) takes a regex expression as input. To match a literal period (`.`), you must escape it:
```
docs["Email"].str.count('\.')
```
Just specifying `.` will use the regex meaning of the period (matching any... | The [**`.str.count(..)`** method [pandas-doc]](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.count.html) works with a [*regular expression* [wiki]](https://en.wikipedia.org/wiki/Regular_expression). This is specified in the documentation:
>
> This function is used to count the number of... | 16,462 |
57,718,512 | I'm trying to try using this model to train on rock, paper, scissor pictures. However, it was trained on 1800 pictures and only has an accuracy of 30-40%. I was then trying to use TensorBoard to see whats going on, but the error in the title appears.
```
from keras.models import Sequential
from keras.layers import De... | 2019/08/29 | [
"https://Stackoverflow.com/questions/57718512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7858253/"
] | The problem is here:
```
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from tensorflow.python.keras.callbacks import TensorBoard
```
Do not mix `keras` and `tf.keras` imports, these are **not compatible with each other**, and produc... | I changed `from tensorflow.python.keras.callbacks import TensorBoard`
to `from keras.callbacks import TensorBoard` and it worked for me. | 16,464 |
51,664,292 | I'm getting the error below when I'm parsing the xml from the URL in the code. I won't post the XML because it's huge. The link is in the code below.
ERROR:
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipyt... | 2018/08/03 | [
"https://Stackoverflow.com/questions/51664292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1706665/"
] | Instead of checking if `child.find('EmentaMateria').text` is not `None`, you should make sure that `child.find('EmentaMateria')` is not `None` first.
Also, you should store the returning value of `child.find('EmentaMateria')` to avoid calling it twice.
Lastly, you should assign `ementa` a default value if `child.find... | If you are using the code to parse an xml file, open the xml file with a text editor and inspect the tags. In my case there were some rogue tags at the end. Once i removed those, the code worked as expected. | 16,469 |
12,164,692 | So I am new in this field and am not sure how to do this!!But basically here is what i did.
I sshed to somehost.
```
ssh hostname
username: foo
password: bar
```
In one of the directories, there is a huge csv file.. abc.csv
Now, i dont want to copy that file to my local.. but read it from there.
When I asked the ... | 2012/08/28 | [
"https://Stackoverflow.com/questions/12164692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | So, here are your options:
**1.** Declare your **base class** as `abstract` and some methods as well
This approach has two good points: you will be free to implement common methods at the base class (that is, not all of them need to be `abstract`) while any abstract method will **must be** overridden at derived class... | You need to specify an abstract method in Parent:
```
public abstract class Parent
{
public void DoSomething()
{
// Do something here...
}
public abstract void ForceChildToDoSomething();
}
```
This forces the child to implement it:
```
public class Child : Parent
{
public override void ... | 16,470 |
28,454,359 | I need to process a large text file containing information on scientific publications, exported from the ScienceDirect search page. I want to store the data in an array of arrays, so that each paper is an array, and all papers are stored in a larger array.
The good part is that each line corresponds to the value I wan... | 2015/02/11 | [
"https://Stackoverflow.com/questions/28454359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4554385/"
] | Since you want to skip blank lines, the easiest thing to do is to check if a line is blank.
```
x = []
with open('my_file.txt', 'r') as f:
temp_list = []
for line in f:
if line.strip(): #line is not blank
temp_list.append(line)
else: #line is blank, i.e., it contains only newlines ... | If first lines are mandatory, you can try to parse them and for each article create structure like this `{'author': 'Name', 'digital_object_identifier': 'Value'}` and so on.
Than you can try to parse most common keywords and append them as fields. So your article woild be like this:
`{'author': 'Name', 'digital_object... | 16,475 |
44,851,342 | How to convert a python dictionary `d = {1:10, 2:20, 3:30, 4:30}` to `{10: [1], 20: [2], 30: [3, 4]}`?
I need to reverse a dictionary the values should become the keys of another dictionary and the values should be key in a list i.e. also in the sorted matter. | 2017/06/30 | [
"https://Stackoverflow.com/questions/44851342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8238359/"
] | ```
d = {1:10, 2:20, 3:30, 4:30}
inv = {}
for key, val in d.iteritems():
inv[val] = inv.get(val, []) + [key]
```
Try this! | ```
o = {}
for k,v in d.iteritems():
if v in o:
o[v].append(k)
else:
o[v] = [k]
```
`o = {10: [1], 20: [2], 30: [3, 4]}` | 16,476 |
29,385,340 | I'm trying to find all the divisors ("i" in my case) of a given number ("a" in my case) with no remainder (a % i == 0). I'm running a loop that goes trough all the vales of i starting from 1 up to the value of a. The problem is that only first 2 products of a % i == 0 are taken into account. The rest is left out. Why i... | 2015/04/01 | [
"https://Stackoverflow.com/questions/29385340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4262683/"
] | The behavior of the script is correct. See for yourself:

I think it's your logic, and what you are trying to achieve is:
```
a = 999
i = 1
d = []
while (i < a):
if(a % i == 0):
d.append(i)
i += 1
print (d)
```
Outputs:
```
[1, ... | To complement Anton's answer, a more Pythonic way to loop would be:
```
a, d = 999, []
for i in range(1, a):
if a%i == 0:
d.append(i)
```
You can also take advantage of the fact that object have a [Boolean value](https://docs.python.org/3.4/reference/datamodel.html#object.__bool__):
```
if not a%i:
```... | 16,481 |
41,690,010 | [](https://i.stack.imgur.com/FnX1O.png)In python selenium, how to create xpath for below code which needs only id and class:
```
<button type="button" id="ext-gen756" class=" x-btn-text">Save</button>
```
And I also need to select Global ID from bel... | 2017/01/17 | [
"https://Stackoverflow.com/questions/41690010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5907308/"
] | If you want to club `id` and `class` together in your `xpath` try like this-
```
driver.find_element_by_xpath('//button[@id="ext-gen756"][@class=" x-btn-text"]');
```
You can also try the same using `AND` -
```
driver.find_element_by_xpath('//button[@id="ext-gen756" and @class=" x-btn-text"]');
```
**EDITED**
Yo... | Just answering my own question after a long time had a look on this. The Question was posted when I was new in xpath topics.
```
<button type="button" id="ext-gen756" class=" x-btn-text">Save</button>
```
in terms of id and class:
```
driver.find_element_by_xpath("//button[@id='ext-gen756'][@class=' x-btn-text']")
... | 16,482 |
5,048,217 | i have some data stored in a .txt file in this format:
```
----------|||||||||||||||||||||||||-----------|||||||||||
1029450386abcdefghijklmnopqrstuvwxy0293847719184756301943
1020414646canBeFollowedBySpaces 3292532113435532419963
```
don't ask...
i have many lines of this, and i need a way to add more digits to ... | 2011/02/19 | [
"https://Stackoverflow.com/questions/5048217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/623985/"
] | As a general principle, there's no shortcut to "inserting" new data in the middle of a text file. You will need to make a copy of the entire original file in a new file, modifying your desired line(s) of text on the way.
For example:
```
with open("input.txt") as infile:
with open("output.txt", "w") as outfile:
... | Copy the file, line by line, to another file. When you get to the line that needs extra chars then add them before writing. | 16,483 |
2,541,954 | I basically want to be able to:
* Write a few functions in python (with the minimum amount of extra meta data)
* Turn these functions into a web service (with the minimum of effort / boiler plate)
* Automatically generate some javascript functions / objects for rpc (this should prevent me from doing as many stupid thi... | 2010/03/29 | [
"https://Stackoverflow.com/questions/2541954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47741/"
] | Yes there is, there is [Pyjamas](http://pyjs.org/). Some people bill this as the "[GWT](http://code.google.com/webtoolkit/) for Python" | It looks like using a javascript XML RPC client (there is jquery plugin for this) together with an XML RPC server is a good way to go.
The jquery plugin will introspect your rpc service and will populate method names make it impossible to mis type the name of a method call without getting early warning. It will not ho... | 16,488 |
36,510,431 | I am very new to python and programming in general and I want to print out the string "forward" whenever i press "w" on the keyboard. It is a test which I will transform into a remote control for a motorized vehicle.
```
while True:
if raw_input("") == "w":
print "forward"
```
Why does it just print out ... | 2016/04/08 | [
"https://Stackoverflow.com/questions/36510431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4909346/"
] | In Python 2.x the raw\_input function will display all characters pressed, and return upon receiving a newline. If you want different behaviour you'll have to use a different function. Here's a portable version of getch for Python, it will return every key press:
```
# Copied from: stackoverflow.com/questions/510357/p... | `raw_input` reads an entire line of input. The line you're inputting is made visible to you, and you can do things like type some text:
```
aiplanes
```
go left a few characters to fix your typo:
```
airplanes
```
go back to the end and delete a character because you didn't mean to make it plural:
```
airplane
... | 16,489 |
74,134,047 | I need some help recursively searching a python dict that contains nested lists.
I have a structure like the below example. The value of key "c" is a list of one or more dicts. The structure can be nested multiple times (as you can see in the second item), but the pattern is the same. In all likelihood, the nested dep... | 2022/10/20 | [
"https://Stackoverflow.com/questions/74134047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20287604/"
] | (Just posting this here from Matt Wards comment as I cannot mark the comment as the answer.)
As the comment suggests, Visual Studio for Mac seems to only use launchSettings.json for Asp.Net projects. I was working with a Console App.
Visual Studio for PC uses launchSettings.json for console applications too but not t... | Well, you can try to change the properties of the file and how VS Studio treats it during build.
1. Right-click on `launchSettings.json` and choose `Properties`
2. Set the below properties as follows:
```
Build action -> Content
Copy to directory -> Copy if newer
```
See if this helps. | 16,490 |
44,756,447 | I've got a lot of commands running in impala shell, in the middle of them I now have a need to run a python script. The script itself is fine when run from outside the impala shell.
When I run from within the impala shell using ! or "shell" (documentation found [here](https://www.cloudera.com/documentation/enterprise/... | 2017/06/26 | [
"https://Stackoverflow.com/questions/44756447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5065581/"
] | This is caused by a known bug [IMPALA-4664](https://issues.apache.org/jira/browse/IMPALA-4664).
A workaround is to leave a space after "!". Can you try this (note the space):
! /home/DOMAIN\_USERS/somemorefolders/python/script.py | Thanks to [@BoboDarph](https://stackoverflow.com/users/8085234/bobodarph "bobodarph") for help in getting there.
I was able to use `!~/somemorefolders/python/script.py` as I could get there from my home directory.
I still think it's a bit shortsighted of impala to force things into lower case but there you go. | 16,492 |
43,021,399 | Just creating a python program that creates a function named letterX, that ... well makes an X. The two lines must be 90 degrees from each other. The pointer ends at the initial position.
I solved this pretty easily, just wondering if you can put this into a loop or just simplify it. I don't know how since i have to c... | 2017/03/25 | [
"https://Stackoverflow.com/questions/43021399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7767472/"
] | Like francescalus commented, it looks like problem is related to integer arithmetic in Fortran.
You may modify the first `if` statement in Matlab implementation as follows:
```
if fix(k/2) ~= j/2
```
---
In your second part, there is a typo error in the Matlab code.
You wrote `x2` instead of `x1`.
Correct co... | I made a small fortran program based on your posts. Then put it through my f2matlab fortran source to matlab source converter (matlab file exchange). Here is the fortran:
```
program kt_f
implicit none
integer j,n,k,f1,f2
real x1,x2,h,sum1,sum2
n=100
k=50
do j=1,n-1
k=j
if(k/2/=j/2.) then
if(j==1) x1=x1+h
if(j... | 16,493 |
6,738,987 | is it possible to add extension method to python built-in types?
I know that I can add extension method to defined type by simply adding new method by . as following:
```
class myClass:
pass
myClass.myExtensionMethod = lambda self,x:x * 2
z = myClass()
print z.myExtensionMethod(10)
```
But is any way to adding ... | 2011/07/18 | [
"https://Stackoverflow.com/questions/6738987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614953/"
] | No. Types defined in C cannot be monkeypatched. | No, because I'm pretty sure all the built-in types are written in optimized C and thus can't be modified with Python. When I try it, I just get:
```
TypeError: can't set attributes of built-in/extension type 'list'
``` | 16,494 |
18,038,492 | I have a PHP script that needs to take one command-line argument. I need to call this script from inside my python script.
```
Popen('php simplepush.php "Here's the argument"', shell=True, cwd="/home/ubuntu/web/firestopapp.com/app")
```
^That works. However, I want to pass a variable in the Python script inste... | 2013/08/04 | [
"https://Stackoverflow.com/questions/18038492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2476581/"
] | You will not be able to get the JSON in controller. In ASP.NET Web API pipeline, binding happens before the action method executes. Media formatter would have read the request body JSON (which is a read-once stream) and emptied the contents by the time the execution comes to your action method. But if you read the JSON... | You can't get the parsed JSON, but you can get the content and parse it yourself. Try this:
```
public async Task PostCustomer(Customer customer)
{
var json = Newtonsoft.Json.JsonConvert.DeserializeObject(await this.Request.Content.ReadAsStringAsync());
///You can deserialize to any object you need or simply ... | 16,502 |
40,445,390 | I have a list composed by tuples.
Each tuple is in the following tuple format: (String, Integer).
I want to merge the tuples that have the same head (String) as follows:
```
[("Foo", 2), ("Bar", 4), ("Foo", 2), ("Bar", 4), ("Foo", 2)]
```
should become:
```
[("Foo", 6), ("Bar",8)].
```
What is a good python alg... | 2016/11/06 | [
"https://Stackoverflow.com/questions/40445390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4383494/"
] | How about collecting the sums in a [`defaultdict`](https://docs.python.org/3.6/library/collections.html#collections.defaultdict)?
```
from collections import defaultdict
d = defaultdict(int)
for (key, value) in items:
d[key] += value
```
And then turn them back to a list of tuples:
```
list(d.items())
```
The... | ```
d = {}
map(lambda (x,y):d.setdefault(x,[]).append(y),a)
print [(k,sum(v)) for k,v in d.items()]
``` | 16,504 |
17,581,418 | I'm trying to build OpenCV with MSYS / MinGW so I can use the cv2 module in python.
I'm on Windows 7 64-bit and using 32 bit Python 2.7. Building OpenCV works, but I cannot seem to use it without getting an "ImportError: DLL load failed: The specified module could not be found." after importing cv2. I've been debuggin... | 2013/07/10 | [
"https://Stackoverflow.com/questions/17581418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/887074/"
] | I feel really stupid. The dlls were in "C:\Program Files (x86)\bin" not "C:\Program Files (x86)\lib" It seems to work now. | Just to make sure other users can be helped with this answer:
Imagine you have compiled OpenCV and have several \*.dll and the cv2.pyd file.
You need to copy those files to 'DLLs' folder within the python directory.
Then import the module to check wether it is ok.
I have also copied the \*.lib files into the appropr... | 16,506 |
28,677,012 | the code:
```
import os
from time import *
import socket
import time
global diskspace
#####################
#display temp
#uses shell script to find out temp then uses python to display it
#python uses os module to run line of shell script
os.system("cat /sys/class/thermal/thermal_zone0/temp > sysTemp")
temp = op... | 2015/02/23 | [
"https://Stackoverflow.com/questions/28677012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3910964/"
] | You have few options:
1. Initialize arrays in constructor MesssageParsingTest using syntax : `firstMessage{0x24,0x54,0x3b,0x72,0x8b,0x03,0x24,0x29,0x23,0x43,0x66,0x22,0x53,0x41,0x11,0x62,0x10}`
in initializer list.
2. Create static const array containing your message, and either copy it to member variable using memcpy... | You can use a temporary buffer and then copy into you member as this:
```
void MessageParsingTest::setUp() {
unsigned char tmp[1500] = {0x24,0x54,0x3b,0x72,0x8b,0x03,0x24,0x29,0x23,0x43,0x66,0x22,0x53,0x41,0x11,0x62,0x10};
memcpy(firstMessage, tmp, 1500);
}
``` | 16,509 |
26,746,127 | I'm in an interactive Python 2.7 Terminal (Terminal default output is "utf-8"). I have a string from the internet, lets call it `a`
```
>>> a
u'M\xfcssen'
>>> a[1]
u'\xfc'
```
I wonder why its value is not `ü` so I try
```
>>> print(a)
Müssen
>>> print(a[1])
ü
```
which works as intended.
So my first question is... | 2014/11/04 | [
"https://Stackoverflow.com/questions/26746127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/620053/"
] | Can you try this
```
updateToServer: function(e) {
e.preventDefault();
var id = e.target.getAttribute('data-id');
var file = this.collection.get(id);
var data = {};
$(e.target).serializeArray().map(function(x) {data[x.name] = x.value;});
this.$el.modal('hide');
setTimeout(function(... | This was not at all what I suspected, and I hadn't given enough information in the question without realizing it. The line in my code that triggered the exception was `file.save()`, but the actual exception was happening inside Backgrid.
I provide a form to allow users to update models from the collection displayed in... | 16,512 |
26,504,852 | On `python/flask/gunicorn/heroku` stack, I need to set an environment variable based on the content of another env variable.
For background, I run a python/Flask app on heroku.
I communicate with an addon via a environment variable that contains credentials and url.
The library I use to communicate with the addon need... | 2014/10/22 | [
"https://Stackoverflow.com/questions/26504852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1827442/"
] | you could also set the enviroment variables at run time as such
```
gunicorn -b 0.0.0.0:5000 -e env_var1=enviroment1 -e env_var2=environment2
``` | OK, so the answer (via Kenneth R, Heroku) is to set the environment before running gunicorn. I.e. write a Procfile like
```
web: sh appstarter.sh
```
which calls a wrapper (shell, python, ..) that sets up the environment variable and then runs the gunicorn command, like for example
appstarter.sh:
```
export LIB_EN... | 16,513 |
14,592,879 | I cannot run any script by pressing F5 or selecting run from the menus in IDLE. It stopped working suddenly. No errors are coughed up. IDLE simply does nothing at all.
Tried reinstalling python to no effect.
Cannot run even the simplest script.
Thank you for any help or suggestions you have.
Running Python 2.6.5 on... | 2013/01/29 | [
"https://Stackoverflow.com/questions/14592879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2022926/"
] | I am using a Dell laptop, and ran into this issue. I found that if I pressed Function + F5, the program would run.
On my laptop keyboard, functions key items are in blue (main functions in white). The Esc (escape) key has a blue lock with 'Fn' on it. I pressed Esc + F5, and it unlocked my function keys. I can now run ... | Your function keys are locked,I think so.
Function keys can be unlocked by fn key + esc.
Then f5 will work without any issue. | 16,516 |
6,080,930 | I have a problem setting up a Virtualenv on my web host server (to install python modules later on)
So far I tried this using SSH-access:
```
wget http://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.5.2.tar.gz
tar xzf virtualenv-1.5.2.tar.gz
~/usr/lib/python2.4 virtualenv-1.5.2/virtualenv.py ~/data/env
... | 2011/05/21 | [
"https://Stackoverflow.com/questions/6080930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/763840/"
] | Same in Ruby.
```
require 'lib/yourlibrary.rb'
```
Or:
```
$LOAD_PATH << File.expand_path(File.dirname(FILE) + “/../lib”))
require 'yourlibrary.rb'
``` | To include a gem in your project, you could download the module and place it in the same folder as your code and then do a 'require'. You can also download the module with Rubygems copy, or you can download the module from it's project page. | 16,517 |
11,871,221 | I have this piece of code which creates a new note..WHen I try to print I get the following error even though it prints the output
```
Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Memo=This is my first memo, Tag=example
Traceback (most recent call last):
File "notebook.py", line 14, in <module>
... | 2012/08/08 | [
"https://Stackoverflow.com/questions/11871221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1050619/"
] | In the Model's `__str__` method, you are returning a value which is `null`.
For example:
```py
class X(models.Model):
name = models.CharField(_('Name'), null=True, blank=True,
max_length=150)
date_of_birth = models.DateField(_('Date of birth'), null=True, blank=True)
street = models.CharField(_('Stre... | You probably have some null value in your table. Enter to mysql and delete null value in table. | 16,518 |
48,375,937 | I am new to python and web-scraping. I am trying to scrape a website (link is the url). I am getting an error as "'NoneType' object is not iterable", with the last line of below code. Could anyone point what could have gone wrong?
```
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
url ... | 2018/01/22 | [
"https://Stackoverflow.com/questions/48375937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9238871/"
] | a bit late, but for any one else stumbling upon this.
```
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.someMethod = functions.https.onRequest((req, res) => {
var stuff = [];
var db = admin.firestore();
d... | Thanks to [Ruan's answer](https://stackoverflow.com/a/49516133/2162226), here's an example for `onCall(..)` variation:
```
exports.fireGetColors = functions.https.onCall((data, context) => {
return new Promise((resolve, reject) => {
var colors = {};
var db = admin.firestore();
db.collect... | 16,528 |
68,584,934 | I want to append to a csv file, some data from redshift tables, using the `pandas` module in python. From python, I can successfully connect and retrieve rows from redshift tables using the `psycopg2` module. Now, I am storing datewise data on the csv. So I need to first create a new date column in the csv, then append... | 2021/07/30 | [
"https://Stackoverflow.com/questions/68584934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15948815/"
] | I solved the problem with the following:
./tsconfig.json
```
{
"compilerOptions": {
"isolatedModules": true,
...
},
"exclude": ["cypress/**/*"]
}
```
./cypress/tsconfig.json
```
{
"extends": "../tsconfig.json",
"compilerOptions": {
"isolatedModules": false
},
"include": [
"../node_mod... | It seems to be a known issue of type conflicts between cypress and jest. Most accounts have detected that the problem started occurring from cypress v10.x onward.
The *following links* corroborate the OP's own answer, suggesting the exclusion of `cypress.config.ts` from `tsconfig.json`. It may or may not be a workarou... | 16,531 |
67,662,674 | My Input JSON data:
```
{
"data": [
{
"config": "current",
"id": "0"
},
{
"config": "current",
"id": "1"
},
{
"config": "current",
"id": "2"
},
{
"config": "current",
... | 2021/05/23 | [
"https://Stackoverflow.com/questions/67662674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11882985/"
] | Assuming you already know [how to parse JSON](https://stackoverflow.com/q/7771011/4518341), you can do this:
```
d = {
"data": [
{"config": "current", "id": "0"},
{"config": "current", "id": "1"},
{"config": "current", "id": "2"},
{"config": "current", "id": "3"},
{"config":... | ```
jsn = {
"data": [
{"config": "current", "id": "0"},
{"config": "current", "id": "1"},
{"config": "current", "id": "2"},
{"config": "current", "id": "3"},
{"config": "previous", "id": "4",},
{"config": "previous", "id": "5"},
{"config": "current", "id": "6"... | 16,533 |
51,937,449 | For my Coursework which I am desperately struggling with I have tried to set my inputs into a dictionary and then use this to format and print the string so that it is displayed as shown below.
>
>
> ```
> Surname, Forename Payroll Department Salary
>
> ```
>
> The name should be displayed using the format... | 2018/08/20 | [
"https://Stackoverflow.com/questions/51937449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10251613/"
] | While it would be simple to make a print function to print the way you want:
```
a = ('Surname', 'Forename', 'Payroll', 'Department', 'Salary')
def printer(tup):
print_string = str("(")
pad = 24
print_string += ", ".join(tup[:2]).ljust(pad)
print_string += ", ".join(tup[2:4]).ljust(pad)... | Why do you need this? Printing a tuple with spacing is impossible to my knowledge, but I'm sure theres another way to achieve what you're looking for. Aside from that, there is a kind of work around, although you aren't printing a tuple, to say.
```
indexs = {
payroll = 0,
dept = 1,
salary = 2,
name = ... | 16,534 |
67,967,272 | I am trying to program a calculator using python. It does not let me run the code because this error tells that:
ValueError: could not convert string to float: ''
This code was working but suddenly this error showed up.
Could anyone help me with telling what I should change or add.
This is the part of the code where th... | 2021/06/14 | [
"https://Stackoverflow.com/questions/67967272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15274509/"
] | As per Lombok documentation (<https://projectlombok.org/api/lombok/AllArgsConstructor.html>):
>
> An all-args constructor requires one argument for every field in the class.
>
>
>
Obviously you haven't provided id as a constructor argument. | If you still need some constructor having not all attributes you can use `lombok.NonNull` & `@RequiredArgsConstrutor`. Simplified example:
```
@AllArgsConstructor
@NoArgsConstructor
@RequiredArgsConstructor
public class Booking {
private Long id;
@lombok.NonNull
private Date startDate;
}
```
will provid... | 16,535 |
63,245,187 | I am just starting to get the concept of what [Prometheus](https://prometheus.io/docs/prometheus/latest/getting_started/) is, and I have done a couple of examples already.
I can understand how Prometheus monitors some data, even the one generated by itself and also some data related to a python application for example.... | 2020/08/04 | [
"https://Stackoverflow.com/questions/63245187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4451521/"
] | Short answer: No. If you actually have text files with data you want to analyze I'd suggest you to write the data to another TMDB (InfluxDB for example) or a plain old SQL database and then connect it with Grafana. Also take a look at PowerBI. I prefer it for data that is scoped more towards business analytics than mon... | While it is impossible to import historical data to Prometheus, such data can be imported to Prometheus-like systems such as VictoriaMetrics. See [these docs](https://victoriametrics.github.io/#how-to-import-time-series-data) for details. | 16,536 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.