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 |
|---|---|---|---|---|---|---|
70,241,576 | This is a very weried situation, in vscode, I edited my code in the root directory and saved it as test\_distribution.py. After I run this file in vscode terminal. Everytime I edit and save this file, it gets run automatically.
So I moved this file to the subfolder of this project, but I found out it still get run whe... | 2021/12/06 | [
"https://Stackoverflow.com/questions/70241576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14232877/"
] | I avoid this issue by adding
```
if __name__ == '__main':
fun()
```
I guess this file will be import or load or something else, then it gets run. Anyway, this is not important. | Perhaps , You have mistakenly installed an extension 'Run on Save' . I think that's causing the Problem. | 11,261 |
4,170,532 | I was not able to come up with a better title for this post, so if anybody does not find it appropriate , please go ahead and edit it.
I am using flask as my python framework, and normally I render templates doing somnething like the below:-
```
@app.route('/home')
def userhome():
data=go get user details from th... | 2010/11/13 | [
"https://Stackoverflow.com/questions/4170532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459514/"
] | I would choose server side templating, because unless you find a JS library that handles the same templating language your code isn't going go be DRY.
In the `home.html` template, I'd do something like
```
<%extends base.html%>
<%include _user_details.html%>
... <% footer and other stuff%>
```
And keep the actual m... | You have two options: template on the server, or template in the browser.
To template in the server, you create an endpoint much like you already have, except the template only creates a portion of the page. Then you hit the URL with an Ajax call, and insert the returned HTML somewhere into your page.
To template in ... | 11,264 |
33,262,919 | When writing doc strings in python, I am wondering if the docstring should contain the exceptions that are implicitly raised or if it should also contain the exceptions I explicitly raise.
Consider the function
```
def inv(a):
if a == 0:
raise ZeroDivisionError
else:
return 1/a
```
So in a d... | 2015/10/21 | [
"https://Stackoverflow.com/questions/33262919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5152563/"
] | It depends what (or whom) you're writing the docstring for. For automatic conversion to API documentation, I like [Google-style docstrings](http://sphinxcontrib-napoleon.readthedocs.org/en/latest/example_google.html), which would look like:
```
def inv(a):
"""Return the inverse of the argument.
Arguments:
... | No. The docstring should describe the input expected. If this were my function, I would include something like this in the docstring:
```
"""Return the inverse of an integer. ZeroDivisionError is raised if zero is
passed to this function."""
```
Therefore it is specified that the input should be an integer. Specify... | 11,265 |
21,234,884 | How can I set a suitable fps number in pygame for any kind of monitor running my game? I know I can set fps using `pygame.time.Clock().tick(fps)` but how can I set suitable fps?
Please post example python code along with answer. | 2014/01/20 | [
"https://Stackoverflow.com/questions/21234884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2837388/"
] | I'm not entirely sure that I understand the question being asked, but I think you will just have to experiment with different numbers and find out what works for you. I find that around 50-100 is a good range.
If what you are trying to do is make game events only update a certain number of times per second while rende... | The trick I've figured out is not limiting the frame rate, but calculating based on time. The pygame.time.Clock.tick() returns time in milliseconds, which you can then pass to other parts of the program to calculate events or animation updates.
For example, I currently use a pair of variable in my Player object to sto... | 11,266 |
58,449,314 | When I activate my ipykernel\_py3 environment and try to launch Jupyter Lab in terminal, I get the repeated error messages as follows:
```
Macintosh-8:~ yuenfannie$ source activate ipykernel_py3
(ipykernel_py3) Macintosh-8:~ yuenfannie$ jupyter lab
[I 12:38:19.969 LabApp] JupyterLab alpha preview extension loaded from... | 2019/10/18 | [
"https://Stackoverflow.com/questions/58449314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4632960/"
] | This is the wrong way round and can never be true, because you're asking for `tt` to be less than 2 and at least 12 at the same time:
```
if 2 >= tt >= 12:
```
You probably meant:
```
if 2 <= tt <= 12:
```
And instead of `elif` with a condition, you can just use `else`. | That is.
```
tt = int(input("What times tables would you like: "))
if 2 <= tt <= 12:
for x in range(1, 13):
aw = tt * x
print(tt, "x", x, " = ", aw)
else:
print("Please enter number between 2 and 12")
``` | 11,267 |
27,948,420 | I am getting confused trying to find a way to **send the left-click in a web browser window in a specific point**. I am using Selenium `selenium-2.44.0` and Python 2.7. My ultimate goal is to be able to click in certain areas in the window, but for now I just want to make sure I am able to click at all. I thought that ... | 2015/01/14 | [
"https://Stackoverflow.com/questions/27948420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3346915/"
] | Assuming there is nothing else going on on your page that would interfere with the click, this should do it:
```
homeLink = driver.find_element_by_link_text("Home")
homeLink.click() #clicking on the Home button and mouse cursor should? stay here
print homeLink.size, homeLink.location
helpLink = driver.find_element_by... | Hard to say for you exact situation but I know a workaround to the question in the summary and bold
>
> send the left-click in a web browser window in a specific point
>
>
>
You just use execute\_script and do the clicking using javascript.
```
self.driver.execute_script('el = document.elementFromPoint(47, 457)... | 11,268 |
18,701,464 | I wanted to write a program to scrape a website from python. Since there is no built-in possibility to do so, I decided to give the BeautifulSoup module a try.
Unfortunately I encountered some problems using pip and ez\_install, since I use Windows 7 64 bit and Python 3.3.
Is there a way to get the BeautifulSoup modu... | 2013/09/09 | [
"https://Stackoverflow.com/questions/18701464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2733724/"
] | Just download [here](http://www.crummy.com/software/BeautifulSoup/bs3/download//) and then add the `BeautifulSoup.py (uncompress the download tarball file use uncompress soft such as 7z)` to your python sys.path use `sys.path.append("/path/to/BeautifulSoup.py")`, of cource you can just put it under your current src dir... | I haven't tried it, but check out [pip](https://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows) to install python packages. It's supposed to be better.
[Why use pip over easy\_install](https://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install)
I have personally used BeautifulSoup a... | 11,269 |
41,525,223 | I'm just trying to run the simple hello world app on their tutorials page. I used to use Google App Engine frequently, but now I can't seem to get it going at all. I'm on win 10 x64. Downloaded latest google cloud sdk, and python version 2.7.13
```
> ERROR 2017-01-07 15:25:21,219 wsgi.py:263] Traceback (most recent... | 2017/01/07 | [
"https://Stackoverflow.com/questions/41525223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4769616/"
] | Google's sample Flask "Hello World" application requires `Flask 0.11.1`.
This library is not vendored by Google, so developers are required to install it via `pip`
>
> This sample shows how to use Flask with Google App Engine Standard.
>
>
> Before running or deploying this application, install the dependencies
> ... | For me, the workaround mentioned here [Google's issue tracker](https://issuetracker.google.com/issues/38290292) worked
* goto [sdk\_home]\google\appengine\tools\devappserver2\python\sandbox.py
* find the definition of \_WHITE\_LIST\_C\_MODULES = [xxx]
add following two lines to the list:
'\_winreg',
'\_ctypes',
* t... | 11,271 |
52,960,057 | I have an assignment where we need to create functions to display text onto the screen in python/pygame. This part I understand. What I don't is that you're supposed to create a function which creates a drop shadow. I know how to make the shadow I just don't know how to make another function to do it and have the optio... | 2018/10/24 | [
"https://Stackoverflow.com/questions/52960057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10391389/"
] | A dropshadow can be rendered by drawing the text twice. The first is a grey version of the text at an offset, then the actual text at the original position.
```
def dropShadowText(screen, text, size, x, y, colour=(255,255,255), drop_colour=(128,128,128), font=None):
# how much 'shadow distance' is best?
dropsh... | I figured it out with help from Kingsley's response. Now you can choose to add a shadow or not, where its positioned and what colour it is. Maybe there is an easier way but this worked for me.
```
import pygame
import sys
pygame.init()
screenSizeX = 1080
screenSizeY = 720
screenSize = (screenSizeX,screenSizeY)
screen... | 11,272 |
18,718,715 | I've been looking into scraping, and I cant manage to scrape twitter searches that date long way back by using python code, i can do it however with an addon for chrome but it falls short since it will only let me obtain a very limited amount of tweets. can anybody point me in the right direction¿ | 2013/09/10 | [
"https://Stackoverflow.com/questions/18718715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2761466/"
] | I found a related answer here:
<https://stackoverflow.com/a/6082633/1449045>
you can get up to 1500 tweets for a search; 3200 for a particular user's timeline
source: <https://dev.twitter.com/docs/things-every-developer-should-know>
see "There are pagination limits"
Here you can find a list of libraries to simplify... | You can use [snscrape](https://github.com/JustAnotherArchivist/snscrape). It doesn't require a Twitter Developer Account it can go back many years. | 11,275 |
26,928,817 | I will start by saying that I have never created an app that required installation and I have no idea how it works. But now I have to, and I am wondering how to proceed, use some kind os installation tools (installshield, wix) or create a python script and turn into an .exe.
What my install needs to do is:
* create a... | 2014/11/14 | [
"https://Stackoverflow.com/questions/26928817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2367912/"
] | I put this logic in my view's `form_valid` like so:
```
def form_valid(self, form):
self.object, created = Car.objects.get_or_create(
**form.cleaned_data
)
return super(CarCreateView, self).form_valid(form)
```
To put that in context, I have a complaints case management system that registers new ... | Do it in form's `clean` method:
```
from django.forms import ModelForm
from myapp.models import Car
class CarForm(ModelForm):
class Meta:
model = Car
def clean(self):
if self._meta.model.objects.filter(**self.cleaned_data).count() > 0:
raise forms.ValidationError('Car already exis... | 11,276 |
52,138,300 | I'm trying to write simple things in a Tkinter module using python 3.6 in Anaconda. This is my code
```
from tkinter import *
root = Tk()
thelabel = label(root, text="this is our tk window")
thelabel.pack()
root.mainloop()
```
but I get the error:
```
TclError: can't invoke "label" command: application has been... | 2018/09/02 | [
"https://Stackoverflow.com/questions/52138300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9784945/"
] | One of the recommended ways to have multiple python installations with differing libraries installed is to use [Virtualenv](https://virtualenv.pypa.io/en/stable/). This gives you the possibility to have a specific python environment with it's own set of dependencies for each project you work on. This works not only for... | I found this to work after searching for a while. Here are the steps I followed to install an older python version alongside my standard one:
* Download the Python3.6 tgz file from the official website (eg. Python-3.6.6.tgz)
* Unpack it with `tar -xvzf Python-3.6.6.tgz`
* `cd Python-3.6.6`
* run `./configure`
* run `m... | 11,277 |
27,751,072 | I have an ordinary Python list that contains (multidimensional) numPy arrays, all of the same shape and with the same number of values. Some of the arrays in the list are duplicates of earlier ones.
I have the problem that I want to remove all the duplicates, but the fact that the data type is numPy arrays complicates... | 2015/01/03 | [
"https://Stackoverflow.com/questions/27751072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541913/"
] | Using the solutions here: [Most efficient property to hash for numpy array](https://stackoverflow.com/questions/16589791/most-efficient-property-to-hash-for-numpy-array) we see that hashing works best with a.tostring() if a is an numpy array. So:
```
import numpy as np
arraylist = [np.array([1,2,3,4]), np.array([1,2,3... | Here is one way using `tuple`:
```
>>> import numpy as np
>>> t = [np.asarray([1, 2, 3, 4]),
np.asarray([1, 2, 3, 4]),
np.asarray([1, 1, 3, 4])]
>>> map(np.asarray, set(map(tuple, t)))
[array([1, 1, 3, 4]), array([1, 2, 3, 4])]
```
If your arrays are multidimensional, then first flatten them to ... | 11,278 |
36,278,220 | I have a big third-party python2.7 application, a bunch of python scripts, which is added into `PATH` and it requires python2.7 instead of python 3.5 which I have by default.
```
$ python
Python 3.5.1 (default, Mar 3 2016, 09:29:07)
[GCC 5.3.0] on linux
Type "help", "copyright", "credits" or "license" for more infor... | 2016/03/29 | [
"https://Stackoverflow.com/questions/36278220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1708058/"
] | My favorite way: use virtualenv or pyenv
========================================
The most used tool for keeping multiple Python environments is [virtualenv](https://virtualenv.pypa.io/en/latest/). I like to use a sugary wrapper around it called [virtualenvwrapper](https://virtualenvwrapper.readthedocs.org/en/latest/)... | You can make use of terminal alias. **The alias will not be temporary** but it will not affect your system, so you can have a short alias like:
**alias pyt "/usr/bin/python2.7"**
in your .bashrc file inside home directory | 11,281 |
42,128,830 | I am trying a simple demo code of tensorflow from [github link](https://github.com/llSourcell/tensorflow_demo).
I'm currently using python version 3.5.2
```
Z:\downloads\tensorflow_demo-master\tensorflow_demo-master>py Python
3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32... | 2017/02/09 | [
"https://Stackoverflow.com/questions/42128830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6833276/"
] | The code link you have provided uses a separate file named `input_data.py` to download data from MNIST using the following two lines in `board.py`
```
import input_data
mnist = input_data.read_data_sets("/tmp/data/",one_hot=True)
```
Since MNIST data is so frequently used for demonstration purposes, Tensorflow prov... | This file is likely corrupt:
```
Z:/downloads/MNIST dataset\train-images-idx3-ubyte.gz
```
Let's analyze the error you posted.
This, indicates that code is currently working with the file in question:
```
Extracting Z:/downloads/MNIST dataset\train-images-idx3-ubyte.gz
```
`Traceback` indicates that a stack tra... | 11,284 |
64,785,224 | How can I remove keys from python dictionary of dictionaries based on some conditions?
Example dictionary:
```
a = {
'k': 'abc',
'r': 20,
'c': {
'd': 'pppq',
'e': 22,
'g': 75
},
'f': ''}
```
I want to remove all entries whose values are type of string. It can contain dictionar... | 2020/11/11 | [
"https://Stackoverflow.com/questions/64785224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3056288/"
] | You could do:
```
a = {
'k': 'abc',
'r': 20,
'c': {
'd': 'pppq',
'e': 22,
'g': 75
},
'f': ''}
def remove_string_values(d):
result = {}
for k, v in d.items():
if not isinstance(v, str):
result[k] = remove_string_values(v) if isinstance(v, dict) el... | Something like this should work:
```
def remove_strings(a):
no_strings = {}
for k,v in a.items():
if type(x) is str:
continue
elif type(x) is dict:
no_strings[k] = remove_strings(v)
else:
no_strings[k] = v
```
This function is recursive - it calls ... | 11,287 |
12,006,267 | So I can create Django model like this:
```
from django.db import models
class Something(models.Model):
title = models.TextField(max_length=200)
```
and I can work with it like this:
```
thing = Something()
#set title
thing.title = "First thing"
#get title
thing.title
```
All works as it should but I'd like ... | 2012/08/17 | [
"https://Stackoverflow.com/questions/12006267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3272/"
] | I think its hard to beat what Django documentation has to [say on this](https://code.djangoproject.com/wiki/DevModelCreation).
>
> The Model class (see base.py) has a **metaclass** attribute that defines ModelBase (also in base.py) as the class to use for creating new classes. So ModelBase.**new** is called to creat... | python is extremely powerfull and permit the developer to use intrespection.
django use a lot of metaclass. and it seem that models.Model use it too. see in
django\db\models\base.py
```
class Model(object):
__metaclass__ = ModelBase
```
i think the metaclass just take the classes attributes such a the Field an... | 11,288 |
64,694,569 | aws cdk returns jsii error on empty stack. Steps to reproduce are at the hello world level which makes me think that I have a version mismatch somewhere. I have re-installed aws cli, cdk and nodejs. Any suggestions on what to look for?
Steps to reproduce:
```
mkdir myfolder
cdk init --language python
.env\Scripts\act... | 2020/11/05 | [
"https://Stackoverflow.com/questions/64694569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14582438/"
] | For AWS-CDK on Windows, there is at least one bug in jsii documented by AWS CDK group. Deep inside the jsiiruntime (line 13278 to be exact), aws cdk group has a comment with a link to a nodejs bug report. I reported my problem to aws-cdk which seemed to be related. They reproduced the bug and created a bug report at no... | TL;DR. Expanded work arounds. (A question was asked in the AWS-CDK bug report noted above).
**Workaround 1: replace jsii 1.14.x distro**
***Distro folders:*** jsii is contained in 2 folders
jsii and jsii-1.14.1.dist-info
REPLACE both of these folders with folders from an older install -- 1.12 or 1.13.
The distro f... | 11,289 |
11,661,053 | I am running Windows 7 currently, and I remember when using Linux at the school computers I was able to type "gedit &" into the terminal for example to open up the gedit text editor. I was wondering whether there is a similar process to open IDLE, and for that matter a Python program/script by typing it into the "termi... | 2012/07/26 | [
"https://Stackoverflow.com/questions/11661053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1553212/"
] | python.exe is the Python interpreter. All of your Python programs are executed with it. If you run it in the console, you will get an interactive prompt:
```
C:\> python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more infor... | python.exe **is** Python, the python interpreter specifically. | 11,290 |
9,353,457 | As I muddle my way through trying to learn how to code (in python) I've hit the same problem I hit frequently.
How do you pass variables to and from functions properly.
In this example, I want to create a new variable inside the function process, but I don't know how to get it back properly (this method does not wo... | 2012/02/19 | [
"https://Stackoverflow.com/questions/9353457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191626/"
] | The `b` inside `func_1()` is local to the function and not available outside of the function. You need to *assign* the returned value of the function `func_1()` to a variable name in the main body.
```
b = func_1()
print b
``` | >
> I am 'expecting' b to be available after the function call, as I have returned it
>
>
>
The fundamental misunderstanding: you aren't returning a variable, you're returning a value. Variables are labels (names) for values. Inside the function, you have a name `b` for a value `"foo"`. You use this name to refer ... | 11,293 |
60,445,837 | i have an api end point where i am uploading data to using python. end point accepts
```
putHeaders = {
'Authorization': user,
'Content-Type': 'application/octet-stream' }
```
My current code is doing this
.Save a dictionary as csv file
.Encode csv to utf8
```
dataFile = open(fileData['name'], 'r').r... | 2020/02/28 | [
"https://Stackoverflow.com/questions/60445837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10004110/"
] | Here's a [working example](https://stackblitz.com/edit/react-ts-w55wqg).
You have to install the `@types/faker` package also for getting type definitions.
```
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import faker from 'faker';
i... | I had the same issue and tried the above suggested solution without success. What worked for me, was changing the following line in `tsconfig.json`:
`//"module": "esnext",
"module": "commonjs",`
Or, pass it at the command-line:
`ts-node -O '{"module": "commonjs"}' ./server/generate.ts > ./server/database.json`
Expl... | 11,303 |
2,754,753 | I use pylons in my job, but I'm new to django. I'm making an rss filtering application, and so I'd like to have two backend processes that run on a schedule: one to crawl rss feeds for each user, and another to determine relevance of individual posts relative to users' past preferences. In pylons, I'd just write paster... | 2010/05/02 | [
"https://Stackoverflow.com/questions/2754753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/303931/"
] | Yes, this is actually how I run my cron backup scripts. You just need to load your virtualenv if you're using virtual environments and your project settings.
I hope you can follow this, but after the line `# manage.py shell` you can write your code just as if you were in `manage.py shell`
You can import your virtuale... | Sounds like you need some twod.wsgi in your life: <http://packages.python.org/twod.wsgi/> | 11,304 |
5,482,546 | so I have a list with a whole bunch of tuples
```
j =
[('jHKT', 'Dlwp Dfbd Gwlgfwqs (1kkk)', 53.0),
('jHKT', 'jbdbjf Bwvbly (1kk1)', 35.0),
('jHKT', 'Tfstzfy (2006)', 9.0),
('jHKT', 'fjznfnt Dwjbzn (1kk1)', 25.0),
('jHKT', 'Vznbsq sfnkz (1k8k)', 4.0),
('jHKT', 'fxzt, Clwwny! (2005)', 8.0),
('jHKT', "Dwfs Thzs jfbn W... | 2011/03/30 | [
"https://Stackoverflow.com/questions/5482546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380714/"
] | I think your code works correctly and you see the first part of the list, where key is realy 0.0. You just sort the list in ascending order :-) | It's probably worth comparing the sorted and unsorted lists to see if the sort is actually changing data. You could try something as simple as:
```
print sum(e[2] for e in j)
j = sorted(j, key=lambda e : e[2])
print sum(e[2] for e in j)
``` | 11,306 |
70,541,783 | I'm python user learning R.
Frequently, I need to check if columns of a dataframe contain NaN(s).
In python, I can simply do
```
import pandas as pd
df = pd.DataFrame({'colA': [1, 2, None, 3],
'colB': ['A', 'B', 'C', 'D']})
df.isna().any()
```
giving me
```
colA True
colB False
dtype: ... | 2021/12/31 | [
"https://Stackoverflow.com/questions/70541783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2743931/"
] | The best waty to check if columns have NAs is to apply a loop to the columns with a function to check whether there is `any(is.na)`.
```
lapply(df, function(x) any(is.na(x)))
$colA
[1] TRUE
$colB
[1] FALSE
```
I can see you load the tidyverse yet did not use it in your example. If we want to do this within the tid... | The easiest way would be:
```
df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D'))
is.na(df)
```
**Output:**
```
colA colB
[1,] FALSE FALSE
[2,] FALSE FALSE
[3,] TRUE FALSE
[4,] FALSE FALSE
```
**Update**, if you only want to see the rows containing NA:
```
> df[rowSums(is.na(df)) > 0,]
... | 11,309 |
67,126,748 | I have a problem with my python(python3.8.5) project! I have two docker containers. One is used for the frontend(container2) using flask. There I have a website where I can send requests(package requests) to the second container(backend). In the backend(container1) I have to create a zip file containing multiple file. ... | 2021/04/16 | [
"https://Stackoverflow.com/questions/67126748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15661344/"
] | A probably incomplete solution, that does what you describe. Depending on other concerns (like file size) this might not be what you really want, but it works.
As an example I have 2 flask servers: flask1 (backend) and flask2 (frontend):
flask1:
```
from flask import Flask, send_file, request
app = Flask(__name__)
... | You could proxy the request from frontend.
I assume you use something like react. So if you add a line like:
```
"proxy": "http://backend-container:8080"
```
to your package.json, frontend should proxy to the backend.
Now you can send requests like http://front-end/api/hello and it will hit the backend.
Not sure if ... | 11,312 |
71,451,635 | This is my first question in here. Question is mostly about Python but a little bit about writing crypto trading bot. I need to calculate some indicators about trading like Bollinger Bands, RSI or etc in my bot.
Indicators are calculated from candlesticks data in trading. And candlesticks data updated in their time pe... | 2022/03/12 | [
"https://Stackoverflow.com/questions/71451635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | It's not quite obvious from your description what `CandlestickUpdater` is for. It looks like its purpose is to notify `TradeControl` that time has come to update `candlestick_data`, whereas updating logic itself is in the `TradeControl.update_candlestick` method. So basically `CandlestickUpdater` is a timer.
There are... | >
> **Q :** *" ... should (I) use mutex-like structures to guard against conditions like race condition "... ?*
>
>
>
**A :**
Given the facts, how the Python Interpreter works ( since ever & most probably forever, as Guido von Rossum has expressed himself ) with all its threads, distributing ***"a permission to ... | 11,313 |
70,648,020 | [](https://i.stack.imgur.com/dbDhf.png)
I configured python 3.6 in JetBrains initially but uninstalled it today since it reached end-of-life. I installed version 3.10 but I keep getting the error that "Python 3.1 has reached end of date."
Clicking on... | 2022/01/10 | [
"https://Stackoverflow.com/questions/70648020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13706804/"
] | We can do this with only one function, `Array.find()`. We can do this by checking if it is equal to the `Remove invalid product` inside the function. See the example below.
```js
const responses = [{
"productName": "Required"
},
null,
{
"status": "Remove invalid product"
},
{
"status": "Remove invalid prod... | You can do it using `array.find()`. Try this code it's help you !
```
function App() {
const responses = [
{
"productName": "Required"
},
null,
{
"status": "Remove invalid product"
},
{
"status": "Remove invalid product"
}
];
return (
<div> checkResponses : {res... | 11,314 |
12,491,731 | I am using tkMessageBox.showinfo ([info at tutorialspoint](http://www.tutorialspoint.com/python/tk_messagebox.htm)) to popup warnings in my program.
The problem happens only when the warning is called with a second TopLevel window (apart from the main one) on screen: in this case the warning remains hidden behind the ... | 2012/09/19 | [
"https://Stackoverflow.com/questions/12491731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/538256/"
] | I think the message box is only ever guaranteed to be above its parent. If you create a second toplevel and you want a messagebox to be on top of that second window, make that second window the parent of the messagebox.
```
tl2 = tk.Toplevel(...)
...
tkMessageBox.showinfo("Say Hello", "Hello World", parent=tl2)
``` | I do not see the issue that you describe. The code I wrote below is just about the minimum needed to create a window which creates a second window. The second window creates an info box using the `showinfo` method. I wonder whether you have something besides this. (Note that I made the windows somewhat large in order t... | 11,317 |
57,672,921 | For clarity, i was looking for a way to compile multiple regex at once.
For simplicity, let's say that every expression should be in the format `(.*) something (.*)`.
There will be no more than 60 expressions to be tested.
As seen [here](https://stackoverflow.com/questions/42136040/how-to-combine-multiple-regex-into-s... | 2019/08/27 | [
"https://Stackoverflow.com/questions/57672921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2243607/"
] | There are various issues with your example:
1. You are using a *capturing* group, so it gets the index `1` that you'd expect to reference the first group of the inner regexes. Use a non-capturing group `(?:%s|%s|%s|%s)` instead.
2. Group indexes increase even inside `|`. So`(?:(a)|(b)|(c))` you'd get:
```
>>> re.matc... | Giacomo answered the question.
However, I also suggest: 1) put the "compile" before the loop, 2) gather non empty groups in a list, 3) think about using (.+) instead of (.\*) in re1,re2,etc.
```
rex= re.compile("%s|%s|%s|%s" % (re1, re2, re3, re4))
for sentence in sentences:
match = rex.search(sentence... | 11,318 |
15,390,807 | Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution.
At the moment I rolled my own naive one:
```
def isqrt(n):
i = int(math.sqrt(n) + 0.5)
if i**2 == n:
return i
raise ValueError('input was... | 2013/03/13 | [
"https://Stackoverflow.com/questions/15390807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/674039/"
] | Sorry for the very late response; I just stumbled onto this page. In case anyone visits this page in the future, the python module gmpy2 is designed to work with very large inputs, and includes among other things an integer square root function.
Example:
```
>>> import gmpy2
>>> gmpy2.isqrt((10**100+1)**2)
mpz(100000... | One option would be to use the `decimal` module, and do it in sufficiently-precise floats:
```
import decimal
def isqrt(n):
nd = decimal.Decimal(n)
with decimal.localcontext() as ctx:
ctx.prec = n.bit_length()
i = int(nd.sqrt())
if i**2 != n:
raise ValueError('input was not a perfe... | 11,319 |
72,394,305 | I used this command:
`python manage.py runserver 0:8080`
After I logined the system I can reach rest API pages, but can't reach other pages.
Although I send a request, the command output does not log.
```
Quit the server with CONTROL-C.
``` | 2022/05/26 | [
"https://Stackoverflow.com/questions/72394305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15506634/"
] | You *can* actually convert from a string holding a base-16 number to a numeric value in plain Sqlite, but it's kind of ugly, using a [recursive CTE](https://sqlite.org/lang_with.html#recursive_common_table_expressions):
```sql
WITH RECURSIVE
hexnumbers(hexstr) AS (VALUES ('0x123'), ('0x4'), ('0x7f')),
parse_hex(nu... | SQLite doesn't convert from hex to dec, you need to write such a function yourself. An example can be found in the [SQLite Forum](https://sqlite.org/forum/info/79dc039e21c6a1ea):
```
/*
** Function UNHEX(arg) -> blob
**
** Decodes the arg which must be an even number of hexidecimal characters into a blob and returns t... | 11,329 |
32,215,510 | I am quite new to use Frame of Tkinter in Python. I discovered Frame from the following [post](https://stackoverflow.com/questions/32198849/set-the-correct-tkinter-widgets-position-in-python)
When i run the GUI the Check box are not in the same line.
[:
def __init__(self):
Frame.__init__(self)
... | 1. Yes, it is possible to use `grid` In any frame you wish
2. Yes, it is possible to place "Camera white balance" and "average white balance" in the same row.
3. The reason the code runs forever without displaying anything is because you are using both grid (for the separator) and pack (for the frames). They both have ... | 11,330 |
35,114,144 | My Celery task raises a custom exception `NonTransientProcessingError`, which is then caught by `AsyncResult.get()`. Tasks.py:
```
class NonTransientProcessingError(Exception):
pass
@shared_task()
def throw_exception():
raise NonTransientProcessingError('Error raised by POC model for test purposes')
```
In ... | 2016/01/31 | [
"https://Stackoverflow.com/questions/35114144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1308967/"
] | ```
import celery
from celery import shared_task
class NonTransientProcessingError(Exception):
pass
class CeleryTask(celery.Task):
def on_failure(self, exc, task_id, args, kwargs, einfo):
if isinstance(exc, NonTransientProcessingError):
"""
deal with NonTransientProcessingErro... | It might be a bit late, but I have a solution to solve this issue. Not sure if it is the best one, but it solved my problem at least.
I had the same issue. I wanted to catch the exception produced in the celery task, but the result was of the class `celery.backends.base.CustomException`. The solution is in the followi... | 11,331 |
20,839,308 | I am using python sklearn library for doing classification of data. Following is the code I have implemented. I just want to ask, is this correct way of classifying? I mean can following code potentially remove all the biases? And, is it 10-k fold cross validation?
```
cv = cross_validation.ShuffleSplit(n_samples, n_i... | 2013/12/30 | [
"https://Stackoverflow.com/questions/20839308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2632729/"
] | you can use:
```
public String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return capitalize(model);
} else {
return capitalize(manufacturer) + " " + model;
}
}
private String capitalize(String s) {
if (s == null ||... | In order to get android device name you have to add only a single line of code:
```
android.os.Build.MODEL;
```
Found here:[getting-android-device-name](http://developer.android.com/reference/android/os/Build.html) | 11,332 |
34,074,840 | I am doing a small python script to perform a wget call, however I am encountering an issue when I am replacing the string that contains the url/ip address and that it will be given to my "wget" string
```
import os
import sys
usr = sys.argv[1]
pswd = sys.argv[2]
ipAddr = sys.argv[3]
wget = "wget http://{IPaddress... | 2015/12/03 | [
"https://Stackoverflow.com/questions/34074840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1757475/"
] | You aren't assigning the result of the `format` call to anything - you're just throwing it away. Try this instead:
```
wget = "wget http://{IPaddress}"
wget = wget.format(IPaddress=ipAddr)
print "The command wget is %s" %wget
os.system(wget)
```
Alternatively, this seems a bit cleaner:
```
wget = "wget http://{I... | You need to actually format your `wget` string like this.
```
import os
import sys
usr = sys.argv[1]
pswd = sys.argv[2]
ipAddr = sys.argv[3]
wget = "wget http://{IPaddress}".format(IPaddress=ipAddr)
print "The command wget is %s" % wget
os.system(wget)
```
`.format()` does not modify the string in place, it ret... | 11,338 |
22,386,359 | I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows ... | 2014/03/13 | [
"https://Stackoverflow.com/questions/22386359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1318479/"
] | In JupyterNotebook cell,
Simply you can use:
```
%%html
<style type='text/css'>
.CodeMirror{
font-size: 17px;
</style>
``` | I would also suggest that you explore the options offered by the [**jupyter themer**](https://github.com/transcranial/jupyter-themer). For more modest interface changes you may be satisfied with running the syntax:
```
jupyter-themer [-c COLOR, --color COLOR]
[-l LAYOUT, --layout LAYOUT]
... | 11,339 |
19,254,178 | essentially I am writing something based off of python and I would like to, in python, be able to get the result of a javascript function.
Lets say `function.js` has a bunch of functions inside it
If I have some python code, in it I would like to be able to do something like the following:
```
val = some_js_function... | 2013/10/08 | [
"https://Stackoverflow.com/questions/19254178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2127988/"
] | My best theory is that this is a possible consequence of dropping and re-creating a table with the same name (<https://issues.apache.org/jira/browse/CASSANDRA-5905>). We are targeting a fix for 2.1 (<https://issues.apache.org/jira/browse/CASSANDRA-5202>); in the meantime, prefer TRUNCATE over drop/recreate. | Although its very late and you must have solve this issue as well. For others having similar problem, try this
```
sudo bash -c 'rm -rf /var/lib/cassandra/data/system/*'
```
Remember, its only for development purposes. **THIS COMMAND WILL DELETE ALL YOUR DATA.** | 11,349 |
51,136,741 | I'm trying to deploy a simple python app to Google Container Engine:
I have created a cluster then run `kubectl create -f deployment.yaml`
It has been created a deployment pod on my cluster. After that i have created a service as: `kubectl create -f deployment.yaml`
>
> Here's my Yaml configurations:
>
>
> **pod.y... | 2018/07/02 | [
"https://Stackoverflow.com/questions/51136741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644562/"
] | >
> The HashedPassword + Salt is stored in a column
>
>
>
That is probably the root problem. You don't need to provide or handle a Salt. See [this answer](http://%20stackoverflow.com/a/17758221/9695604).
You should not need a `GetSalt()` method.
You can't simply concatenate 2 base64 strings, the decoder doesn... | The Base64 format stores 6 bits per character. Which, as bytes are 8 bits, sometimes some padding is needed at the end. One or two `=` characters are appended. `=` is not otherwise used.
If you concatenate two Base64 strings at the join there maybe some padding. Putting padding in the middle of a Base64 string is not ... | 11,350 |
52,648,383 | I am trying to perform a MultiOutput Regression using ElasticNet and Random Forests as follows:
```python
from sklearn.ensemble import RandomForestRegressor
from sklearn.multioutput import MultiOutputRegressor
from sklearn.linear_model import ElasticNet
X_train, X_test, y_train, y_test = train_test_split(X_features, ... | 2018/10/04 | [
"https://Stackoverflow.com/questions/52648383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10456915/"
] | MultiOutputRegressor itself doesn't have these attributes - you need to access the underlying estimators first using the `estimators_` attribute (which, although not mentioned in the [docs](http://scikit-learn.org/stable/modules/generated/sklearn.multioutput.MultiOutputRegressor.html), it exists indeed - see the docs f... | ```
regr_multi_Enet.estimators_[0].coef_
```
To get the coefficients of the first estimator etc. | 11,351 |
26,292,909 | this is my first post here!
My goal is to duplicate the payload of a unidirectional TCP stream and send this payload to multiple endpoints concurrently. I have a working prototype written in Python, however I am new to Python, and to Socket programming. Ideally the solution is capable of running in both Windows and \*... | 2014/10/10 | [
"https://Stackoverflow.com/questions/26292909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4128004/"
] | The problem is caused by missing or conflicting dependencies:
1. Add hadoop-auth to your classpath
2. If the problem still arises, remove hadoop-core from your classpath. It is conflicting with hadoop-auth.
This will solve the problem. | Finally i found an answer for this.
1. Copy the PlatformName class from hadoop-auth and custom compile it locally.
package org.apache.hadoop.util;
public class PlatformName {
```
private static final String platformName = System.getProperty("os.name") + "-" + System.getProperty("os.arch") + "-" + System.getPro... | 11,352 |
4,178,440 | Any Java tutorial that resembles Mark Pilgrim's approach for [DiveIntoPython](http://www.diveintopython.net/)? | 2010/11/14 | [
"https://Stackoverflow.com/questions/4178440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/313127/"
] | What about the official Java Tutorial? I found it pretty helpful to get started with the language. | I haven't read Dive Into Python but I do know that Bruce Eckels Thinking In Java is an excellent book and well worth a look.
Be warned though - it's monster size and not easy to carry around! | 11,353 |
741,063 | I always had doubts when it comes to designing proper report of execution.
Say you have the following (stupid, to be simple) case. I will use python.
```
def doStuff():
doStep1()
doStep2()
doStep3()
```
Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really ... | 2009/04/12 | [
"https://Stackoverflow.com/questions/741063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78374/"
] | I found [this](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) while searching for Aspect Oriented Programming for python. I agree with other posters that such concerns shouldn't be mixed with core logic.
In essence,points where you want to put logging might not always be arbitary, may be concepts like ... | I would use the standard [`logging`](http://docs.python.org/library/logging.html) module that's been part of the standard library since Python 2.3.
That way, there is a good chance that people looking at your code will already know how the `logging` module works. And if they have to learn then at least it's well-docum... | 11,356 |
44,274,464 | I've got a program that reads strings with special characters (used in spanish) from a file. I then use chdir to change to a directory which its name is the string.
For example in a file called "names.txt" I got the following
```
Tableta
Música
.
.
etc
```
That file is encoded in utf-8 so that I read it from pyt... | 2017/05/31 | [
"https://Stackoverflow.com/questions/44274464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7586576/"
] | Your file "names.txt" has a Byte-Order Mask (BOM). To remove it, open the file with the following decoder:
```
f = open("names.txt", encoding="utf-8-sig")
```
As a side note, it is safer to strip a file name: `names[0].strip()` instead of `names[0][:-1]`. | The beginning of your file has the unicode BOM. Skip first character when reading your file or open it with `utf-8-sig` encoding. | 11,366 |
66,801,663 | I have several database tables that I use in Django. Now I want to design everything around the database not in the Django ORM but in the rational style of my MySQL database. This includes multiple tables for different information. I have made a drawing of what I mean. I want the `createsuperuser` command to query once... | 2021/03/25 | [
"https://Stackoverflow.com/questions/66801663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14375016/"
] | <https://docs.djangoproject.com/en/3.1/howto/custom-management-commands/#module-django.core.management>
You can create django custom commands which will looks like:
python manage.py createsuperuser2 (or similar name)
```
class Command(BaseCommand):
def handle(self, *args, **options):
username = input("us... | Just setup `REQUIRED_FIELDS` inside your User class. If you don't have custom user class, create `class User(AbstractUser)` but dont forget to set `AUTH_USER_MODEL = "users.User"` in `settings.py`
```
REQUIRED_FIELDS = ["country","city","street"]
``` | 11,367 |
1,738,494 | I'm having a tough time getting the logging on Appengine working. the statement
```
import logging
```
is flagged as an unrecognized import in my PyDev Appengine project. I suspected that this was just an Eclipse issue, so I tried calling
```
logging.debug("My debug statement")
```
which does not print anything... | 2009/11/15 | [
"https://Stackoverflow.com/questions/1738494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/211584/"
] | The problem is most likely with the setup of the dev\_appserver. Try running it with the -d flag to turn on debugging. | I have experience only with the Java App Engine, but there they set things up to only log WARN and ERROR. Try using one of those and see if you start getting output!
I'm sure there are ways to loosen the filter, but I wouldn't know how to do it in Python. | 11,368 |
50,546,740 | I am using python 3.6.4 and pandas 0.23.0. I have referenced pandas 0.23.0 documentation for constructor and append. It does not mention anything about non-existent values. I didn't find any similar example.
Consider following code:
```
import pandas as pd
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
... | 2018/05/26 | [
"https://Stackoverflow.com/questions/50546740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4446712/"
] | I agree with RafaelC that padding your list for 2018 data with NaNs for missing values is the best way to do this. You can use `np.nan` from Numpy (which you will already have installed since you have Pandas) to generate NaNs.
```
import pandas as pd
import numpy as np
months = ["Jan", "Feb", "Mar", "Apr", "May", "Ju... | You can add a row using `pd.DataFrame.loc` via a series. So you only need to convert your array into a `pd.Series` object before adding a row:
```
df.loc[index_yrs[2]] = pd.Series(r2018, index=df.columns[:len(r2018)])
print(df)
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2016 26.0 ... | 11,371 |
67,407,000 | I have the below `string` as input:
```
'name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0'
```
I wrote function which convert it to `di... | 2021/05/05 | [
"https://Stackoverflow.com/questions/67407000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14976099/"
] | Your approach is good, except for a couple weird things:
* You aren't creating a *JSON* anything, so to avoid any confusion I suggest you don't name your returned dictionary `json_data` or your function `str_2_json`. JSON, or **J**ava**S**cript **O**bject **N**otation is just that -- a standard of denoting an object a... | ```
import json
json_data = json.loads(string)
``` | 11,372 |
55,120,078 | Is there any way to add new records in the file with each field occupying specific size using python? As shown in below picture, there are together 8 columns
`[column number:column bytes] ->[1:20,2:10,3:10,4:39, 6:2, 7:7,8:7]` each of different size. For example if first column value is of 20 bytes "ABBSBABBSBT ", this... | 2019/03/12 | [
"https://Stackoverflow.com/questions/55120078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11056039/"
] | When you use `ParseExact`, your string and format should match *exactly*.
The proper format is: `ddd, d MMM yyyy hh:mm:ss zzz` (or `HH` which depends on your hour format)
After you parse it, you need to use `ToString` to format it with `yyyy-MM-dd'T'hh:mm:ss` format (or `HH` which depends you want [12-hour clock](htt... | You need to specify the format that the input data has (the second parameter of `DateTime.ParseExact`). In your case, the data you provide has the format `ddd, d MMM yyyy hh:mm:ss zzz`. Also, in the last line, where you print the result you have to format it.
So, this is how you have to do it:
```
string dataa = "Mon... | 11,377 |
61,396,228 | How can I convert small float values such as *1.942890293094024e-15* or *2.8665157186802404e-07* to binary values in Python?
I tried [GeeksforGeek's solution](https://www.geeksforgeeks.org/python-program-to-convert-floating-to-binary/), however, it does not work for values this small (I get this error: **ValueError: i... | 2020/04/23 | [
"https://Stackoverflow.com/questions/61396228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13281273/"
] | After some consultation, I found a good [piece of code](https://trinket.io/python3/8934ea47a2) that solves my problem. I just had to apply some little tweaks on it (making it a function, removing automatic input requests etc.).
Huge thanks to @kartoon! | One problem I see is with `str(number).split(".")`. I've added a simple hack before that: `number = "{:30f}".format(number)` so that there is no `e` in number. Though, I'm not sure if the result is correct. | 11,378 |
14,582,773 | my problem is how to best release memory the response of an asynchrones url fetch needs on appengine. Here is what I basically do in python:
```
rpcs = []
for event in event_list:
url = 'http://someurl.com'
rpc = urlfetch.create_rpc()
rpc.callback = create_callback(rpc)
urlfetch.make_fetch_call(rpc, u... | 2013/01/29 | [
"https://Stackoverflow.com/questions/14582773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1471612/"
] | Wrong approach: Put these urls into a (put)-queue, increase its rate to the desired value (defaut: 5/sec), and let each task handle one url-fetch (or a group hereof). Please note that theres a safety limit of 3000 url-fetch-api-calls / minute (and one url-fetch might use more than one api-call) | Use the task queue for urlfetch as well, fan out and avoid exhausting memory, register named tasks and provide the event\_list cursor to next task. You might want to fetch+process in such a scenario instead of registering new task for every process, especially if process also includes datastore writes.
I also find ndb... | 11,379 |
36,011,478 | What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1:
```
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
I would like to add 1 to every second item, which would give:
```
list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11]
```
I've tried:
```
list1[... | 2016/03/15 | [
"https://Stackoverflow.com/questions/36011478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6052660/"
] | ```
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in range(1, len(list1), 2):
list1[i] +=1
print(list1)
```
using i%2 seems not very efficient | Try this:
```
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in range(1,len(list1),2):
list1[i] += 1
``` | 11,380 |
19,378,869 | ```
Error occurred during initialization of VM.
Could not reserve enough space for object heap.
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
```
The bat file has the following command:
```
java -cp stanford-corenlp-3.2.0.jar;stanford-corenlp-3.2.0-models... | 2013/10/15 | [
"https://Stackoverflow.com/questions/19378869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2120596/"
] | I've recently had this issue. I'm running a Django application, which is served by uWSGI. I'm actually running uWSGI processes with as-limit argument set to 512MB. After digging around this, I've discovered that every process which the application runs using subprocess, will keep same OS limits as uWSGI processes.
Aft... | Try setting the heap size explicitly: see [Could not reserve enough space for object heap](https://stackoverflow.com/questions/4401396/could-not-reserve-enough-space-for-object-heap)
This setting can be also be affected by environment variables - you should print the variables in the batch file (I think the `set` comm... | 11,390 |
71,586,428 | I want to find a concise way to sample n consecutive elements with stride m from a numpy array. The simplest case is with sampling 1 element with stride 2, which means getting every other element in a list, which can be done like this:
```
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a[::2]
ar... | 2022/03/23 | [
"https://Stackoverflow.com/questions/71586428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9079872/"
] | If `a` is long enough you could reshape, slice, and ravel
```
a.reshape(-1,3)[:,:2].ravel()
```
But `a` has to be (9,) or (12,). And the result will still be a copy.
The suggested:
```
np.lib.stride_tricks.as_strided(a, (4,2), (8*3, 8)).ravel()[:-1]
```
is also a copy. The `as_strided` part is a view, but `ravel... | This code might be useful, I tested it on the example in the question (n=2, m=3)
```
import numpy as np
def get_slice(arr, n, m):
b = np.array([])
for i in range(0, len(arr), m):
b = np.concatenate((b, arr[i:i + n]))
return b
sliced_arr = get_slice(np.arange(10), n=2, m=3)
print(sliced_arr)
```
... | 11,391 |
63,348,785 | I'm new and trying to follow this tutorial:
<https://www.youtube.com/watch?v=_uQrJ0TkZlc>
from 05:00:00 I follow him just like he doing, then at 05:05:04 when he run the server it's work fine for him, but for me is not.
This is exactly my steps....
After Install django like this:
```
pip install django
```
I writ... | 2020/08/10 | [
"https://Stackoverflow.com/questions/63348785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14068193/"
] | The 2nd approach doesn't require you to have recording rules for every possible interval over which you'd like an average rate, saving resources. | The `avg_over_time(rate(metric_total[5m])[$__interval:])` calculates average of average rates. This isn't a good metric, since [average of averages doesn't equal to average](https://math.stackexchange.com/questions/95909/why-is-an-average-of-an-average-usually-incorrect). So the better approach would be to calculate `r... | 11,392 |
22,204,801 | I need to run a simple C program several time, each one with different input string (let's say AAAAA... increasing size, until I get "TRUE" as output).
e.g.
```
./program A # output FALSE
./program AA # output FALSE
./program AAA # output FALSE
./program AAAA # output FALSE
./program AAAAA # output FALSE
./program AAA... | 2014/03/05 | [
"https://Stackoverflow.com/questions/22204801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219368/"
] | You could try something like this (see [docs](http://docs.python.org/2/library/subprocess.html#subprocess.call)):
```
import subprocess
args = ""
while True:
args += "A"
result = subprocess.call(["./program", "{args}".format(args=args)])
if result == 'TRUE':
break
```
The `subprocess` module... | **file.py**
```
import os
count=10
input="A"
for i in range(0, count):
input_args=input_args+input_args
os.popen("./program "+input_args)
```
running **file.py** would execute **./program** 10 times with increasing `A` input | 11,393 |
48,783,650 | I have a python list l.The first few elements of the list looks like below
```
[751883787]
[751026090]
[752575831]
[751031278]
[751032392]
[751027358]
[751052118]
```
I want to convert this list to pandas.core.series.Series with 2 leading 0.My final outcome will look like
```
00751883787
00751026090
00752575831
007... | 2018/02/14 | [
"https://Stackoverflow.com/questions/48783650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9300211/"
] | you can try:
```
list=[121,123,125,145]
series='00'+pd.Series(list).astype(str)
print(series)
```
output:
```
0 00121
1 00123
2 00125
3 00145
dtype: object
``` | This is one way.
```
from itertools import chain; concat = chain.from_iterable
import pandas as pd
lst = [[751883787],
[751026090],
[752575831],
[751031278]]
pd.DataFrame({'a': pd.Series([str(i).zfill(11) for i in concat(lst)])})
a
0 00751883787
1 00751026090
2 00752575831
3 00... | 11,398 |
42,345,745 | I am using python-social-auth. But when I run makemigrations and migrate. The tables "social\_auth-\*" are not created.
My settings.py looks like this
```
INSTALLED_APPS += (
'social.apps.django_app.default',
)
AUTHENTICATION_BACKENDS += (
'social.backends.facebook.FacebookOAuth2',
'social.backends.google... | 2017/02/20 | [
"https://Stackoverflow.com/questions/42345745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7007547/"
] | I had to migrate to social-auth-core as described in this dokument :
[Migrating from python-social-auth to split social](https://github.com/omab/python-social-auth/blob/master/MIGRATING_TO_SOCIAL.md)
Then all is working fine. But after this problems I am thinking about changing to all-auth.
Regards for any help | Strange .. when entering the admin interface I receive the exception :
```
No installed app with label 'social_django'.
```
But later in the Error Report I have :
```
INSTALLED_APPS
['django.contrib.admin',
'django.contrib.auth',
.....
'myauth.apps.MyauthConfig',
'main.apps.MainConfig',
... | 11,403 |
40,461,824 | I have a Adafruit Feather Huzzah ESP8266 and want to load a lua script onto it.
The script is out of [this Adafruit tutorial](https://learn.adafruit.com/manually-bridging-mqtt-mosquitto-to-adafruit-io/programming-the-esp8266) and I changed only the Wifi and MQTT connection settings.
I followed the instructions at
<h... | 2016/11/07 | [
"https://Stackoverflow.com/questions/40461824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2427707/"
] | Adding a delay of 0.6 ms to the `luatool.py` solved the problem for me:
```
python ./luatool.py --delay 0.6 --port /dev/tty.SLAB_USBtoUART --src LightSensor-master/init.lua --dest init.lua --verbose
```
I found this solution because I read some advice that the python script might try to talk to the Feather faster th... | I had the same problem, I detached the cable and attached again and ran the command
```
sudo python esp8266/luatool.py --delay 0.6 --port /dev/ttyUSB0 --src init.lua --dest init.lua --restart --verbose
```
1st time it fails but next time execute the same command and it works for me. | 11,404 |
49,037,742 | I've noticed that installing Pandas and Numpy (it's dependency) in a Docker container using the base OS Alpine vs. CentOS or Debian takes much longer. I created a little test below to demonstrate the time difference. Aside from the few seconds Alpine takes to update and download the build dependencies to install Pandas... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49037742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3089468/"
] | Debian based images use only `python pip` to install packages with `.whl` format:
```
Downloading pandas-0.22.0-cp36-cp36m-manylinux1_x86_64.whl (26.2MB)
Downloading numpy-1.14.1-cp36-cp36m-manylinux1_x86_64.whl (12.2MB)
```
WHL format was developed as a quicker and more reliable method of installing Python soft... | In this case the alpine not be the best solution change alpine for slim:
FROM python:3.8.3-alpine
========================
Change to that:
`FROM python:3.8.3-slim`
In my case it was resolved with this small change. | 11,405 |
72,095,609 | With given 2D and 1D lists, I have to dot product them. But I have to calculate them without using `.dot`.
For example, I want to make these lists
```
matrix_A = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31]]
vector_x = [0, 1, 2, ... | 2022/05/03 | [
"https://Stackoverflow.com/questions/72095609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19021583/"
] | You could use a list comprehension with nested for loops.
```py
matrix_A = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31]]
vector_x = [0, 1, 2, 3]
result_list = [sum(a*b for a,b in zip(row, vector_x)) for row in matrix_A]
print(re... | If you do not mind using numpy, this is a solution
```
import numpy as np
matrix_A = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31]]
vector_x = [0, 1, 2, 3]
res = np.sum(np.array(matrix_A) * np.array(vector_x), axis=1)
print(res)
... | 11,415 |
41,249,099 | I am able to create a DirContext using the credentials provided. So it seems that I am connecting to the ldap server and verifying credentials but later on we do a .search on the context that we get from these credentials. Here it is failing. I have included my spring security configuration in addition to code that sho... | 2016/12/20 | [
"https://Stackoverflow.com/questions/41249099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431499/"
] | In method searchForUser is called the method SpringSecurityLdapTemplate.searchForSingleEntryInternal where it's passed an array of objects. The first object of array relates to username@domain. The second one, is the username itself. So, when you are searching for (&(objectClass=user)(sAMAccountName={0})) in ActiveDire... | The issue was pretty straightforward once I used Apache Directory Studio to try and run the ldap queries coming out of Spring Security Active Directory defaults. They assume you have an attribute called userPrincipalName which is a combination of the sAMAccountName and the domain.
In the end I had to set the searchFi... | 11,416 |
49,641,899 | I am not familiar with how to export the list to the `csv` in python. Here is code for one list:
```
import csv
X = ([1,2,3],[7,8,9])
Y = ([4,5,6],[3,4,5])
for x in range(0,2,1):
csvfile = "C:/Temp/aaa.csv"
with open(csvfile, "w") as output:
writer = csv.writer(output, lineterminator='\n')
for ... | 2018/04/04 | [
"https://Stackoverflow.com/questions/49641899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6703592/"
] | To output multiple columns you can use [`zip()`](https://docs.python.org/3/library/functions.html#zip) like:
### Code:
```
import csv
x0 = [1, 2, 3]
y0 = [4, 5, 6]
x2 = [7, 8, 9]
y2 = [3, 4, 5]
csvfile = "aaa.csv"
with open(csvfile, "w") as output:
writer = csv.writer(output, lineterminator='\n')
writer.writ... | You could try:
```
with open('file.csv') as fin:
reader = csv.reader(fin)
[fout.write(r[0],r[1]) for r in reader]
```
If you need further help, leave a comment. | 11,417 |
52,149,479 | I am preprocessing a timeseries dataset changing its shape from 2-dimensions (datapoints, features) into a 3-dimensions (datapoints, time\_window, features).
In such perspective time windows (sometimes also called look back) indicates the number of previous time steps/datapoints that are involved as input variables to... | 2018/09/03 | [
"https://Stackoverflow.com/questions/52149479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3482860/"
] | `os.system` is deprecated. Use `subprocess` instead, which will handle the quoting nicely for you.
Since you have a pipe, you would normally have to create 2 `subprocess` objects, but here you just want to feed standard input so:
```
import subprocess
p = subprocess.Popen(["/usr/bin/cmd","-parameters"],stdin=subproce... | If you want to echo quotes, you need to escape them.
For example:
```
echo "value"
```
>
> value
>
>
>
```
echo "\"value\""
```
>
> "value"
>
>
>
So your python code should look like
```
os.system('echo {{\\"value\\": {0:0.0f}}} | /usr/bin/cmd -parameters'.format(value))
```
Note, that you should use... | 11,419 |
72,068,358 | Why python doesn't raise an error when I try do this, instead it print Nothing.
```
empty = []
for i in empty:
for y in i:
print(y)
```
Is that python stop iterate it the first level or it just iterates over and print **None**?
I found this when trying to create a infinite loop but it stop when list bec... | 2022/04/30 | [
"https://Stackoverflow.com/questions/72068358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18132490/"
] | There is nothing to iterate over in `empty` list. Hence, `for` loop won't run even for a single time. However, if it is required to get an error for this you can raise an exception like below:
```
empty = []
if len(empty) == 0:
raise Exception("List is empty")
for i in empty:
for y in i:
print(y)
``` | Your list variable `empty` is initialized with empty list. so, the first iteration itself will not enter, since the list is empty. | 11,420 |
60,233,935 | I have been trying to get my first trial with templating with Ansible to work and I am stopped by this following exception. As far as I can see, I think I have maintained the indentation well and also validated the yml file. I don't know where to go from here, help pls! Below is the yml file followed by the exception I... | 2020/02/14 | [
"https://Stackoverflow.com/questions/60233935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4682497/"
] | There are at minimum two things wrong with the playbook you posted:
1. `hosts:` is a `dict`, but should not be
2. `testhost:` has a `null` value
[Reading the fine manual](https://docs.ansible.com/ansible/2.9/reference_appendices/playbooks_keywords.html#term-hosts) shows that `hosts:` should be a string, or `list[str]... | This error can also happen if you wind up with the wrong structure in your playbook.
For example:
```yaml
tags: # oops
- role: foo/myrole
```
instead of
```yaml
roles:
- role: foo/myrole
``` | 11,422 |
19,306,963 | In a file like:
```
jaslkfdj,asldkfj,,,
slakj,aklsjf,,,
lsak,sajf,,,
```
how can you split it up so there is just a key value pair of the two words? I tried to split using commas but the only way i know how to make key/value pairs is when there is only one commma in a line.
python gives the error: "ValueError: t... | 2013/10/10 | [
"https://Stackoverflow.com/questions/19306963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2844776/"
] | It seems more likely that what you tried is this:
```
>>> line = 'jaslkfdj,asldkfj,,,'
>>> key, value = line.split(',')
ValueError: too many values to unpack (expected 2)
```
There are two ways around this.
First, you can split, and then just take the first two values:
```
>>> line = 'jaslkfdj,asldkfj,,,'
>>> part... | Try slicing for the first two values:
```
"a,b,,,,,".split(",")[:2]
```
Nice summary of slice notation in [this answer](https://stackoverflow.com/a/509295/169121). | 11,423 |
46,554,928 | I don't care if I achieve this through vim, sed, awk, python etc. I tried in all, could not get it done.
For an input like this:
```
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
I want:
```
top f1 f... | 2017/10/03 | [
"https://Stackoverflow.com/questions/46554928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977601/"
] | With this as the input:
```
$ cat file
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
```
Try:
```
$ sed -E ':a; s/^( *) ([^ ])/\1.\2/; ta' file
top f1 f2 f3
...sub1 f1 f2 f3
...sub2 f... | There are two different ways to do this in vim.
1. With a regex:
```
:%s/^\s\+/\=repeat('.', len(submatch(0)))
```
This is fairly straightforward, but a little verbose. It uses the eval register (`\=`) to generate a string of `'.'`s the same length as the number of spaces at the beginning of each line.
2. With a n... | 11,426 |
73,700,589 | I have an integer array.
```
Dim a as Variant
a = Array(1,2,3,4,1,2,3,4,5)
Dim index as Integer
index = Application.Match(4,a,0) '3
```
index is 3 here. It returns the index of first occurrence of 4. But I want the last occurrence index of 4.
In python, there is rindex which returns the reverse index. I am new to v... | 2022/09/13 | [
"https://Stackoverflow.com/questions/73700589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7006773/"
] | [`XMATCH()`](https://support.microsoft.com/en-us/office/xmatch-function-d966da31-7a6b-4a13-a1c6-5a33ed6a0312) avaibalble in O365 and Excel 2021. Try-
```
Sub ReverseMatch()
Dim a As Variant
Dim index As Integer
a = Array(1, 2, 3, 4, 1, 2, 3, 4, 5)
index = Application.XMatch(4, a, 0, -1) '-1 indicate search la... | Try the next way, please:
```
Sub lastOccurrenceMatch()
Dim a As Variant, index As Integer
a = Array(1, 2, 3, 4, 1, 2, 3, 4, 5)
index = Application.Match(CStr(4), Split(StrReverse(Join(a, "|")), "|"), 0) '2
Debug.Print index, UBound(a) + 1 - index + 1
End Sub
```
Or a version not raising an error in ... | 11,435 |
30,236,277 | I am an enthusiastic learner of opencv and write down a code for video streaming with opencv I want to learn the use of cv2.createTrackbar() to add some interactive functionality. Though, I tried this function but its not working for me :
For streaming and resizing the frame i use this code
```
import cv2
import sys... | 2015/05/14 | [
"https://Stackoverflow.com/questions/30236277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4706745/"
] | Your code will surely fail. There are too many issues indicating you haven't read the document. Even the 1st `new_size` one will **fail for sure**.
`cap = cv2.VideoCapture(sys.argv[1])` this is wrong. Because it requires `int` instead of `str`. You have to do `cap = cv2.VideoCapture(int(sys.argv[1]))`
another obviou... | Sorry, i am familiar with c++, here is the C++ code, hope it helps.
The code mentioned below adds a contrast adjustment to the live video stream from the camera using createTrackbar function
```
#include "opencv2\highgui.hpp"
#include "opencv2\core.hpp"
#include <iostream>
using namespace cv;
using namespace std;
in... | 11,438 |
46,248,019 | I am using plotly in a Jupyter notebook (python v3.6) and trying to get the example code for mapbox to work (see: <https://plot.ly/python/scattermapbox/>).
When I execute the cell, I don't get any error, but I see no output either, just a blank output cell. When I mouse over the output cell area, I can see there's a f... | 2017/09/15 | [
"https://Stackoverflow.com/questions/46248019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1404267/"
] | D'oh! Was using the wrong mapbox token. I should have used the public token, but instead used a private one. The only error was a js one in the console.
Thanks user1561393!
```
jupyter labextension install plotlywidget
``` | What is your `mapbox_token`? My guess is you haven't signed up for Mapbox to get an API token (which allows you to download their excellent tile maps for mapbox-gl). The map's not going to show without this token. | 11,439 |
29,974,933 | I am using python multiprocessing Process. Why can't I start or restart a process after it exits and I do a join. The process is gone, but in the instantiated class \_popen is not set to None after the process dies and I do a join. If I try and start again it tells me I can't start a process twice. | 2015/04/30 | [
"https://Stackoverflow.com/questions/29974933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686334/"
] | From the Python multiprocessing documentation.
>
> start()
>
>
> Start the process’s activity.
>
>
> This must be called at most once per process object. It arranges for the object’s run() method to be invoked in a separate process.
>
>
>
A Process object can be run only once. If you need to re-run the same r... | From your question we can just guess, what you're talking about. Are you using `subprocess`? How do you start your process? By invoking `call()` or `Popen()`?
In case I guessed right:
Just keep your `args` list from your `subprocess` call and restart your process by calling that command again. The instance of your su... | 11,440 |
36,996,629 | I am doing `pip install setuptools --upgrade` but getting error below
```
Installing collected packages: setuptools
Found existing installation: setuptools 1.1.6
Uninstalling setuptools-1.1.6:
Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/basecomm... | 2016/05/03 | [
"https://Stackoverflow.com/questions/36996629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450312/"
] | Try to upgrade manually:
```
pip uninstall setuptools
pip install setuptools
```
If it doesn't work, try:
`pip install --upgrade setuptools --user python`
As you can see, the operation didn't get appropriate privilege:
`[Errno 1] Operation not permitted: '/tmp/pip-rV15My-uninstall/System/Library/Frameworks/Python... | I ran into a similar problem but with a different error, and different resolution. (My search for a solution led me here, so I'm posting my details here in case it helps.)
TL;DR: if upgrading `setuptools` in a Python virtual environment appears to work, but reports `OSError: [Errno 2] No such file or directory`, try d... | 11,441 |
12,683,745 | Normally, one shuts down Apache Tomcat by running its `shutdown.sh` script (or batch file). In some cases, such as when Tomcat's web container is hosting a web app that does some crazy things with multi-threading, running `shutdown.sh` gracefully shuts down *some* parts of Tomcat (as I can see more available memory ret... | 2012/10/02 | [
"https://Stackoverflow.com/questions/12683745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892029/"
] | you need to replace `grepResults = subprocess.call([grepCmd], shell=true)` with `grepResults = subprocess.check_output([grepCmd], shell=true)` if you want to save the results of the command in grepResults. Then you can use split to convert that to an array and the second element of the array will be the pid: `pid = int... | You can add "c" to ps so that only the command and not the arguments are printed. This would stop grab from matching its self.
I'm not sure if tomcat shows up as a java application though, so this may not work.
PS: Got this from googling: "grep includes self" and the first hit had that solution.
EDIT: My bad! OK som... | 11,442 |
22,869,920 | I am trying to insert raw JSON strings into a sqlite database using the sqlite3 module in python.
When I do the following:
```
rows = [["a", "<json value>"]....["n", "<json_value>"]]
cursor.executemany("""INSERT OR IGNORE INTO FEATURES(UID, JSON) VALUES(?, ?)""", rows)
```
I get the following error:
>
> sqlite3.P... | 2014/04/04 | [
"https://Stackoverflow.com/questions/22869920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087908/"
] | Your input is interpreted as a list of characters (that's where the '48 supplied' is coming from - 48 is the length of the `<json value>` string).
You will be able to pass your input in as a string if you wrap it in square brackets like so
```
["<json value>"]
```
The whole line would then look like
```
rows = [["... | It's kind of a long shot... but perhaps you could quote the JSON values to ensure the parsing works as desired:
```
cursor.executemany("""INSERT OR IGNORE INTO FEATURES(UID, JSON) VALUES(?, '?')""", rows)
```
EDIT: Alternatively... this might force the json into a sting in the insertion?
```
rows = [ uid, '"{}"'.fo... | 11,445 |
34,227,066 | Using python I can easily increase the current process's niceness:
```
>>> import os
>>> import psutil
>>> # Use os to increase by 3
>>> os.nice(3)
3
>>> # Use psutil to set to 10
>>> psutil.Process(os.getpid()).nice(10)
>>> psutil.Process(os.getpid()).nice()
10
```
However, decreasing a process's niceness does no... | 2015/12/11 | [
"https://Stackoverflow.com/questions/34227066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448640/"
] | Linux, by default, doesn't allow unprivileged users to decrease the nice value (i.e. increase the priority) of their processes, so that one user doesn't create a high-priority process to starve out other users. Python is simply forwarding the error the OS gives you as an exception.
The root user can increase the prior... | This is not a restriction by Python or the `os.nice` interface. It is described in `man 2 nice` that only the superuser may decrease the niceness of a process:
>
> nice() adds inc to the nice value for the calling process. (A higher
> nice value means a low priority.) Only the superuser may specify a
> negative inc... | 11,447 |
41,455,463 | For a list of daily maximum temperature values from 5 to 27 degrees celsius, I want to calculate the corresponding maximum ozone concentration, from the following pandas DataFrame:
[](https://i.stack.imgur.com/iGW9y.png)
I can do this by using the fol... | 2017/01/04 | [
"https://Stackoverflow.com/questions/41455463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7159945/"
] | It means you are using python 2.x and you have many options because default integer division results in integer numbers
option 1: import the division library
```
from __future__ import division
```
option 2: change either of the factors to float or alternatively you can change 3 to float (decimal point) by ading .0... | You could also just do:
```
print 'The diameter of {} is {}'.format("Earth",10/3)
``` | 11,452 |
13,639,464 | I would like a javascript function that mimics the python .format() function that works like
```
.format(*args, **kwargs)
```
A previous question gives a possible (but not complete) solution for '.format(\*args)
[JavaScript equivalent to printf/string.format](https://stackoverflow.com/questions/610406/javascript-eq... | 2012/11/30 | [
"https://Stackoverflow.com/questions/13639464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/188963/"
] | UPDATE: If you're using ES6, template strings work very similarly to `String.format`: <https://developers.google.com/web/updates/2015/01/ES6-Template-Strings>
If not, the below works for all the cases above, with a very similar syntax to python's `String.format` method. Test cases below.
```js
String.prototype.format... | This should work similar to python's `format` but with an object with named keys, it could be numbers as well.
```
String.prototype.format = function( params ) {
return this.replace(
/\{(\w+)\}/g,
function( a,b ) { return params[ b ]; }
);
};
console.log( "hello {a} and {b}.".format( { a: 'foo', b: 'baz'... | 11,454 |
7,800,213 | I'm trying to read data from Google Fusion Tables API into Python using the *csv* library. It seems like querying the API returns CSV data, but when I try and use it with *csv.reader*, it seems to mangle the data and split it up on every character rather than just on the commas and newlines. Am I missing a step? Here's... | 2011/10/17 | [
"https://Stackoverflow.com/questions/7800213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201103/"
] | `csv.reader()` takes in a file-like object.
Change
```
reader = csv.reader(serv_resp.read())
```
to
```
reader = csv.reader(serv_resp)
```
Alternatively, you could do:
```
reader = csv.DictReader(serv_resp)
``` | It's not the CSV module that's causing the problem. Take a look at the output from `serv_resp.read()`. Try using `serv_resp.readlines()` instead. | 11,455 |
68,043,856 | I wrote python code to check how many characters need to be deleted from two strings for them to become anagrams of each other.
This is the problem statement "Given two strings, and , that may or may not be of the same length, determine the minimum number of character deletions required to make and anagrams. Any chara... | 2021/06/19 | [
"https://Stackoverflow.com/questions/68043856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9262680/"
] | You can use [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) for this:
```
from collections import Counter
def makeAnagram(a, b):
return sum((Counter(a) - Counter(b) | Counter(b) - Counter(a)).values())
```
`Counter(x)` (where x is a string) returns a dictionary th... | Assuming there are only lowercase letters
The idea is to make character count arrays for both the strings and store frequency of each character. Now iterate the count arrays of both strings and difference in frequency of any character `abs(count1[str1[i]-‘a’] – count2[str2[i]-‘a’])` in both the strings is the number o... | 11,456 |
49,053,579 | Say I created a django project called `django_site`.
I created two sub-projects: `site1` and `polls`.
You see that I have two `index.html` in two sub-projects directories.
However, now, if I open on web browser `localhost:8000/site1` or `localhost:8000/polls`, they all point to the `index.html` of `polls`.
How can ... | 2018/03/01 | [
"https://Stackoverflow.com/questions/49053579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/546678/"
] | You have to configure urls like this :
In your `django_site directory` you have an url file. You have to get urls from all your django apps :
```
from django.urls import include, path
from django.contrib import admin
from polls import views
from site1 import views
urlpatterns = [
path('polls/', include('polls.u... | I solved the problem by:
In `views.py` in `site1` or `polls`:
```
def index(request):
return render(request, 'polls/index.html', context)
```
And inside `django_site` I created a folder `templates`, then in this folder there are two folders `site1` and `polls`. In each subfolder I put `index.html` respectively. | 11,457 |
30,013,356 | I have a list of emails about 10.000 Long, with incomplete emails id, due to data unreliability and would like to know how can I complete them using python.
sample emails:
xyz@gmail.co
xyz@gmail.
xyz@gma
xyz@g
I've tried using `validate_email` package to filter out bad emails and have tried various re... | 2015/05/03 | [
"https://Stackoverflow.com/questions/30013356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394449/"
] | A strategy to consider is to build a "trie" data structure for the domains that you have such as `gma` and `gmail.co`. Then where a domain is a prefix of one other domain, you can consider going down the longer branch of the trie if there is a unique such branch. This will mean in your example replacing `gma` ultimatel... | ```
def email_check():
fo = open("/home/cam/Desktop/out.dat", "rw+") #output file
with open('/home/cam/Desktop/email.dat','rw') as f:
for line in f:
at_pos=line.find('@')
if line[at_pos + 1] == 'g':
line=line[:at_pos+1]+'gmail.com'
elif line[at_pos +1] == 'y':
... | 11,458 |
53,252,181 | I'm a newby with Spark and trying to complete a Spark tutorial:
[link to tutorial](https://www.youtube.com/watch?v=3CPI2D_QD44&index=4&list=PLot-YkcC7wZ_2sxmRTZr2c121rjcaleqv)
After installing it on local machine (Win10 64, Python 3, Spark 2.4.0) and setting all env variables (HADOOP\_HOME, SPARK\_HOME etc) I'm trying... | 2018/11/11 | [
"https://Stackoverflow.com/questions/53252181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10637265/"
] | The heart of the problem is the connection between pyspark and python, solved by redefining the environment variable.
I´ve just changed the environment variable's values `PYSPARK_DRIVER_PYTHON` from `ipython` to `jupyter` and `PYSPARK_PYTHON` from `python3` to `python`.
Now I'm using Jupyter Notebook, Python 3.7, Jav... | I had the same issue. I had set all the `environment variables` correctly but still wasn't able to resolve it
In my case,
```
import findspark
findspark.init()
```
adding this before even creating the sparkSession helped.
I was using `Visual Studio Code` on `Windows 10` and spark version was `3.2.0`. Python versio... | 11,459 |
25,484,269 | I am not an experienced programmer, I have a problem with my code, I think it's a logical mistake of mine but I couldn't find an answer at <http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/whilestatements.html> .
What I want is to check if the serial device is locked, and the different between conditions that "it ... | 2014/08/25 | [
"https://Stackoverflow.com/questions/25484269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3918035/"
] | Use `break` to exit a loop:
```
while True:
ser = serial.Serial("/dev/ttyUSB0", 4800, timeout =1)
checking = ser.readline();
if checking.find(",,,,"):
print "not locked yet"
else:
print "locked and loaded"
break
```
The `True` and `False` line didn't do anything in your code; ... | You can use a variable as condition for your `while` loop instead of just `while True`. That way you can change the condition.
So instead of having this code:
```
while True:
...
if ...:
True
else:
False
```
... try this:
```
keepGoing = True
while keepGoing:
ser = serial.Serial... | 11,469 |
31,018,497 | I'm a newbie to python.
I was trying to display the time duration.
What I did was:
```
startTime = datetime.datetime.now().replace(microsecond=0)
... <some more codes> ...
endTime = datetime.datetime.now().replace(microsecond=0)
durationTime = endTime - startTime
print("The duration is " + str(durationTime))
```
The... | 2015/06/24 | [
"https://Stackoverflow.com/questions/31018497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4528322/"
] | You can split your timedelta as follows:
```
>>> hours, remainder = divmod(durationTime.total_seconds(), 3600)
>>> minutes, seconds = divmod(remainder, 60)
>>> print '%s:%s' % (minutes, seconds)
```
This will use python's builtin divmod to convert the number of seconds in your timedelta to hours, and the remainder w... | You can do this by converting `durationTime` which is a `datetime.timedelta` object to a `datetime.time` object and then using `strftime`.
```
print datetime.time(0, 0, durationTime.seconds).strftime("%M:%S")
```
Another way would be to manipulate the string:
```
print ':'.join(str(durationTime).split(':')[1:])
``... | 11,470 |
42,157,406 | I'm a beginner to mongodb and python, and i'm trying to write python code to delete the documents of multiple collections older than 30 days based on date field which is of NumberLong type and also has to export the collections to CSV before deleting. I'm using below simple code to print the records as a first step by ... | 2017/02/10 | [
"https://Stackoverflow.com/questions/42157406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7544956/"
] | I use datetime for dates in python..
This is an example:
```
import datetime
date = datetime.date(2017,2,10)
otherDate = datetime.date(1999,1,1)
date < otherDate # False
``` | You have to use [datetime.datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime) like this:
`query = {"date": {"$lt": datetime.datetime(2021, 6, 14, 0, 0, 0, 0)}}`
To use the current time you can do:
`query = {"date": {"$lt": datetime.now(timezone.utc)}}`
Source: <https://pymongo.readthedocs.i... | 11,471 |
41,403,465 | My flask app is outputting 'no content' for the `for()` block and i dont know why.
I tested my query in `app.py` , here is `app.py`:
```
# mysql config
app.config['MYSQL_DATABASE_USER'] = 'user'
app.config['MYSQL_DATABASE_PASSWORD'] = 'mypass'
app.config['MYSQL_DATABASE_DB'] = 'mydbname'
app.config['MYSQL_DATABASE_HO... | 2016/12/30 | [
"https://Stackoverflow.com/questions/41403465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/700070/"
] | You haven't got anything in your template called `blogposts`. You need to use keyword arguments to pass the data:
```
return render_template('index.html', blogposts=blogposts)
```
Also note you should really do that query inside the function, otherwise it will only ever execute on process start and you'll always ha... | I had same problem. I solved it as change directory of terminal to the folder containing app.py and then run
```
export FLASK_APP=app.py
```
then, you should run
```
python -m flask run
``` | 11,473 |
35,538,814 | I have a bunch of `.java` files in a directory and I want to compile all of them to `.class` files via python code.
As you know, the `Javac` command line tool is the tool that I must use and it require the name of `.java` files to be equal with the class name. Unfortunately for my `.java` files, it isn't. I mean they... | 2016/02/21 | [
"https://Stackoverflow.com/questions/35538814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3580433/"
] | In many cases a simple regex will work.
If you want to be 100% certain I suggest using a full-blown Java parser like [javalang](https://github.com/c2nes/javalang) to parse each file, then walk the AST to pull out the class name.
Something like
```
import glob
import javalang
# look at all .java files in the working... | This regex works for me. `(?<=^public class )\b.*\b(?= extends Applet)`.
The way to use it correctly:
```
re.compile(ur'(?<=^public class )\b.*\b(?= extends Applet)', re.MULTILINE)
``` | 11,474 |
42,501,900 | I just wanted to ask you all about what is fitfunc, errfunc followed by scipy.optimize.leastsq is intuitively. I am not really used to python but I would like to understand this. Here is the code that I am trying to understand.
```
def optimize_parameters2(p0,mz):
fitfunc = lambda p,p0,mz: calculate_sp2(p, p0, mz)... | 2017/02/28 | [
"https://Stackoverflow.com/questions/42501900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6646128/"
] | Inspite of `change` event trigger the modal on `click` event of `select option` like
```
$('select option').on('click',function(){
$("#modelId").modal('show');
});
``` | You can also use modal function
```
$('select option').on('click'function(){
$('modelId').modal('show');
});
``` | 11,476 |
58,370,832 | I wanted to include an XML file in another XML file and parse it with python. I am trying to achieve it through Xinclude. There is a file1.xml which looks like
```
<?xml version="1.0"?>
<root>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="file2.xml" parse="xml" />
</document>
<test... | 2019/10/14 | [
"https://Stackoverflow.com/questions/58370832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186922/"
] | Not sure why you want to use XInclude, but including an XML file in another one is a basic mechanism of SGML and XML, and can be achieved without XInclude as simple as:
```
<!DOCTYPE root [
<!ENTITY externaldoc SYSTEM "file2.xml">
]>
<root>
<document>
&externaldoc;
</document>
<test>some text</test>
</root... | You need to make xml.etree to include the files referenced with xi:include.
I have added the key line to your original example:
```
from xml.etree import ElementTree, ElementInclude
tree = ElementTree.parse("file1.xml")
root = tree.getroot()
#here you make the parser actually include every referenced file
ElementInc... | 11,479 |
48,848,829 | I'm coming from Python so trying to figure out basic things in Js.
I have the following:
```
{
name: 'Jobs ',
path: '/plat/jobs',
meta: {
label: 'jobs',
link: 'jobs/Basic.vue'
},
```
what I want is to create this block for each element in a list using a for loop (including the brackets)
in python t... | 2018/02/18 | [
"https://Stackoverflow.com/questions/48848829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2680978/"
] | Included is an example that operates on an array of objects, returning a new array of objects. An object is overloaded in JavaScript, but in this case it is synonymous in other languages to a hash, object, or dictionary (depending on application).
```js
let items = [{
name: 'foo',
path: 'foopath',
label: 'foo... | I would use the list.map function
```
items.map(i => {
return {
name: i.name,
path: i.path,
meta: {
label: i.label,
link: i.link
}
}))
```
This will return a new list of items as specified
NOTE: this can be simplified further with an implicit return
... | 11,481 |
45,705,876 | Say I am working with OpenGL in python.
Often times you make a call such as
```
glutDisplayFunc(display)
```
where display is a function that you have written.
What if I have a class
```
class foo:
#self.x=5
def display(self, maybe some other variables):
#run some code
print("Hooray!, X ... | 2017/08/16 | [
"https://Stackoverflow.com/questions/45705876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4327053/"
] | You can call method of another component from a different component but it will not update the value of the calling component without some tweaking like
`Event Emitters` if they have a parent child relationship or `Shared Services` or using `ngrx redux pattern`
How to Call a different component method be like
Compon... | You **`cannot`** do that, There are two possible ways you could achieve this,
1. use **[`angular service`](https://angular.io/tutorial/toh-pt4)** to pass the data between two components
2. use **[`Event Emitters`](https://angular.io/api/core/EventEmitter)** to pass the value among the components. | 11,482 |
5,369,546 | I tried to install python below way. But this did not work.
This take "error: bad install directory or PYTHONPATH".
[What's the proper way to install pip, virtualenv, and distribute for Python?](https://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python/4325047... | 2011/03/20 | [
"https://Stackoverflow.com/questions/5369546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/104080/"
] | For completeness, here's another way of causing this:
```
@if(condition)
{
<input type="hidden" value="@value">
}
```
The problem is that the unclosed element makes it not obvious enough that the content is an html block (but we aren't *always* doing xhtml, right?).
In this scenario, you can use:
```
@if(condi... | I've gotten this issue with Razor. I'm not sure if it's a bug in the parser or what, but the way I've solved it is to break up the:
```
@using(Html.BeginForm()) {
<h1>Example</h1>
@foreach (var post in Model.Posts)
{
Html.RenderPartial("ShowPostPartial", post);
}
}
```
into:
```
@{ Html.BeginForm(); }
<h1>Ex... | 11,483 |
40,619,916 | I am supposed to check if a word or sentence is a palindrome using code, and I was able to check for words, but I'm having trouble checking sentences as being a palindrome. Here's my code, it's short but I'm not sure how else to add it to check for sentence palindromes. I'm sort of a beginner at python, and I've alread... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40619916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7087165/"
] | ```
import string
def is_palindrome(s):
whitelist = set(string.ascii_lowercase)
s = s.lower()
s = ''.join([char for char in s if char in whitelist])
return s == s[::-1]
``` | Without for:
```
word_pilandrom = str(input("Please enter a word: "))
new_word=word_pilandrom.lower().replace(" ","")
if new_word[::1] == new_word[::-1]:
print("OK")
else:
print("NOT")
``` | 11,489 |
39,834,949 | I'm aware this is normally done with twistd, but I'm wanting to use iPython to test out code 'live' on twisted code.
[How to start twisted's reactor from ipython](https://stackoverflow.com/questions/4673375/how-to-start-twisteds-reactor-from-ipython) asked basically the same thing but the first solution no longer work... | 2016/10/03 | [
"https://Stackoverflow.com/questions/39834949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4443898/"
] | Async code in general can be troublesome to run in a live interpreter. It's best just to run an async script in the background and do your iPython stuff in a separate interpreter. You can intercommunicate using files or TCP. If this went over your head, that's because it's not always simple and it might be best to avoi... | While this doesn't answer the question I thought I had, it does answer (sort of) the question I posted. Embedding ipython works in the sense that you get access to business objects with the reactor running.
```
from twisted.internet import reactor
from twisted.internet.endpoints import serverFromString
from myfactory ... | 11,499 |
24,053,152 | I want to convert date like Jun 28 in datetime format like 2014-06-28. I tried following code and many more variation which gives me correct output in ipython but I m unable to save the record in database. It throws error as value has an invalid date format. It must be in YYYY-MM-DD format. Can anyone help me to fix th... | 2014/06/05 | [
"https://Stackoverflow.com/questions/24053152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3446107/"
] | Once you have a `date` object, you can use the `strftime()` function to [format](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior) it into a string.
Let's say `new_date` is your date object from your question. Then you can do:
```
new_date.strftime('%Y-%m-%d')
```
Btw, you can do the s... | I tried on console:
```
>>import datetime
>>datetime.datetime.strptime("Jun-08-2013", '%b-%d-%Y').date()
datetime.date(2013, 6, 8)
```
There are several errors in the code. So solution should be:
```
m = "Jun"
d = 28
if datetime.datetime.strptime("Aug",'%b').month > datetime.datetime.now().m... | 11,500 |
64,956,344 | I have created a python program that works fine. but I want to make it more neat, I ask the user for numbers, number1, number2 etc. up to 5. I want to just do this with a for loop though, like this
```
for i in range(0,5):
number(i) = int(input("what is the number"))
```
I realise that this code docent actually ... | 2020/11/22 | [
"https://Stackoverflow.com/questions/64956344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14640673/"
] | What your code is, cannot be done per se but it can be done using lists like this:
```
number_list = []
for i in range(5);
number = int(input("What is the number?"))
number_list.append(number)
// Now you can access the list using indexes
for j in len(number_list):
print(number_list[j])
``` | If you want to save also variable names you can use python `dictionaries` like this:
```
number = {}
for i in range(0,5):
number[f'number{i}'] = int(input("what is the number "))
print(number)
```
output:
```
{'number0': 5, 'number1': 4, 'number2': 5, 'number3': 6, 'number4': 3}
``` | 11,501 |
849,058 | Consider this python program:
```
import sys
lc = 0
for line in open(sys.argv[1]):
lc = lc + 1
print lc, sys.argv[1]
```
Running it on my 6GB text file, it completes in ~ 2minutes.
Question: **is it possible to go faster?**
Note that the same time is required by:
```
wc -l myfile.txt
```
so, I suspect the... | 2009/05/11 | [
"https://Stackoverflow.com/questions/849058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25891/"
] | as others have said - "no"
Almost all of your time is spent waiting for IO. If this is something that you need to do more than once, *and* you have a machine with tons of ram, you could keep the file in memory. If your machine has 16GB of ram, you'll have 8GB available at /dev/shm to play with.
Another option:
If you... | Note that Python I/O is implemented in C, so there is not much luck speeding it up further. | 11,504 |
58,837,883 | I was automating software installation using python's pyautogui model. So, I crop some images from installation screen like for clicking next, accept the terms and conditions. Using image search I am able to locate the image on the screen and able to click on the right areas. Works fine in my system.
However, the scrip... | 2019/11/13 | [
"https://Stackoverflow.com/questions/58837883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2853557/"
] | As far as I can assume! The problem is with image resolution.
In my company, I also have a robot that automates some complex task. All the monitors here are same but still, I was facing some trouble matching images. Cropped image from one PC was not working on another. So what I am doing right now is using "SNIPPING TO... | You can change the resolution if you make script in `1366x768`and trying in 1920x1080 it will never work because you need to add new image
there are two ways you can use:
1:> replace the image
2:> add the x,y position
**Way:**
```
xy = pyautogui.locateCenterOnScreen('your directory', grayscale=True, confidence=.5... | 11,514 |
41,734,584 | I have some background in machine learning and python, but I am just learning TensorFlow. I am going through the [tutorial on deep convolutional neural nets](https://www.tensorflow.org/tutorials/deep_cnn/) to teach myself how to use it for image classification. Along the way there is an exercise, which I am having trou... | 2017/01/19 | [
"https://Stackoverflow.com/questions/41734584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6862133/"
] | I'm also working on this exercise. I'll try and explain my approach properly, rather than just give the solution. It's worth looking back at the mathematics of a fully connected layer (<https://www.tensorflow.org/get_started/mnist/beginners>).
So the linear algebra for a fully connected layer is:
*y = W \* x + b*
wh... | I'll try to answer your question although I'm not 100% I got it right as well.
Looking at the cuda-convnet [architecture](https://github.com/akrizhevsky/cuda-convnet2/blob/master/layers/layers-cifar10-11pct.cfg) we can see that the TensorFlow and cuda-convnet implementations start to differ after the second pooling l... | 11,515 |
2,860,106 | Would it be possible to create a class interface in python and various implementations of the interface.
Example: I want to create a class for pop3 access (and all methods etc.). If I go with a commercial component, I want to wrap it to adhere to a contract.
In the future, if I want to use another component or code m... | 2010/05/18 | [
"https://Stackoverflow.com/questions/2860106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | Of course. There is no need to create a base class or an interface in this case either, as everything is dynamic. | Yes, this is possible. There are typically no impediments to doing so: just keep a stable API and change how you implement it. | 11,516 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.