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 |
|---|---|---|---|---|---|---|
5,939,850 | I'm writing some shell scripts to check if I can manipulate information on a web server.
I use a bash shell script as a wrapper script to kick off multiple python scripts in sequential order
The wrapper script takes the web server's host name and user name and password. and after performing some tasks, hand's it to th... | 2011/05/09 | [
"https://Stackoverflow.com/questions/5939850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745512/"
] | Please try the following code.
```
<?php
$thumbnail_id = get_post_thumbnail_id(get_the_ID());
if (!empty($thumbnail_id))
{
$thumbnail = wp_get_attachment_image_src($thumbnail_id, 'full');
if (count ($thumbnail) >= 3)
{
$thumbnail_url = $thumbnail[0];
$thumbnail_width = $thumbnail[1];
$thumbnail_heigh... | What about putting a around that an setting the above code and then using CSS to set the width and height? Something like this:
**CSS**
```
.deals img {
width: 620px;
max-height: 295px;
}
```
**HTML / PHP**
```
<div class="deals"><?php the_post_thumbnail( array(620,295) ); ?></div>
``` | 13,794 |
49,809,680 | I'm extremely new to python, I've just got it set up on Visual Studio 2017CE version 15.6.6 on Windows 7 SP1 x64 Home Premium. I went through a couple of walk through tutorials and can verify that at the least Python is installed and working.
I'm trying to follow instructions from the MPIR documentations on building ... | 2018/04/13 | [
"https://Stackoverflow.com/questions/49809680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1757805/"
] | As Intel Core 2 Quad Q9650 is a Yorkfield core from the Penryn family,
18. core2\_penryn (x64)
should be fine. | And for the second part of your question, mpir\_config.py will generate 2 projects in the mpir-3.0.0\build.vc15 solution directory : one for the dynamic lib, and one for the static lib.
Just open mpir.sln and build the desired one. | 13,795 |
53,311,249 | I am reading a utf8 file with normal python text encoding. I also need to get rid of all the quotes in the file. However, the utf8 code has multiple types of quotes and I can't figure out how to get rid of all of them. The code below serves as an example of what I've been trying to do.
```
def change_things(string, re... | 2018/11/15 | [
"https://Stackoverflow.com/questions/53311249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10655038/"
] | You can just type those sorts of into your file, and replace them same as any other character.
```
utf8_quotes = "“”‘’‹›«»"
mystr = 'Text with “quotes”'
mystr.replace('“', '"').replace('”', '"')
```
There's a few different single quote variants too. | There's a list of unicode quote marks at <https://gist.github.com/goodmami/98b0a6e2237ced0025dd>. That should allow you to remove any type of quotes. | 13,796 |
72,148,172 | Is there a website or git repository where there is a clear listing of all the python packages and other dependencies installed on Google CoLaboratory? Is there a docker image that corresponds to a Google CoLab environment? | 2022/05/06 | [
"https://Stackoverflow.com/questions/72148172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3659451/"
] | I see your question is to view the already installed packages in google colab.
You can run this command for viewing it:
```
!pip list -v | grep [Kk]eras
```
You can also view all the packages, through this command:
```
!pip list -v
```
For more info, visit [this link](https://colab.research.google.com/github/avi... | You can find out about all the packages installed in Colab using
```
!pip list -v
```
Where it shows you the packages' names, versions, locations, and the installer. | 13,798 |
34,461,003 | I'm new to programming and am learning Python with the book Learning Python the Hard Way. I'm at exercise 36, where we're asked to write our own simple game.
<http://learnpythonthehardway.org/book/ex36.html>
(The problem is, when I'm in the hallway (or more precisely, in 'choices') and I write 'gate' the game respond... | 2015/12/25 | [
"https://Stackoverflow.com/questions/34461003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5713452/"
] | >
> The problem is, when I'm in the hallway (or more precisely, in
> 'choices') and I write 'gate' the game responds as if I said "man" of
> "oldman" etc.
>
>
>
Explanation
-----------
What you were doing was being seen by Python as:
```
if ("oldman") or ("man") or ("ask" in choice):
```
Which evaluates to T... | Look carefully at the evaluation of your conditions:
```
if "oldman" or "man" or "ask" in choice:
```
This will first evaluate if `"oldman"` is `True`, which happens to be the case, and the `if` condition will evaluate to be `True`.
I think what you intended is:
```
if "oldman" in choice or "man" in choice... | 13,800 |
49,978,967 | I have a nested list like this :
```
[['Asan', '20180418', 'A', '17935.00'],
['Asan', '20180417', 'B', '17948.00'],
['Asan', '20180416', 'C', '17979.00'],
['Asan', '20180416', 'D', '17816.00'],
.
.
.
.
['Asan', '20180415', 'N', '18027.00']]
```
I need to do some calculations for the 3rd element in every list... | 2018/04/23 | [
"https://Stackoverflow.com/questions/49978967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8077586/"
] | [`zip`](https://docs.python.org/3.4/library/functions.html#zip) makes things easy here for pair-wise comparison:
```
l = [['Asan', '20180418', 'A', '17935.00'],
['Asan', '20180417', 'B', '17948.00'],
['Asan', '20180416', 'C', '17979.00'],
['Asan', '20180416', 'C', '200.00'],
['Asan', '20180416', 'D... | Do you mean something like this?
```
l = [['Asan', '20180418', 'A', '17935.00'],
['Asan', '20180417', 'B', '17948.00'],
['Asan', '20180416', 'C', '17979.00'],
['Asan', '20180416', 'C', '200.00'],
['Asan', '20180416', 'D', '17816.00']]
last_seen = l[0]
new_list = []
for r in l[1:]:
if r[2] == ... | 13,801 |
9,874,042 | I'm trying to complete 100 model runs on my 8-processor 64-bit Windows 7 machine. I'd like to run 7 instances of the model concurrently to decrease my total run time (approx. 9.5 min per model run). I've looked at several threads pertaining to the Multiprocessing module of Python, but am still missing something.
[Usin... | 2012/03/26 | [
"https://Stackoverflow.com/questions/9874042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/698809/"
] | I don't see any computations in the Python code. If you just need to execute several external programs in parallel it is sufficient to use `subprocess` to run the programs and `threading` module to maintain constant number of processes running, but the simplest code is using `multiprocessing.Pool`:
```
#!/usr/bin/env ... | Here is my way to maintain the minimum x number of threads in the memory. Its an combination of threading and multiprocessing modules. It may be unusual to other techniques like respected fellow members have explained above BUT may be worth considerable. For the sake of explanation, I am taking a scenario of crawling a... | 13,806 |
34,889,737 | I am a new programmer that just learned python so I made a small program just for fun:
```
year = int(input("Year Of Birth: "), 10)
if year < 2016:
print("You passed! You may continue!")
else:
break
```
I searched this up and I tried using break but I got a error saying I have to use break outside of the l... | 2016/01/20 | [
"https://Stackoverflow.com/questions/34889737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4584838/"
] | `Break` is used in a `loop`. For example:
```
i = 3
while True:
i = i + 1 #increments i by 1
print(i)
if i == 5:
break
print("Done!")
```
Normally, `while True` will execute indefinitely because `True` is always equal to `True`. (This is equivalent to something like `1==1`). The `break` stateme... | `Break` is used inside a loop to get out of that loop which looks something like `while`, `for` and you are trying to use it in Flow Control statements i.e `if` , `elif` and `else` | 13,807 |
68,940,884 | I have written a code in javascript that I don't know how to write in python. The use of it is rather simple. There are 2 variables: Buy and Sell. E.g There is Buy, Buy, Sell, Buy, Sell, Sell
the javascript gives me a new list with Buy,Sell,Buy,Sell
```
´´const fs = require('fs');
class Trade {
price;
side;
}
const... | 2021/08/26 | [
"https://Stackoverflow.com/questions/68940884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16480780/"
] | You can try:
1. `stack` all the dates into one column
2. `drop_duplicates`: effectively getting rid of equal end and start dates
3. Keep every second row and restructure the result
```
df = df.sort_values(["category", "start", "end"])
stacked = df.set_index("category").stack().droplevel(-1).rename("start")
output = s... | You could do it like this:
**Sample data:**
```
import pandas as pd
d = {'category': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B'}, 'start': {0: '2015-01-01', 1: '2016-01-01', 2: '2016-06-01', 3: '2016-01-01', 4: '2018-01-01'}, 'end': {0: '2016-01-01', 1: '2016-06-01', 2: '2016-12-01', 3: '2016-07-01', 4: '2018-08... | 13,808 |
57,665,576 | I’m new to nix and would like to be able to install openconnect with it.
Darwin seems to be unsupported at this time via nix, though it can be installed with either brew or macports.
I’ve tried both a basic install and allowing unsupported. I didn’t see anything on google or stackoverflow as yet that helped.
Basic ... | 2019/08/26 | [
"https://Stackoverflow.com/questions/57665576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1241878/"
] | Please check this
```
let dataJobs = await page.evaluate(()=>{
var a = document.getElementById("task-listing-datatable").getAttribute("data-tasks"); //Search job list
var ar = eval(a);//Convert string to arr
var keyword = ['Image Annotation', 'What Is The Best Dialogue Category About Phones', 'Lab... | why not try and save the result of the match in a dynamic array instead of returning the value, something like a global array:
```
let array = [];
let dataJobs = await page.evaluate(()=>{
var a = document.getElementById("task-listing-datatable").getAttribute("data-tasks"); //Search job list
var ar = eval(a);//... | 13,809 |
60,920,262 | First I have created an environment in anaconda navigator in which i have installed packages like Keras,Tensorflow and Theano.
Now I have activated my environment through anaconda navigator and have launched the Spyder Application.
Now When i try to import keras it is showing error stating that:
```
Traceback (most r... | 2020/03/29 | [
"https://Stackoverflow.com/questions/60920262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13148984/"
] | You could use below aggregation for unique active users over day and month wise. I've assumed ct as timestamp field.
```
db.collection.aggregate(
[
{"$match":{"ct":{"$gte":dateFrom,"$lt":dateTo}}},
{"$facet":{
"dau":[
{"$group":{
"_id":{
"user":"$user",
"ymd":{"$dateToString":... | I made a quick test on a large database of events, and counting with a distinct is much faster than an aggregate if you have the right indexes :
```
collection.distinct('user', { ct: { $gte: dateFrom, $lt: dateTo } }).length
``` | 13,810 |
51,549,234 | I'm trying to spin up an EMR cluster with a Spark step using a Lambda function.
Here is my lambda function (python 2.7):
```
import boto3
def lambda_handler(event, context):
conn = boto3.client("emr")
cluster_id = conn.run_job_flow(
Name='LSR Batch Testrun',
ServiceRole='EMR_DefaultR... | 2018/07/27 | [
"https://Stackoverflow.com/questions/51549234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5175894/"
] | I could solve the problem eventually. Main problem was the broken "Applications" configuration, which has to look like the following instead:
```
Applications=[{
'Name': 'Spark'
},
{
'Name': 'Hive'
}],
```
The final Steps element:
```
Steps=[{
'Name': 'lsr-step1',
... | Not all EMR pre-built with ability to copy your jar, script from S3 so you must do that in bootstrap steps:
```
BootstrapActions=[
{
'Name': 'Install additional components',
'ScriptBootstrapAction': {
'Path': code_dir + '/scripts' + '/emr_bootstrap.sh'
}
}
],
```
And here ... | 13,813 |
53,503,196 | I want to separate the exact words of a text file (*text.txt*) ending in a certain string by using 'endswith'. The fact is that my variable
```
h=[w for w in 'text.txt' if w.endswith('os')]
```
does not give what I want when I call it. On the other hand, if I try naming the open file
```
f=open('text.txt')
h=[w fo... | 2018/11/27 | [
"https://Stackoverflow.com/questions/53503196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10502088/"
] | Open the file first and then process it like this:
```
with open('text.txt', 'r') as file:
content = file.read()
h=[w for w in content.split() if w.endswith('os')]
``` | ```
with open('text.txt') as f:
words = [word for line in f for word in line.split() if word.endswith('os')]
```
Your first attempt does not read the file, or even open it. Instead, it loops over the characters of the string `'text.txt'` and checks each of them if it ends with `'os'`.
Your second attempt iterate... | 13,814 |
55,318,862 | I want to try to make a little webserver where you can put location data into a database using a grid system in Javascript. I've found a setup that I really liked and maked an example in CodePen: <https://codepen.io/anon/pen/XGxEaj>. A user can click in a grid to point out the location. In the console log I see the dat... | 2019/03/23 | [
"https://Stackoverflow.com/questions/55318862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9606978/"
] | This can be achieved by converting your JS object into JSON:
```
var json = JSON.stringify(myJsObj);
```
And then converting your Python object to JSON:
```
import json
myPythonObj = json.loads(json)
```
More information about the JSON package for Python can be found [here](https://www.w3schools.com/python/python... | You should use the python [json](https://docs.python.org/3/library/json.html) module.
Here is how you can perform such operation using the module.
```
import json
json_data = '{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}'
loaded_json = json.loads(json_data)
``` | 13,819 |
66,602,656 | I am following the instruction (<https://github.com/huggingface/transfer-learning-conv-ai>) to install conv-ai from huggingface, but I got stuck on the docker build step: `docker build -t convai .`
I am using Mac 10.15, python 3.8, increased Docker memory to 4G.
I have tried the following ways to solve the issue:
1.... | 2021/03/12 | [
"https://Stackoverflow.com/questions/66602656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11210924/"
] | It seems that pip does not install the pre-built wheel, but instead tries to build *spacy* from source. This is a fragile process and requires extra dependencies.
To avoid this, you should ensure that the Python packages *pip*, *wheel* and *setuptools* are up to date before proceeding with the installation.
```
# rep... | Did you try adding numpy into the requirements.txt? It looks to me that it is missing. | 13,820 |
47,186,849 | Given an iterable consisting of a finite set of elements:
>
> (a, b, c, d)
>
>
>
as an example
What would be a Pythonic way to generate the following (pseudo) ordered pair from the above iterable:
```
ab
ac
ad
bc
bd
cd
```
A trivial way would be to use for loops, but I'm wondering if there is a pythonic way ... | 2017/11/08 | [
"https://Stackoverflow.com/questions/47186849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/962891/"
] | Try using [combinations](https://docs.python.org/2/library/itertools.html#itertools.combinations).
```
import itertools
combinations = itertools.combinations('abcd', n)
```
will give you an iterator, you can loop over it or convert it into a list with `list(combinations)`
In order to only include pairs as in your e... | You can accomplish this in a list comprehension.
```
data = [1, 2, 3, 4]
output = [(data[n], next) for n in range(0,len(data)) for next in data[n:]]
print(repr(output))
```
Pulling the comprehension apart, it's making a tuple of the first member of the iterable and the first object in a list composed of all other ... | 13,821 |
54,551,016 | I am trying to use cloud SQL / mysql instance for my APPEngine account. The app is an python django-2.1.5 appengine app. I have created an instance of MYSQL in the google cloud.
I have added the following in my app.yaml file copied from the SQL instance details:
```
beta_settings:
cloud_sql_instances: <INSTANCE_CO... | 2019/02/06 | [
"https://Stackoverflow.com/questions/54551016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204942/"
] | App Engine doesn't have any guarantees regarding IP address of a particular instance, and may change at any time. Since it is a Serverless platform, it abstracts away the infrastructure to allow you to focus on your app.
There are two options when using App Engine Flex: Unix domain socket and TCP port. Which one App ... | I've encountered this issue before and after hours of scratching my head, all I needed to do was enable "Cloud SQL Admin API" and the deployed site connected to the database. This also sets permissions on your GAE service account for cloud proxy to connect to your GAE service. | 13,823 |
60,765,225 | right now i use
```
foo()
import pdb; pdb.set_trace()
bar()
```
for debugging purposes. Its a tad cumbersome, is there a better way to implement a breakpoint in python?
edit: i understand there are IDE's that are useful, but i want to do this programatically, furthermore all the documentation i can find is for... | 2020/03/19 | [
"https://Stackoverflow.com/questions/60765225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11898750/"
] | Personally I prefer to use my editor for debugging. I can visually set break points and use keyboard shortcuts to step through my code and evaluate variables and expressions. Visual Studio Code, Eclipse and PyCharm are all popular choices.
If you insist on using the command line, you can use the interactive debugger.... | Python 3.7 added a [breakpoint() function](https://docs.python.org/3/library/functions.html#breakpoint) that, by default, performs the same job without the explicit import (to keep it lower overhead). It's [quite configurable](https://docs.python.org/3/whatsnew/3.7.html#whatsnew37-pep553) though, so you can have it do ... | 13,824 |
50,885,291 | Trying to upgrade pip in my terminal. Here's my code:
```
(env) macbook-pro83:zappatest zorgan$ pip install --upgrade pip
Could not fetch URL https://pypi.python.org/simple/pip/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:645) - skipping... | 2018/06/16 | [
"https://Stackoverflow.com/questions/50885291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6733153/"
] | a. Check your system date and time and see whether it is correct.
b. If the 1st solution doesn't fix it try using a lower security method:
```
pip install --index-url=http://pypi.python.org/simple/linkchecker
```
This bypasses HTTPS and uses HTTP instead, try this workaround only if you are in a hurry.
c. Try down... | You can get more details about upgrade failed by using
`$ pip install --upgrade pip -vvv`
there will be more details help you debug it.
---
Try
`pip --trusted-host pypi.python.org install --upgrade pip`
Maybe useful.
---
Another solution:
`$ pip install certifi`
then run install. | 13,825 |
1,195,494 | Was wondering how you'd do the following in Windows:
From a c shell script (extension csh), I'm running a Python script within an 'eval' method so that the output from the script affects the shell environment. Looks like this:
```
eval `python -c "import sys; run_my_code_here(); "`
```
Was wondering how I would do ... | 2009/07/28 | [
"https://Stackoverflow.com/questions/1195494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101126/"
] | If it's in `cmd.exe`, using a temporary file is the only option [that I know of]:
```
python -c "print(\"Hi\")" > temp.cmd
call temp.cmd
del temp.cmd
``` | (Making some guesses where details are missing from your question)
In CMD, when a batch script modifies the environment, the default behavior is that it modifies the environment of the CMD process that is executing it.
Now, if you have a batch script that calls another batch script, there are 3 ways to do it.
1. ex... | 13,828 |
36,510,859 | I'm trying to use the CVXOPT qp solver to compute the Lagrange Multipliers for a Support Vector Machine
```
def svm(X, Y, c):
m = len(X)
P = matrix(np.dot(Y, Y.T) * np.dot(X, X.T))
q = matrix(np.ones(m) * -1)
g1 = np.asarray(np.diag(np.ones(m) * -1))
g2 = np.asarray(np.diag(np.ones(m)))
... | 2016/04/08 | [
"https://Stackoverflow.com/questions/36510859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681410/"
] | Your matrix elements have to be of the floating-point type as well. So the error is removed by using `A = A.astype('float')` to cast it. | The error - `"TypeError: 'A' must be a 'd' matrix with 1000 columns:"` has two condition namely:
1. if the type code is not equal to '`d`'
2. if the `A.size[1] != c.size[0]`.
Check for these conditions. | 13,829 |
51,940,568 | I'm trying to learn Python with [CS Dojo's tutorial](https://www.youtube.com/watch?v=NSbOtYzIQI0). I'm currently working on the task he gave us, which was building a "miles to kilometers converter". The task itself was very simple, but I want to build a program that does a little more than that. I want the output to be... | 2018/08/21 | [
"https://Stackoverflow.com/questions/51940568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10252435/"
] | The value **d** needs to be converted into a string before it can be concatenated with the rest of the return statement:
```
d = str(distance * 1.6)
``` | In Python 3.6+, f-string saves your time typing ugly quotes and plus signs and improves the readability a lot.
```
return f"The distance {name} is {d} in kilometers."
```
You can also do formatting easily inside f-strings
```
return f"The distance {name.title()} is {d:.2f} in kilometers."
``` | 13,834 |
9,885,071 | I am reading a text file which I guess is encoded in utf-8. Some lines can only be decoded as latin-1 though. I would say this is very bad practice, but nevertheless I have to cope with it.
I have the following questions:
First: how can I "guess" the encoding of a file? I have tried `enca`, but in my machine:
```
en... | 2012/03/27 | [
"https://Stackoverflow.com/questions/9885071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647991/"
] | 1. Guess the text encoding a file - in what? Python, Perl, Java, C? Note that this sometimes produces unexpected results (e.g. [the "bush hid the facts" bug](http://en.wikipedia.org/wiki/Bush_hid_the_facts))
2. Sometimes a file will have text encoded in different encodings. Either the file format specifies different en... | When you say "partially encoded in different encodings", are you sure it's not just UTF-8? UTF-8 mixes single-byte, 2-byte and more-byte encodings, depending on the complexity of the character, so part of it looks like ASCII / latin-1 and part of it looks like Unicode.
<http://www.joelonsoftware.com/articles/Unicode.h... | 13,835 |
70,463,263 | I am not able to serialize a custom object in python 3 .
Below is the explanation and code
```
packages= []
data = {
"simplefield": "value1",
"complexfield": packages,
}
```
where packages is a list of `custom object Library`.
`Library object` is a class as below (I have also sub-classed `json.JSONEncoder` b... | 2021/12/23 | [
"https://Stackoverflow.com/questions/70463263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1281182/"
] | Inheriting `json.JSONEncoder` will not make a class serializable. You should define your encoder separately and then provide the encoder instance in the `json.dumps` call.
See an example approach below
```
import json
from typing import Any
class Library:
def __init__(self, name):
print("calling Library ... | You can use the `default` parameter of `json.dump`:
```
def default(obj):
if isinstance(obj, Library):
return {"name": obj.name}
raise TypeError(f"Can't serialize {obj!r}.")
json.dumps(data, default=default)
``` | 13,836 |
57,584,229 | I tried the following python code to assign a new value to a list.
```
a,b,c=[],[],[]
def change():
return [1]
for i in [a,b,c]:
i=change()
print(a)
```
The output is `[]`, but what I need is `[1]` | 2019/08/21 | [
"https://Stackoverflow.com/questions/57584229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4917205/"
] | What you're doing here is you're re-assigning the variable `i` within the loop, but you're not actually changing `a`, `b`, or `c`.
As an example, what would you expect the following source code to output?
```py
a = []
i = a
i = [1]
print(a)
```
Here, you are reassigning `i` after you've assigned `a` to it. `a` its... | You created a variable called i, to it you assigned (in turn) a, then 1, then b, then 1, then c, then 1. Then you printed a, unaltered. If you want to change a, you need to assign to a. That is:
```
a = [1]
``` | 13,837 |
38,193,878 | I am trying to automate my project create process and would like as part of it to create a new jupyter notebook and populate it with some cells and content that I usually have in every notebook (i.e., imports, titles, etc.)
Is it possible to do this via python? | 2016/07/05 | [
"https://Stackoverflow.com/questions/38193878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5983171/"
] | You can do it using **nbformat**. Below an example taken from [Creating an IPython Notebook programatically](https://gist.github.com/fperez/9716279):
```py
import nbformat as nbf
nb = nbf.v4.new_notebook()
text = """\
# My first automatic Jupyter Notebook
This is an auto-generated notebook."""
code = """\
%pylab inl... | This is absolutely possible. Notebooks are just json files. This
[notebook](https://gist.github.com/anonymous/1c79fa2d43f656b4463d7ce7e2d1a03b "notebook") for example is just:
```
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Header 1"
]
},
{
"cell_type": "code",
"... | 13,846 |
55,411,549 | **EDIT:** I am trying to manipulate JSON files in Python. In my data some polygons have multiple related information: coordinates (`LineString`) and **area percent** and **area** (`Text` and `Area` in `Point`), I want to combine them to a single JSON object. As an example, the data from files are as follows:
```
data ... | 2019/03/29 | [
"https://Stackoverflow.com/questions/55411549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8410477/"
] | Can you try the following:
```
>>> df = pd.DataFrame([[1, 2, 4], [4, 5, 6], [7, '[8', 9]])
>>> df = df.astype('str')
>>> df
0 1 2
0 1 2 4
1 4 5 6
2 7 [8 9
>>> df[df.columns[[df[i].str.contains('[', regex=False).any() for i in df.columns]]]
1
0 2
1 5
2 [8
>>>
``` | Use this:
```
s=df.applymap(lambda x: '[' in x).any()
print(df[s[s].index])
```
Output:
```
col2 col4
0 b [d
1 [f h
2 j l
3 n [pa
``` | 13,847 |
62,461,130 | I am trying to update a Lex bot using the python SDK put\_bot function. I need to pass a checksum value of the function as specified [here](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lex-models.html#LexModelBuildingService.Client.put_bot). How do I get this value?
So far I have tried usi... | 2020/06/18 | [
"https://Stackoverflow.com/questions/62461130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13765073/"
] | The issue here seems to be that in the first example you got one `div` with multiple components in it:
```
<div id="controls">
<NavControl />
<NavControl />
<NavControl />
</div>
```
The problem is that in the second example you are creating multiple `div` elements with the same id and each of them have nes... | I am unsure of the actual desired scope, so I will go over both.
If we want multiple `controls` in the template, as laid out, switch `id="controls"` to `class="controls"`:
```
<template>
<div id="navControlPanel">
<div class="controls" v-bind:key="control.id" v-for="control in controls">
<NavC... | 13,851 |
24,245,324 | Something about the `id` of objects of type `str` (in python 2.7) puzzles me. The `str` type is immutable, so I would expect that once it is created, it will always have the same `id`. I believe I don't phrase myself so well, so instead I'll post an example of input and output sequence.
```
>>> id('so')
14061415512388... | 2014/06/16 | [
"https://Stackoverflow.com/questions/24245324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1565828/"
] | This behavior is specific to the Python interactive shell. If I put the following in a .py file:
```
print id('so')
print id('so')
print id('so')
```
and execute it, I receive the following output:
```
2888960
2888960
2888960
```
In CPython, a string literal is treated as a constant, which we can see in the byte... | In your first example a new instance of the string `'so'` is created each time, hence different id.
In the second example you are binding the string to a variable and Python can then maintain a shared copy of the string. | 13,852 |
7,927,904 | How do I close a file in python after opening it this way:
`line = open("file.txt", "r").readlines()[7]` | 2011/10/28 | [
"https://Stackoverflow.com/questions/7927904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/442852/"
] | Best to use a context manager. This will close the file automatically at the end of the block and doesn't rely on implementation details of the garbarge collection
```
with open("file.txt", "r") as f:
line = f.readlines()[7]
``` | There are several ways, e.g you could just use `f = open(...)` and `del f`.
If your Python version supports it you can also use the `with` statement:
```
with open("file.txt", "r") as f:
line = f.readlines()[7]
```
This automatically closes your file.
**EDIT:** I don't get why I'm downvoted for explaining how ... | 13,861 |
37,582,199 | How I can pass the data from object oriented programming to mysql in python? Do I need to make connection in every class?
Update:
This is my object orinted
```
class AttentionDataPoint(DataPoint):
def __init__ (self, _dataValueBytes):
DataPoint._init_(self, _dataValueBytes)
self.attentionValue=se... | 2016/06/02 | [
"https://Stackoverflow.com/questions/37582199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6341585/"
] | You asked a [similar question](https://stackoverflow.com/questions/37575008/adding-sheet2-to-existing-excelfile-from-data-of-sheet1-with-pandas-python) on adding data to a second excel sheet. Perhaps you can address there any issues around the `to_excel()` part.
On the category count, you can do:
```
df.Manufacturer.... | As answered by [Stefan](https://stackoverflow.com/users/1494637/stefan), using `value_counts()` over the designated column would do.
Since you are saving multiple DataFrames to a single workbook, I'd use `pandas.ExcelWriter`:
```
import pandas as pd
writer = pd.ExcelWriter('file_name.xlsx')
df.to_excel(writer) # ... | 13,862 |
4,870,393 | We have a gazillion spatial coordinates (x, y and z) representing atoms in 3d space, and I'm constructing a function that will translate these points to a new coordinate system. Shifting the coordinates to an arbitrary origin is simple, but I can't wrap my head around the next step: 3d point rotation calculations. In o... | 2011/02/02 | [
"https://Stackoverflow.com/questions/4870393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572043/"
] | Using quaternions to represent rotation isn't difficult from an algebraic point of view. Personally, I find it hard to reason *visually* about quaternions, but the formulas involved in using them for rotations are not overly complicated. I'll provide a basic set of reference functions here.1 (See also this lovely answe... | Note that the inversion of matrix is not that trivial at all! Firstly, all n (where n is the dimension of your space) points must be in general position (i.e. no individual point can be expressed as a linear combination of rest of the points [caveat: this may seem to be a simple requirement indeed, but in the realm of ... | 13,863 |
6,931,112 | I was wondering how the random number functions work. I mean is the server time used or which other methods are used to generate random numbers? Are they really random numbers or do they lean to a certain pattern? Let's say in python:
```
import random
number = random.randint(1,10)
``` | 2011/08/03 | [
"https://Stackoverflow.com/questions/6931112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366121/"
] | Try:
```
links.parent().addClass('current')
.closest('li').addClass('current');
```
[jQuery Docs](http://api.jquery.com/parent/) | Use the `.parent()` api to do it
[Docs](http://api.jquery.com/parent/)
**EDIT**
Something like this:
```
$(this).parent().parent().addClass("current")
``` | 13,866 |
457,207 | I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size.
After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a p... | 2009/01/19 | [
"https://Stackoverflow.com/questions/457207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367099/"
] | Use this to get the dimension of pdf
```
from PyPDF2 import PdfWriter, PdfReader, PdfMerger
reader = PdfReader("/Users/user.name/Downloads/sample.pdf")
page = reader.pages[0]
print(page.cropbox.lower_left)
print(page.cropbox.lower_right)
print(page.cropbox.upper_left)
print(page.cropbox.upper_right)
```
After this ... | Acrobat Javascript API has a setPageBoxes method, but Adobe doesn't provide any Python code samples. Only C++, C# and VB. | 13,868 |
16,128,572 | I have number of molecules in smiles format and I want to get molecular name from smiles format of molecule and I want to use python for that conversion.
for example :
```
CN1CCC[C@H]1c2cccnc2 - Nicotine
OCCc1c(C)[n+](=cs1)Cc2cnc(C)nc(N)2 - Thiamin
```
which python module will help me in doing such conversions?... | 2013/04/21 | [
"https://Stackoverflow.com/questions/16128572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/778942/"
] | I don't know of any one module that will let you do this, I had to play at data wrangler to try to get a satisfactory answer.
I tackled this using Wikipedia which is being used more and more for structured bioinformatics / chemoinformatics data, but as it turned out my program reveals that a lot of that data is incorr... | Reference: [NCI/CADD](https://cactus.nci.nih.gov/chemical/structure)
from urllib.request import urlopen
```
def CIRconvert(smi):
try:
url ="https://cactus.nci.nih.gov/chemical/structure/" + smi+"/iupac_name"
ans = urlopen(url).read().decode('utf8')
return ans
except:
return 'N... | 13,878 |
68,236,416 | I am trying to install django using pipenv but failing to do so.
```
pipenv install django
Creating a virtualenv for this project...
Pipfile: /home/djangoTry/Pipfile
Using /usr/bin/python3.9 (3.9.5) to create virtualenv...
⠴ Creating virtual environment...RuntimeError: failed to query /usr/bin/python3.9 with code 1 e... | 2021/07/03 | [
"https://Stackoverflow.com/questions/68236416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16091170/"
] | The problem isn't with installing Django, is on creating your venv, I don't create on this way so I will pass the way that i create
Step 1 - Install pip
Step 2 - Install virtaulEnv
[check here how to install both](https://gist.github.com/Geoyi/d9fab4f609e9f75941946be45000632b)
after installed, `run python3 -m venv ... | Try pipenv install --python 3.9 | 13,882 |
72,664,661 | I’m new to python and trying to get a loop working. I’m trying to iterate through a dataframe – for each unique value in the “Acct” column I want to create a csv file, with the account name. So there should be an Account1.csv, Account2.csv and Account3.csv created.
When I run this code, only Account3.csv is being crea... | 2022/06/17 | [
"https://Stackoverflow.com/questions/72664661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19361388/"
] | you need to use a `TextInput` component to handle this kind of event. You can find the API here: <https://reactnative.dev/docs/textinput>.
Bear in mind that react library is built as an API so it can take advantage of different renders. But the issue is that when using the mobile native renderer you will not have the ... | First, you add `onKeyDown={keyDownHandler}` to a React element. This will trigger your `keyDownHandler` function each time a key is pressed. Ex:
```
<div className='example-class' onKeyDown={keyDownHandler}>
```
You can set up your function like this:
```
const keyDownHandler = (
event: React.KeyboardEvent<HTML... | 13,883 |
43,536,182 | i am having on HDFS this huge file which is an extract of my db. e.g.:
```
1||||||1||||||||||||||0002||01||1999-06-01 16:18:38||||2999-12-31 00:00:00||||||||||||||||||||||||||||||||||||||||||||||||||||||||2||||0||W.ISHIHARA||||1999-06-01 16:18:38||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||19155||... | 2017/04/21 | [
"https://Stackoverflow.com/questions/43536182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5013752/"
] | I found the databrick csv reader quite useful to do that.
```
toProcessFileDF_raw = sqlContext.read.format('com.databricks.spark.csv')\
.options(header='false',
inferschema='false',
... | Logs would have been helpful.
`binaryFiles` will read this as binary file from HDFS as a single record and returned in a key-value pair, where the key is the path of each file, the value is the content of each file.
Note from Spark documentation: Small files are preferred, large file is also allowable, but may cause ... | 13,888 |
60,054,247 | I have a python list of list that I would like to insert into a MySQL database.
The list looks like this:
```
[[column_name_1,value_1],[column_name_2, value_2],.......]
```
I want to insert this into the database table which has column names as `column_name_1, column_name_2.....`
so that the database table looks li... | 2020/02/04 | [
"https://Stackoverflow.com/questions/60054247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12675531/"
] | You have several options.
```
working_directory=$PWD
python3.8 main.py "$working_directory"
```
This will pass the value of your variable as a command line argument. In Python you will use `sys.argv[1]` to access it.
```
export working_directory=$PWD
python3.8 main.py
```
This will add an environment variable usi... | You can use the `pathlib` library to avoid putting it as a parameter:
```
import pathlib
working_derictory = pathlib.Path().absolute()
``` | 13,889 |
7,521,623 | I am trying to parse HTML with BeautifulSoup.
The content I want is like this:
```
<a class="yil-biz-ttl" id="yil_biz_ttl-2" href="http://some-web-url/" title="some title">Title</a>
```
i tried and got the following error:
```
maxx = soup.findAll("href", {"class: "yil-biz-ttl"})
---------------------------------... | 2011/09/22 | [
"https://Stackoverflow.com/questions/7521623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/648866/"
] | You're missing a close-quote after `"class`:
```
maxx = soup.findAll("href", {"class: "yil-biz-ttl"})
```
should be
```
maxx = soup.findAll("href", {"class": "yil-biz-ttl"})
```
also, I don't think you can search for an attribute like `href` like that, I think you need to search for a tag:
```
maxx = [link['h... | Well first of all you have a syntax error. You have your quotes wrong in `class` part.
Try:
`maxx = soup.findAll("href", {"class": "yil-biz-ttl"})` | 13,890 |
4,302,201 | I'll give a simplified example here. Suppose I have an iterator in python, and each object that this iterator returns is itself iterable. I want to take all the objects returned by this iterator and chain them together into one long iterator. Is there a standard utility to make this possible?
Here is a contrived examp... | 2010/11/29 | [
"https://Stackoverflow.com/questions/4302201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125921/"
] | You can use [`itertools.chain.from_iterable`](http://docs.python.org/library/itertools.html#itertools.chain.from_iterable)
```
>>> import itertools
>>> x = iter([ xrange(0,5), xrange(5,10)])
>>> a = itertools.chain.from_iterable(x)
>>> list(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
If that's not available on your versio... | Here's the old-fashioned way:
```
Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import generators
>>> def mychain(iterables):
... for it in iterables:
... for item in it:
... yie... | 13,895 |
22,385,108 | On the `operator` module, we have the `or_` function, [which is the bitwise or](http://docs.python.org/2/library/operator.html#operator.or_) (`|`).
However I can't seem to find the logical or (`or`).
The documentation [doesn't seem to list it](http://docs.python.org/2/library/operator.html#mapping-operators-to-functi... | 2014/03/13 | [
"https://Stackoverflow.com/questions/22385108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1595865/"
] | The `or` operator *short circuits*; the right-hand expression is not evaluated when the left-hand returns a true value. This applies to the `and` operator as well; when the left-hand side expression returns a false value, the right-hand expression is not evaluated.
You could not do this with a function; all operands *... | The reason you are getting `1` after executing `>>> 1 or 2` is because `1` is `true` so the expression has been satisfied.
It might make more sense if you try executing `>>> 0 or 2`. It will return `2` because the first statement is `0` or `false` so the second statement gets evaluated. In this case `2` evaluates to ... | 13,896 |
12,866,612 | I need to get distribute version 0.6.28 running on Heroku. I updated my requirements.txt, but that seems to have no effect.
I'm trying to install from a module from a tarball that required this later version of the distribute package.
During deploy I only get this:
```
Running setup.py egg_info for package from... | 2012/10/12 | [
"https://Stackoverflow.com/questions/12866612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/591222/"
] | Ok, here's a solution that does work for the moment. Long-term fix I think is Heroku upgrading their version of distribute.
1. Fork the python buildpack: <https://github.com/heroku/heroku-buildpack-python/>
2. Add the requirements you need to the pack (I put them in bin/compile, just before the other pip install requi... | Try adding distribute with the specific version to your dependencies on a first push, then adding the required dependency.
```
cat requirements.txt
...
distribute==0.6.28
...
git push heroku master
...
cat requirements.txt
...
your deps here
``` | 13,902 |
37,192,957 | I have a numpy and a boolean array:
```
nparray = [ 12.66 12.75 12.01 13.51 13.67 ]
bool = [ True False False True True ]
```
I would like to replace all the values in `nparray` by the same value divided by 3 where `bool` is False.
I am a student, and I'm reasonably new to python indexing. Any advice or suggest... | 2016/05/12 | [
"https://Stackoverflow.com/questions/37192957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6141885/"
] | naming an array bool might not be the best idea. As ayhan did try renaming it to bl or something else.
You can use numpy.where see the docs [here](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html)
```
nparray2 = np.where(bl == False, nparray/3, nparray)
``` | Use [`boolean indexing`](http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#boolean-or-mask-index-arrays) with `~` as the negation operator:
```
arr = np.array([12.66, 12.75, 12.01, 13.51, 13.67 ])
bl = np.array([True, False, False, True ,True])
arr[~bl] = arr[~bl] / 3
array([ 12.66 , 4.25 ,... | 13,903 |
38,638,180 | Running interpreter
```
>>> x = 5000
>>> y = 5000
>>> print(x is y)
False
```
running the same in script using `python test.py` returns `True`
What the heck? | 2016/07/28 | [
"https://Stackoverflow.com/questions/38638180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3337819/"
] | You need to use the [EnhancedPatternLayout](https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/EnhancedPatternLayout.html) then you can use the `{GMT+0}` specifier as per documentation.
If you instead you want to run your application in UTC timezone, you can add the following JVM parameter :
```
-Duser.ti... | ```
log4j.appender.A1.layout=org.apache.log4j.EnhancedPatternLayout
log4j.appender.A1.layout.ConversionPattern=[%d{ISO8601}{GMT}] %-4r [%t] %-5p %c %x - %m%n
``` | 13,906 |
64,926,963 | I used the official docker image of flask. And installed the rpi.gpio library in the container
```
pip install rpi.gpio
```
It's succeeded:
```
root@e31ba5814e51:/app# pip install rpi.gpio
Collecting rpi.gpio
Downloading RPi.GPIO-0.7.0.tar.gz (30 kB)
Building wheels for collected packages: rpi.gpio
Building whe... | 2020/11/20 | [
"https://Stackoverflow.com/questions/64926963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12192583/"
] | You need to close the second file. You were missing the () at the end of `f2.close` so the close method actually won't have been executed.
In the example below, I am using `with` which creates a context manager to automatically close the file.
```
with open('BestillingNr.txt', 'r') as f:
bestillingNr = int(f.read... | after this line `f2.write(f'{str(bestillingNr)}')`, you should add flush command `f2.flush()`
This code is work well:
```
f = open('BestillingNr.txt', 'r')
bestillingNr = int(f.read())
f.close()
bestillingNr += 1
f2 = open('BestillingNr.txt', 'w')
f2.write(f'{str(bestillingNr)}')
f2.flush()
f2.close()
``` | 13,907 |
10,505,851 | I have a complex class and I want to simplify it by implementing a facade class (assume I have no control on complex class). My problem is that complex class has many methods and I will just simplify some of them and rest of the will stay as they are. What I mean by "simplify" is explained below.
I want to find a way ... | 2012/05/08 | [
"https://Stackoverflow.com/questions/10505851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/932278/"
] | It's called Inheritence. Consider the following code:
```
class Complex {
public function complex() { /* Complex Function */ }
public function simple() { /* Already simple function */ }
}
class SimplifiedComplex extends Complex {
public function complex() { /* Simplify Here */ }
}
```
The `simple()` met... | Depending on your use case, you might want to create a facade in front of some of the functionality in complex class by delegating (Option 1), and instead of providing support for the rest of the functionality in complex class, you provide means to access complex class directly (getComplexClass).
This might make the d... | 13,908 |
26,747,308 | I have a Python script, say `myscript.py`, that uses relative module imports, ie `from .. import module1`, where my project layout is as follows:
```
project
+ outer_module
- __init__.py
- module1.py
+ inner_module
- __init__.py
- myscript.py
- myscript.sh
```
And I have a Bash script, say `... | 2014/11/04 | [
"https://Stackoverflow.com/questions/26747308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1884158/"
] | You want to create a custom filter. It can be done very easily. This filter will test the name of your friend against the search. If
```
app.filter('filterFriends', function() {
return function(friends, search) {
if (search === "") return friends;
return friends.filter(function(friend) {
... | I think it would be easier to just do:
```
<tr ng-repeat="friend in friends" ng-show="([friend] | filter:search).length > 0">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
```
Also this way the filter will apply to all the properties, not just name. | 13,912 |
55,374,909 | I am new in python so I'm trying to read a csv with 700 lines included a header, and get a list with the unique values of the first csv column.
Sample CSV:
```
SKU;PRICE;SUPPLIER
X100;100;ABC
X100;120;ADD
X101;110;ABV
X102;100;ABC
X102;105;ABV
X100;119;ABG
```
I used the example here
[How to create a list in Pyt... | 2019/03/27 | [
"https://Stackoverflow.com/questions/55374909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | A solution using pandas. You'll need to call the `unique` method on the correct column, this will return a pandas series with the unique values in that column, then convert it to a list using the `tolist` method.
An example on the `SKU` column below.
```
import pandas as pd
df = pd.read_csv('final_csv.csv', sep=";... | A solution using neither `pandas` nor `csv` :
```py
lines = open('file.csv', 'r').read().splitlines()[1:]
col0 = [v.split(';')[0] for v in lines]
uniques = filter(lambda x: col0.count(x) == 1, col0)
```
or, using `map` (but less readable) :
```py
col0 = list(map(lambda line: line.split(';')[0], open('file.csv', ... | 13,913 |
42,854,598 | If I reset the index of my pandas DataFrame with "inplace=True" (following [the documentation](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html)) it returns a class 'NoneType'. If I reset the index with "inplace=False" it returns the DataFrame with the new index. Why?
```
print(typ... | 2017/03/17 | [
"https://Stackoverflow.com/questions/42854598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6421290/"
] | Ok, now I understand, thanks for the comments!
So inplace=True should return None **and** make the change in the original object. It seemed that on listing the dataframe again, no changes were present.
But of course I should not have **assigned the return value** to the dataframe, i.e.
```
testDataframe = testDatafr... | inplace=True is always changed in the original data\_frame. If you want a changed data\_frame then remove second parameter i.e `inplace = True`
```
new_data_frame = testDataframe.set_index(['Codering'])
```
Then
```
print(new_data_frame)
``` | 13,915 |
32,303,006 | I need to compute the integral of the following function within ranges that start as low as `-150`:
```
import numpy as np
from scipy.special import ndtr
def my_func(x):
return np.exp(x ** 2) * 2 * ndtr(x * np.sqrt(2))
```
The problem is that this part of the function
```
np.exp(x ** 2)
```
tends toward infi... | 2015/08/31 | [
"https://Stackoverflow.com/questions/32303006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2623899/"
] | I think a combination of @askewchan's solution and [`scipy.special.log_ndtr`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.log_ndtr.html) will do the trick:
```
from scipy.special import log_ndtr
_log2 = np.log(2)
_sqrt2 = np.sqrt(2)
def my_func(x):
return np.exp(x ** 2) * 2 * ndtr(x * np.sq... | Not sure how helpful will this be, but here are a couple of thoughts that are too long for a comment.
You need to calculate the integral of [](https://i.stack.imgur.com/Tt5t4.gif), which you [correctly identified](http://docs.scipy.org/doc/scipy... | 13,916 |
46,409,846 | I am trying to implement `Kmeans` algorithm in python which will use `cosine distance` instead of euclidean distance as distance metric.
I understand that using different distance function can be fatal and should done carefully. Using cosine distance as metric forces me to change the average function (the average in... | 2017/09/25 | [
"https://Stackoverflow.com/questions/46409846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8671126/"
] | So it turns out you can just normalise X to be of unit length and use K-means as normal. The reason being if X1 and X2 are unit vectors, looking at the following equation, the term inside the brackets in the last line is cosine distance.
[](https://i.stack.imgur.com/7amC... | Unfortunately no.
Sklearn current implementation of k-means only uses Euclidean distances.
The reason is K-means includes calculation to find the cluster center and assign a sample to the closest center, and Euclidean only have the meaning of the center among samples.
If you want to use K-means with cosine distance... | 13,918 |
73,326,374 | I want to solve NP-hard combinatorial optimization problem using quantum optimization.In this regard, I am using "classiq" python library, which a high level API for making hardware compatible quantum circuits, with IBMQ backend.
To use "classiq", you have to first do the authentication of your machine (according to t... | 2022/08/11 | [
"https://Stackoverflow.com/questions/73326374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17990100/"
] | Prepared statement escaped the parameters:
```java
private final String insertSQL = "INSERT INTO demo2 (contract_nr, name, surname, address, tel, date_of_birth, license_nr, nationality, driver1, driver2, pickup_date, drop_date, renting_days, pickup_time, drop_time, price, included_km, effected_km, mail, type, valid, c... | The answer to this question is that we do not need `'` around `?` in insert sql.
This is wrong:
```
private final String insertSQL = "INSERT INTO demo2 (contract_nr, name, surname, address, tel, date_of_birth, license_nr, nationality, driver1, driver2, pickup_date, drop_date, renting_days, pickup_time, drop_time, pri... | 13,921 |
63,532,068 | I have my python3 path under `/usr/bin`, any my pip path under `/.local/bin` of my local repository.
With some pip modules installed, I can run my code successfully through `python3 mycode.py`.
But I tried to run the shell script:
```
#!/usr/bin
echo "starting now..."
nohup python3 mycode.py > log.txt 2>&1 &
echo $! ... | 2020/08/22 | [
"https://Stackoverflow.com/questions/63532068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9207332/"
] | Just use:
```
msgbox Range("B1:B19").SpecialCells(xlCellTypeBlanks).Address
``` | This solution adapts your code.
```
Dim cell As Range
Dim emptyStr As String
emptyStr = ""
For Each cell In Range("B1:B19")
If IsEmpty(cell) Then _
emptyStr = emptyStr & cell.Address(0, 0) & ", "
Next cell
If emptyStr <> "" Then MsgBox Left(emptyStr, Len(emptyStr) - 2)
```
If the `cell` is empty, it st... | 13,922 |
52,302,767 | In my pc, how can i listen incoming connection as a DLNA server?
On my TV there is the possibility for get media from a DLNA server, i would write a simple python script that grant access at TV to my files.
The ends are:
* LG webOS smartTV
* macOS | 2018/09/12 | [
"https://Stackoverflow.com/questions/52302767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8954551/"
] | One project I've found is Cohen3. Does not look as too much alive, but at least supports Python version 3: <https://github.com/opacam/Cohen3>
There's also a Coherence project (it seems Cohen3 is somehow derived from it, not sure): <https://gitlab.digitalcourage.de/coherence> | There is already server app doing it [Serviio](http://serviio.org/) I already using this on windows 10 and raspberry pi 2 and 3 and it works well, easy to setup by web app and you'll save a time with making your own solution. | 13,926 |
10,496,649 | Continued from [How to use wxSpellCheckerDialog in Django?](https://stackoverflow.com/questions/10474971/how-to-use-wxspellcheckerdialog-python-django/10476811#comment13562681_10476811)
I have added spell checking to Django application using pyenchant.
It works correctly when first run. But when I call it again (or a... | 2012/05/08 | [
"https://Stackoverflow.com/questions/10496649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1110394/"
] | You don't need wxPython to use pyEnchant. And you certainly shouldn't be using wx stuff with django. wxPython is for desktop GUIs, while django is a web app framework. As "uhz" pointed out, you can't call wxPython methods outside the main thread that wxPython runs in unless you use its threadsafe methods, such as wx.Ca... | It seems you are trying to use wx controls from inside Django code, is that correct? If so you are doing a very weird thing :)
When you write a GUI application with wxPython there is one main thread which can process Window messages - the main thread is defined as the one where wx.App was created. You are trying to do... | 13,927 |
55,585,079 | I tried running this code in TensorFlow 2.0 (alpha):
```py
import tensorflow_hub as hub
@tf.function
def elmo(texts):
elmo_module = hub.Module("https://tfhub.dev/google/elmo/2", trainable=True)
return elmo_module(texts, signature="default", as_dict=True)
embeds = elmo(tf.constant(["the cat is on the mat",
... | 2019/04/09 | [
"https://Stackoverflow.com/questions/55585079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38626/"
] | In Tensorflow 2.0 you should be using `hub.load()` or `hub.KerasLayer()`.
**[April 2019]** - For now only Tensorflow 2.0 modules are loadable via them. In the future many of 1.x Hub modules should be loadable as well.
For the 2.x only modules you can see examples in the notebooks created for the modules [here](https:... | this function load will work with tensorflow 2
```
embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder-large/3")
```
instead of
```
embed = hub.Module("https://tfhub.dev/google/universal-sentence-encoder-large/3")
```
[this is not accepted in tf2]
use hub.load() | 13,928 |
16,138,090 | What is the most efficient and portable way to generate a random random in `[0,1]` in Cython? One approach is to use `INT_MAX` and `rand()` from the C library:
```
from libc.stdlib cimport rand
cdef extern from "limits.h":
int INT_MAX
cdef float randnum = rand() / float(INT_MAX)
```
Is it OK to use `INT_MAX` in ... | 2013/04/22 | [
"https://Stackoverflow.com/questions/16138090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The C standard says `rand` returns an `int` in the range 0 to RAND\_MAX inclusive, so dividing it by RAND\_MAX (from `stdlib.h`) is the proper way to normalise it. In practice, RAND\_MAX will almost always be equal to MAX\_INT, but don't rely on that.
Because `rand` has been part of ISO C since C89, it's guaranteed to... | 'c' stdlib rand() returns a number between 0 and RAND\_MAX which is generally 32767.
Is there any reason not to use the python random() ?
[Generate random integers between 0 and 9](https://stackoverflow.com/questions/3996904/python-generate-random-integers-between-0-and-9) | 13,930 |
52,397,563 | I've been pulling my hair out trying to figure this one out, hoping someone else has already encountered this and knows how to solve it :)
I'm trying to build a very simple Flask endpoint that just needs to call a long running, blocking `php` script (think `while true {...}`). I've tried a few different methods to asy... | 2018/09/19 | [
"https://Stackoverflow.com/questions/52397563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2407296/"
] | This kind of stuff is the actual and probably main use case for `Python Celery` (<https://docs.celeryproject.org/>). As a general rule, do not run long-running jobs that are CPU-bound in the `wsgi` process. It's tricky, it's inefficient, and most important thing, it's more complicated than setting up an *async* task in... | This approach works for me, it calls the timeout command (sleep 10s) in the command line and lets it work in the background. It returns the response immediately.
```
@app.route('/endpoint1')
def endpoint1():
subprocess.Popen('timeout 10', shell=True)
return 'success1'
```
However, not testing on WSGI server... | 13,933 |
28,150,433 | I'm trying to install Scrapy on windows 7. I'm following these instructions:
<http://doc.scrapy.org/en/0.24/intro/install.html#intro-install>
I’ve downloaded and installed python-2.7.5.msi for windows following this tutorial <https://adesquared.wordpress.com/2013/07/07/setting-up-python-and-easy_install-on-windows-7/... | 2015/01/26 | [
"https://Stackoverflow.com/questions/28150433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3640056/"
] | `ur` is python2 syntax you are trying to install an [incompatible](http://doc.scrapy.org/en/latest/faq.html#does-scrapy-work-with-python-3) package meant for python2 not python3:
```
_ajax_crawlable_re = re.compile(ur'<meta\s+name=["\']fragment["\']\s+content=["\']!["\']/?>')
^^ python... | Step By Step way to install scrapy on Windows 7
1. Install Python 2.7 from [Python Download link](https://www.python.org/downloads) (Be sure to install Python 2.7 only because currently scrapy is not available for Python3 in Windows)
2. During pyhton install there is checkbox available to add python path to system ... | 13,935 |
71,102,179 | I have tried anything in the internet and nothing works. My code:
```py
@bot.command()
async def bug(ctx, bug):
deleted_message_id = ctx.id
await ctx.channel.send(str(deleted_message_id))
await ctx.send(ctx.author.mention+", you're bug report hs been reported!")
```
I use python version 3.10 | 2022/02/13 | [
"https://Stackoverflow.com/questions/71102179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18196675/"
] | If you don't want to store the translation on the elements html themselves, you'll need to have an object mapping the values to the names to be output.
Here's a minimalist example:
```js
const numberNameMap = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five'
};
const select = document.querySelector('se... | I've simplified your code to do exactly what you want. Try this
```js
$(window).keydown(function(e) {
if( [37, 38, 39, 40, 13].includes(e.which) ){
e.preventDefault();
let $col = $('.multiple li.selected');
let $row = $col.closest('.multiple');
let $nextCol = $col;
... | 13,940 |
19,721,027 | After reading the [Software Carpentry](http://software-carpentry.org/) essay on [Handling Configuration Files](http://software-carpentry.org/v4/essays/config.html) I'm interested in their *Method #5: put parameters in a dynamically-loaded code module*. Basically I want the power to do calculations within my input files... | 2013/11/01 | [
"https://Stackoverflow.com/questions/19721027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2530083/"
] | "Never use eval or exec; they are evil". This is the only answer that works here, I think. There is no fully safe way to use exec/eval on an untrusted string string or file.
The best you can do is to come up with your own language, and either interpret it yourself or turn it into safe Python code before handling it to... | If you are willing to use PyPy, then its [sandboxing feature](http://doc.pypy.org/en/latest/sandbox.html) is specifically designed for running untrusted code, so it may be useful in your case. Note that there are some issues with CPython interoperability mentioned that you may need to check.
Additionally, there is a l... | 13,942 |
69,607,117 | I am trying to train a dl model with tf.keras. I have 67 classes of images inside the image directory like airports, bookstore, casino. And for each classes i have at least 100 images. The data is from [mit indoor scene](http://web.mit.edu/torralba/www/indoor.html) dataset But when I am trying to train the model, I am ... | 2021/10/17 | [
"https://Stackoverflow.com/questions/69607117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12195048/"
] | I think it might be a corrupted file. It is throwing an exception after a data integrity check in the `DecodeBMPv2` function (<https://github.com/tensorflow/tensorflow/blob/0b6b491d21d6a4eb5fbab1cca565bc1e94ca9543/tensorflow/core/kernels/image/decode_image_op.cc#L594>)
If that's the issue and you want to find out whic... | This is in fact a **corrupted file problem**. However, the underlying issue is far more subtle. Here is an explanation of what is going on and how to circumvent this obstacle. I encountered the very same problem on the very same [MIT Indoor Scene Classification](https://www.kaggle.com/datasets/itsahmad/indoor-scenes-cv... | 13,943 |
61,183,427 | I am beginner of python and trying to insert percentage sign in the output.
Below is the code that I've got.
```
print('accuracy :', accuracy_score(y_true, y_pred)*100)
```
when I run this code I got 50.0001 and I would like to have %sign at the end of the number
so I tried to do as below
```
print('Macro average ... | 2020/04/13 | [
"https://Stackoverflow.com/questions/61183427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10267370/"
] | Use f strings:
```
print(f"Macro average precision : {precision_score(y_true, y_pred, average='macro')*100}%\n")
```
Or convert the value to string, and add (*concatenate*) the strings:
```
print('Macro average precision : ' + str(precision_score(y_true, y_pred, average='macro')*100) + "%\n")
```
See [the discuss... | The simple, "low-tech" way is to correct your (lack of) output expression. Convert the float to a string and concatenate. To make it easy to follow:
```
pct = precision_score(y_true, y_pred, average='macro')*100
print('Macro average precision : ' + str(pct) + "%\n")
```
This is inelegant, but easy to follow. | 13,944 |
52,418,698 | I have Spark and Airflow cluster, I want to send a spark job from Airflow container to Spark container. But I am new about Airflow and I don't know which configuration I need to perform. I copied `spark_submit_operator.py` under the plugins folder.
```py
from airflow import DAG
from airflow.contrib.operators.spark_su... | 2018/09/20 | [
"https://Stackoverflow.com/questions/52418698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4230665/"
] | If you use SparkSubmitOperator the connection to master will be set as "Yarn" by default regardless master which you set on your python code, however, you can override master by specifying conn\_id through its constructor with the condition you have already created the aforementioned `conn_id` at "Admin->Connection" me... | I guess you need to set master in extra options in your connections for this spark conn id (spark\_default).By default is yarn, so try{"master":"your-con"}
Also does your airflow user has spark-submit in the classpath?, from logs looks like it doesnt. | 13,947 |
28,034,947 | So i'm trying to do something like this
```
#include <stdio.h>
int main(void)
{
char string[] = "bobgetbob";
int i = 0, count = 0;
for(i; i < 10; ++i)
{
if(string[i] == 'b' && string[i+1] == 'o' && string[i+2] == 'b')
count++;
}
printf("Number of 'bobs' is: %d\n... | 2015/01/19 | [
"https://Stackoverflow.com/questions/28034947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4123828/"
] | >
> Could i iterate through the string itself like so?
>
>
>
> ```
> for letter in s:
> #compare stuff
>
> ```
>
> How would I compare specific indexes in the string using the above method?
>
>
>
The pythonic way of doing these kind of comparisons without specifically referring to indexes would be:
```
for ... | Try this - i.e. go to len(s)-2 as you won't ever get a bob starting after that point
```
count = 0
s = "bobgetbob"
for i in range(len(s) - 2):
if s[i] == 'b' and s[i + 1] == 'o' and s[i + 2] == 'b':
count += 1
print "Number of 'bobs' is: %d" % count
``` | 13,948 |
11,464,750 | useI am working on a python script to check if the url is working. The script will write the url and response code to a log file.
To speed up the check, I am using threading and queue.
The script works well if the number of url's to check is small but when increasing the number of url's to hundreds, some url's just wi... | 2012/07/13 | [
"https://Stackoverflow.com/questions/11464750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1516432/"
] | Python's threading module isn't really multithreaded because of the global interpreter lock, <http://wiki.python.org/moin/GlobalInterpreterLock> as such you should really use `multiprocessing` <http://docs.python.org/library/multiprocessing.html> if you really want to take advantage of multiple cores.
Also you seem to... | At first glance this looks like a race condition, since many threads are trying to write to the log file at the same time. See [this question](https://stackoverflow.com/q/489861/520779) for some pointers on how to lock a file for writing (so only one thread can access it at a time). | 13,957 |
13,350,427 | I am learning to use javascript, ajax, python and django together.
In my project, a user selects a language from a drop-down list. Then the selected is sent back to the server. Then the server sends the response back to the django template. This is done by javascript. In the django template, I need the response, for e... | 2012/11/12 | [
"https://Stackoverflow.com/questions/13350427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1165201/"
] | You could use jquery to send the ajax request and server could send the response with html content.
For example,
Server: When server receives the ajax request. This would return the html content i.e. a template which could be rendered to the client via ajax
```
def update_html_on_client(request):
language = reque... | Because your templates are rendered on the server, your best bet is to simply reload the page (which re-renders the page with your newly selected language).
An alternative to using ajax would be to store the language in a cookie, that way you don't have to maintain state on the client. Either way, the reload is still ... | 13,958 |
66,889,445 | I am trying to push my app to heroku, I am following the tutorial from udemy - everything goes smooth as explained. Once I am at the last step - doing `git push heroku master` I get the following error in the console:
```
(flaskdeploy) C:\Users\dmitr\Desktop\jose\FLASK_heroku>git push heroku master
Enumerating objects... | 2021/03/31 | [
"https://Stackoverflow.com/questions/66889445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11803958/"
] | You could use [repr](https://docs.python.org/3/library/functions.html#repr)
```py
print(repr(var))
``` | Maybe you want to use f-string ?
```
var = "textlol"
print(f"\"{var}\"")
``` | 13,959 |
16,206,224 | I have a python list and I would like to export it to a csv file, but I don't want to store all the list in the same row. I would like to slice the list at a given point and start a new line. Something like this:
```
list = [x1,x2,x3,x4,y1,y2,y3,y4]
```
and I would like it to export it in this format
```
x1 x2 x3 ... | 2013/04/25 | [
"https://Stackoverflow.com/questions/16206224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1956586/"
] | For a `list` (call it `seq`) and a target row length (call it `rowsize`), you would do something like this:
```
split_into_rows = [seq[i: i + rowsize] for i in range(0, len(seq), rowsize)]
```
You could then use the writer's `writerows` method to write elements to the file:
```
writer.writerows(split_into_rows)
``... | I suggest using a temp array B.
1. Get the length of the original array A
2. Copy the first A.length/2 to array B
3. Add new line character to array B.
4. Append the rest of array A to B. | 13,963 |
13,219,585 | im teaching myself python and im abit confused
```
#!/usr/bin/python
def Age():
age_ = int(input("How old are you? "))
def Name():
name_ = raw_input("What is your name? ")
def Sex():
sex_ = raw_input("Are you a man(1) or a woman(2)? ")
if sex_ == 1:
man = 1
e... | 2012/11/04 | [
"https://Stackoverflow.com/questions/13219585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1222298/"
] | Programming Lua has example on [non-preemptive multithreading](http://www.lua.org/pil/9.4.html) (using coroutines), which you can probably use almost directly. In my opinion coroutines will be a better solution for your use case.
There is also [copas library](http://keplerproject.github.com/copas/index.html) that desc... | Lua Lanes creates an entirely new (but minimal) Lua state for each lane.
Any upvalues or arguments passed are copied, not referenced; this means your allClients table is being copied, along with the sockets it contains.
The error is occurring because the sockets are userdata, which Lua Lanes does not know how to copy ... | 13,970 |
17,664,841 | I have a set and dictionary and a value = 5
```
v = s = {'a', 'b', 'c'}
d = {'b':5 //<--new value}
```
If the key 'b' in dictionary d for example is in set s then I want to make that value equal to the new value when I return a dict comprehension or 0 if the key in set s is not in the dictionary d. So this is my cod... | 2013/07/15 | [
"https://Stackoverflow.com/questions/17664841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1509483/"
] | The expanded form of what you're trying to achieve is
```
a = {}
for k in v:
a[k] = d[k] if k in d else 0
```
where `d[k] if k in d else 0` is [the Python's version of ternary operator](https://docs.python.org/dev/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator). See? You need to drop `k:` fr... | You can't use a ternary `if` expression for a name:value pair, because a name:value pair isn't a value.
You *can* use an `if` expression for the value or key separately, which seems to be exactly what you want here:
```
{k: (d[k] if k in v else 0) for k in v}
```
However, this is kind of silly. You're doing `for k ... | 13,971 |
2,616,190 | e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"? | 2010/04/11 | [
"https://Stackoverflow.com/questions/2616190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | In c# 6.0 you can now do
```
string username = SomeUserObject?.Username;
```
username will be set to null if SomeUSerObject is null.
If you want it to get the value "", you can do
```
string username = SomeUserObject?.Username ?? "";
``` | It is called null coalescing and is performed as follows:
```
string username = SomeUserObject.Username ?? ""
``` | 13,974 |
70,279,160 | trying to find out correct syntax to traverse through through the list to get all values and insert into oracle.
edit:
Below is the json structure :
```
[{
"publishTime" : "2021-11-02T20:18:36.223Z",
"data" : {
"DateTime" : "2021-11-01T15:10:17Z",
"Name" : "x1",
"frtb" : {
"code" : "set1"
},... | 2021/12/08 | [
"https://Stackoverflow.com/questions/70279160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17544527/"
] | Knative Serving does not support such a policy as of today. However, the community thinks that Kubernetes' Descheduler should work just fine, as is discussed in <https://github.com/knative/serving/issues/6176>. | Not kn specific but you could try adding `activeDeadlineSeconds` to the podSpec. | 13,984 |
47,351,274 | In summary, When provisioning my vagrant box using Ansible, I get thrown a mysterious error when trying to clone my bitbucket private repo using ssh.
The error states that the "Host key verification failed".
Yet if I vagrant ssh and then run the '*git clone*' command, the private repo is successfully cloned. This indi... | 2017/11/17 | [
"https://Stackoverflow.com/questions/47351274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4515324/"
] | Since you run the whole playbook with `become: true`, SSH key-forwarding (as well as troubleshooting) becomes irrelevant, because the user connecting to BitBucket from your play is `root`.
Run the task connecting to BitBucket as `ubuntu` user:
* either specifying `become: false` in the `Clone bitbucket repo` task),
*... | This answer comes direct from techraf's helpful comments.
* I changed the owner of the /var/www directory from 'www-data' to
'ubuntu' (the username I use to login via ssh).
* I also added "become: false" above the git task.
NOTE: I have since been dealing with the following issue so this answer does not fully resolve... | 13,985 |
40,477,687 | I'm getting `ImportError: No module named django` when trying to up my containers running `docker-compose up`.
Here's my scenario:
Dockerfile
```
FROM python:2.7
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/
```
docker-compose.yml
... | 2016/11/08 | [
"https://Stackoverflow.com/questions/40477687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2812350/"
] | Maybe what you want is to do this:
```
void printHandResults(struct Card (*hand)[]);
```
and this:
```
void printHandResults(struct Card (*hand)[]) {
}
```
What you were doing was passing a pointer to an array of struct variables in the main, BUT, the function was set to receive **an array of pointers to struct ... | More easy way:
```
#define HAND_SIZE 5
typedef struct Cards{
char suit;
char face;
}card_t;
void printHandResults( card_t*);
int main(void)
{
card_t hand[HAND_SIZE];
card_t* p_hand = hand;
...
printHandResults(p_hand);
}
void printHandResults( card_t *hand)
{
// Here you must play with pointer's ar... | 13,986 |
57,498,262 | It seems so basic, but I can't work out how to achieve the following...
Consider the scenario where I have the following data:
```py
all_columns = ['A','B','C','D']
first_columns = ['A','B']
second_columns = ['C','D']
new_columns = ['E','F']
values = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
df ... | 2019/08/14 | [
"https://Stackoverflow.com/questions/57498262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10750173/"
] | An option is `pivot_longer` from the dev version of `tidyr`
```
library(tidyr)
library(dplyr)
library(tibble)
nm1 <- sub("\\.?\\d+$", "", names(df))
names(df) <- paste0(nm1, ":", ave(seq_along(nm1), nm1, FUN = seq_along))
df %>%
rownames_to_column('rn') %>%
pivot_longer(-rn, names_to= c(".value", "Group"), n... | You may use base R's `reshape`. The trick is the nested `varying` and to `cbind` an `id` column.
```
reshape(cbind(id=1:nrow(DF), DF), varying=list(c(2, 4), c(3, 5)), direction="long",
timevar="Group", v.names=c("Gene", "AVG_EXPR"), times=c("Group1", "Group2"))
# id Group Gene AVG_EXPR
#... | 13,988 |
67,080,686 | So I need to enforce the type of a class variable, but more importantly, I need to enforce a list with its types. So if I have some code which looks like this:
```
class foo:
def __init__(self, value: list[int]):
self.value = value
```
Btw I'm using python version 3.9.4
So essentially my question is, ho... | 2021/04/13 | [
"https://Stackoverflow.com/questions/67080686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15017177/"
] | You can enable the system keyboard by configuring `OVRCameraRig` Oculus features.
1. From the Hierarchy view, select `OVRCameraRig` to open settings in the Inspector view.
2. Under `OVR Manager`, in the `Quest Features` section, select `Require System Keyboard`.
[
{
keyboard = TouchScreenKeyboard.Open("", TouchScreenKeyboardType.Default);
}
```
Just add... | 13,990 |
1,399,727 | Assuming the text is typed at the same time in the same (Israeli) timezone, The following free text lines are equivalent:
```
Wed Sep 9 16:26:57 IDT 2009
2009-09-09 16:26:57
16:26:57
September 9th, 16:26:57
```
Is there a python module that would convert all these text-dates to an (identical) `datetime.datetime` in... | 2009/09/09 | [
"https://Stackoverflow.com/questions/1399727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51197/"
] | The [python-dateutil](http://labix.org/python-dateutil) package sounds like it would be helpful. Your examples only use simple HH:MM timestamps with a (magically shortened) city identifier, but it seems able to handle more complicated formats like those earlier in the question, too. | You could you [`time.strptime`](http://docs.python.org/library/time.html#time.strptime)
Like this :
```
time.strptime("2009-09-09 16:26:57", "%Y-%m-%d %H:%M:%S")
```
It will return a struct\_time value (more info on the python doc page). | 13,991 |
62,767,387 | I'm a noob with python beautifoulsoup library and i'm trying to scrape data from a website's highcharts. i found that all the data i need is located in a script tag, however i dont know how to scrape them (please see the attached image) Is there a way to get the data from this script tag using python beautifulsoup?
[sc... | 2020/07/07 | [
"https://Stackoverflow.com/questions/62767387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13881565/"
] | Check out this working sandbox:
<https://codesandbox.io/s/confident-taussig-tg3my?file=/src/App.js>
One thing to note is you shouldn't base keys off of linear sequences [or indexes] because that can mess up React's tracking. Instead, pass the index value from map into the IssueRow component to track order, and give ea... | This should be inside another `React.useEffect()`:
```
setTimeout(() => {
createIssue(sampleIssue);
}, 2000);
```
Otherwise, it will run every render in a loop. As a general rule of thumb there should be no side effects outside of useEffect. | 13,993 |
63,438,737 | I have an image in which text is lighter and not clearly visible, i want to enhance the text and lighten then background using python pil or cv2. Help is needed. I needed to print this image and hence it has ro be clearer.
what i have done till now is below
```
from PIL import Image, ImageEnhance
im = Image.open('t.j... | 2020/08/16 | [
"https://Stackoverflow.com/questions/63438737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Save first column in an array, too.
Insert before your `END` section `{dates[FNR] = $1}` and replace both `$1` with `dates[n]`. | Could you please try following, have written on mobile so couldn't test it as of now, should work but.
```
awk '
{
diff=$2-$3
a[$1]=(a[$1]!="" && a[$1]>diff?a[$1]:diff)
}
END{
for(i in a){
print i,a[i]
}
}' *.txt
``` | 13,995 |
58,771,456 | i am installing connector of Psycopg2 but i am unable install, how do i install that successfully?
in using this command line to install:
```
pip install psycopg2
(test) C:\Users\Shree.Shree-PC\Desktop\projects\purchasepo>pip install psycopg2
Collecting psycopg2
Using cached https://files.pythonhosted.org/packages... | 2019/11/08 | [
"https://Stackoverflow.com/questions/58771456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10123621/"
] | It was such a dump solution, it took me hours to find this:
When I get the file from DocumentPicker I had to add the type of the file because DocumentPicker return an odd type called "success", when I changed it to 'image/jpeg' it worked :D its not a solution at all because I will need to find a way to know what type ... | you should try to modify the content-type to
```
fetch("http://192.168.0.3:8000/api/file", {
method: "POST",
headers:{
'Content-Type': 'multipart/form-data',
},
body: data
})
```
and for the form-url-urlencoded, the fetch is not supported. you have to push it by yourself.you ca... | 13,997 |
1,817,183 | I'm trying to learn the super() function in Python.
I thought I had a grasp of it until I came over this example (2.6) and found myself stuck.
[http://www.cafepy.com/article/python\_attributes\_and\_methods/python\_attributes\_and\_methods.html#super-with-classmethod-example](https://web.archive.org/web/2017082006590... | 2009/11/29 | [
"https://Stackoverflow.com/questions/1817183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/169854/"
] | Sometimes texts have to be read more for the flavor of the idea rather than for the details. This is one of those cases.
In the [linked page](http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#a-super-solution), Examples 2.5, 2.6 and 2.7 should all use one method, `do_your_s... | The example from the web page seems to work as published. Did you create a `do_something` method for the superclass as well but not make it into a classmethod? Something like this will give you that error:
```
>>> class A(object):
... def do_something(cls):
... print cls
... # do_something = classmethod(... | 13,998 |
10,269,860 | Here is a simple code in python 2.7.2, which fetches site and gets all links from given site:
```
import urllib2
from bs4 import BeautifulSoup
def getAllLinks(url):
response = urllib2.urlopen(url)
content = response.read()
soup = BeautifulSoup(content, "html5lib")
return soup.find_all("a")
links1 = g... | 2012/04/22 | [
"https://Stackoverflow.com/questions/10269860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/808271/"
] | When a document claims to be XML, I find the lxml parser gives the best results. Trying your code but using the lxml parser instead of html5lib finds the 300 links. | You are precisely right that the problem is the `<?xml...` line. Disregarding it is very simple: just skip the first line of content, by replacing
```
content = response.read()
```
with something like
```
content = "\n".join(response.readlines()[1:])
```
Upon this change, `len(links2)` becomes 300.
ETA: ... | 14,007 |
73,494,380 | I have a script using `docker` python library or [Docker Client API](https://docker-py.readthedocs.io/en/1.8.0/api/#containers). I would like to limit each docker container to use only 10cpus (total 30cpus in the instance), but I couldn't find the solution to achieve that.
I know in docker, there is `--cpus` flag, but... | 2022/08/25 | [
"https://Stackoverflow.com/questions/73494380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16729348/"
] | cPanel has a feature called Multi-PHP, which does what you need (if your host has it enabled).
For each project, it puts a snippet like this in the `.htaccess` which sets the PHP version to use:
```
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php81” package as the default “PHP” programming lang... | You can use as many different versions as you want.
Consider:
1. Install PHP versios with PHP-FPM
2. Create directory strucure for each version (website)
3. Configure Apache for Both Websites.
With the above configuration you have combined virtual hosts and PHP-FPM to serve multiple websites and multiple versions of ... | 14,008 |
7,073,557 | Question: Is there a way to make a program run with out logging in that doesn't involve the long painful task of creating a windows service, or is there an easy way to make a simple service?
---
Info: I'm working on a little project for college which is a simple distributed processing program. I'm going to harness th... | 2011/08/16 | [
"https://Stackoverflow.com/questions/7073557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186608/"
] | The Windows NT Resource Kit introduced the [Srvany.exe command-line utility](http://support.microsoft.com/kb/137890), which can be used to start any Windows NT/2000/2003 application as a service.
You can download Srvany.exe [here](http://www.microsoft.com/download/en/details.aspx?id=17657). | Use Visual Studio and just create yourself a Windows Service project. I think you'll find it very easy. | 14,009 |
26,044,173 | I made a program in python which allows you to type commands (e.g: if you type clock, it shows you the date and time). But, I want it to be fullscreen. The problem is that my software doesnt have gui and I dont want it to so that probably means that I wont be using tkinter or pygame. Can some of you write a whole 'hell... | 2014/09/25 | [
"https://Stackoverflow.com/questions/26044173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061311/"
] | Since Vista, cmd.exe can no longer go to full-screen mode. You'll need to implement a full-screen console emulator yourself or look for another existing solution. E.g. [ConEmu](http://www.hanselman.com/blog/conemuthewindowsterminalconsolepromptwevebeenwaitingfor.aspx) appears to be able to do it. | Solution
--------
Use your Operating System services to configure parameters.
```
<_aMouseRightClick_>->[Properties]->[Layout]
```
Kindly notice, that some of the `python` interpreter process window parameters are given in [char]-s, while some other in [px]:
```
size.Width [char]-s
size.Height[char]-s
loc.X [... | 14,018 |
40,265,591 | I have a data frame that in which every row represents a day of the week, and every column represents the serial number of an internet-connected device that failed to communicate with the server on that day.
I am trying to get a Series of serial numbers that have failed to communicate for a full week.
The code block:... | 2016/10/26 | [
"https://Stackoverflow.com/questions/40265591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3285817/"
] | You could try something like this, if you pass in the name of the controller as a string. This solution assumes that your models are using `ActiveRecord` prior to rails 5 where `ApplicationRecord` was used to define models; in that case just switch `ActiveRecord::Base` with `ApplicationRecord`. Also if you have models ... | This method doesn't rely on exceptions, and works with input as Class or String. It should work for any Rails version :
```
def has_model?(controller_klass)
all_models = ActiveRecord::Base.descendants.map(&:to_s)
model_klass_string = controller_klass.to_s.sub(/Controller$/,'').singularize
all_models.include?(mod... | 14,019 |
66,942,621 | Im attempting to launch a python script from my Java program - The python script listens for socket connections from the Java program and responds with data.
In order to do this I have attempted to use the ProcessBuilder API to:
1. activate a python virtualenv (located in my working directory)
2. run my python script ... | 2021/04/04 | [
"https://Stackoverflow.com/questions/66942621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15539237/"
] | If your Java program exits, the Python process you launched will exit as well as child processes are killed when a parent process dies unless they have been detached from that process.
If you want your Java program to keep running until the Python program has completed execution, then you need to have the Java code wa... | In the end the solution was simple:
```
Process process = Runtime.getRuntime().exec("<path/to/venv/python_interpreter> "+"path/to/scripytorun.py)
```
In my case the succcessful command was
```
Process process = Runtime.getRuntime().exec( System.getProperty("user.dir")+"/env/bin/python "+System.getProperty("use... | 14,020 |
51,783,232 | I am using python regular expressions. I want all colon separated values in a line.
e.g.
```
input = 'a:b c:d e:f'
expected_output = [('a','b'), ('c', 'd'), ('e', 'f')]
```
But when I do
```
>>> re.findall('(.*)\s?:\s?(.*)','a:b c:d')
```
I get
```
[('a:b c', 'd')]
```
I have also tried
```
>>> re.findall(... | 2018/08/10 | [
"https://Stackoverflow.com/questions/51783232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1217998/"
] | Use split instead of regex, also avoid giving variable name like keywords
:
```
inpt = 'a:b c:d e:f'
k= [tuple(i.split(':')) for i in inpt.split()]
print(k)
# [('a', 'b'), ('c', 'd'), ('e', 'f')]
``` | The easiest way using `list comprehension` and `split` :
```
[tuple(ele.split(':')) for ele in input.split(' ')]
```
#driver values :
```
IN : input = 'a:b c:d e:f'
OUT : [('a', 'b'), ('c', 'd'), ('e', 'f')]
``` | 14,021 |
36,563,002 | I have a python code. I need to execute the python script from my c# program. After searching a bit about this, I came to know that there is mainly two ways of executing a python script from c#.
One by using 'Process' command and
the other by using Iron Python.
My question might seem dumb, is there any other way th... | 2016/04/12 | [
"https://Stackoverflow.com/questions/36563002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5743035/"
] | The constants you're looking for are not called `LONG_LONG_...`. Check your `limits.h` header. Most likely you're after `ULLONG_MAX`, `LLONG_MAX`, etc. | >
> Why do the integers and long integers have the same limits? Shouldn't the long integers have a larger range of values?
>
>
>
You have stepped into one of the hallmarks of the C language - its adaptability.
C defines the range of `int` to be at least as wide as `short` and the range of `long` to be at least as... | 14,026 |
19,940,549 | I am using the [NakedMUD](http://homepages.uc.edu/~hollisgf/nakedmud.html) code base for a project. I am running into an issue in importing modules.
In \*.py (Python files) they import modules with the following syntax:
```
import mudsys, mud, socket, char, hooks
```
and in C to embed Python they use:
```
mudmod =... | 2013/11/12 | [
"https://Stackoverflow.com/questions/19940549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/583608/"
] | You may want to enable WCF Tracing and Message Logging, which will allow you to monitor/review communication to/from the WCF service and hopefully isolate the issue (which, based on the provided error message, may likely be a timeout issue.)
The following links provide a good overview:
<http://msdn.microsoft.com/e... | adkSerenity and shambulator,
Thank you. I found the problem. It turned out to be a buffer size. I was pretty sure it wasn't a timeout because the shortest timeout was set to one minute and I could reproduce the error in thirty seconds.
I had been avoiding WCF Tracing and Message Logging because it was so intimidating... | 14,031 |
12,993,175 | I'm having a problem with python keyring after the installation.
here are my steps:
```
$ python
>>> import keyring
>>> keyring.set_password('something','otherSomething','lotOfMoreSomethings')
```
and then throws this:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/p... | 2012/10/20 | [
"https://Stackoverflow.com/questions/12993175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1715386/"
] | For each market where you have specific requirements due to market-specific licensing or legal issues, you can create a separate app in iTunes Connect and make it available for download only in the relevant market. And if you need to, this also allows you to provide a market-specific EULA. It's a big maintenance burden... | A 3rd party app has no access whatsoever to any information about the user of the device or access to the iTunes account. There is no way to know the user's true country. At any given time, the device may not even be associated with any one person. An iPod touch, for example, may have no user logged into any iTunes acc... | 14,032 |
38,156,681 | I create a custom Authentication backends for my login system. Surely, the custom backends works when I try it in python shell. However, I got error when I run it in the server. The error says "The following fields do not exist in this model or are m2m fields: last\_login". Do I need include the last\_login field in cu... | 2016/07/02 | [
"https://Stackoverflow.com/questions/38156681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5458894/"
] | This is happening because you are using django's [`login()`](https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.login) function to log the user in.
Django's `login` function emits a signal named `user_logged_in` with the `user` instance you supplied as argument. [See `login()` source](https... | Thanks, I defined a custom `login` method as follows to get through this issue in my automated tests in which I by default keep the signals off.
Here's a working code example.
```
def login(client: Client, user: User) -> None:
"""
Disconnect the update_last_login signal and force_login as `user`
Ref: http... | 14,033 |
50,092,608 | I've defined a helper method to load json from a string or file like so:
```
def get_json_from_string_or_file(obj):
if type(obj) is str:
return json.loads(obj)
return json.load(obj)
```
When I try it with a file it fails on the `load` call with the following exception:
```
File "/usr/local/Cellar/py... | 2018/04/30 | [
"https://Stackoverflow.com/questions/50092608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2155605/"
] | Following code works.
```
import os
import json
def get_json_from_string_or_file(obj):
if type(obj) is str:
return json.loads(obj)
return json.load(obj)
filename = os.path.join(os.path.dirname(__file__), "..", "test.json")
with open(filename, 'r') as f:
result = get_json_from_string_or_file(f)
... | Sorry, I'd comment but I lack the rep. Can you paste a sample JSON file that doesn't work into a pastebin? I'll edit this into an answer after that if I can. | 14,034 |
67,103,105 | I'm trying to upload PDF-file in the Xero account using the python request library (POST method) and Xeros FilesAPI said "Requests must be formatted as multipart MIME" and have some required fields ([link](https://developer.xero.com/documentation/files-api/files#POST)) but I don't how to do that exactly...If I do GET-r... | 2021/04/15 | [
"https://Stackoverflow.com/questions/67103105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9025820/"
] | As I see you're improperly set the boundary. You set it in the headers but not tell to `requests` library to use custom boundary. Let me show you an example:
```
>>> import requests
>>> post_url = 'https://api.xero.com/files.xro/1.0/Files/'
>>> files = {'file': open('/tmp/test.txt', 'rb')}
>>> headers = {
... 'Auth... | I've tested this with Xero's Files API to upload a file called "helloworld.rtf" in the same directory as my main app.py file.
```
var1 = "Bearer "
var2 = YOUR_ACCESS_TOKEN
access_token_header = var1 + var2
body = open('helloworld.rtf', 'rb')
mp_encoder = MultipartEncoder(
fields={
'helloworld.rtf': ('helloworld.... | 14,035 |
19,829,952 | Objective:
Trying to run SL4A facade APIs from python shell on the host system (windows 7 PC)
My environment:
1. On my windows 7 PC, i have python 2.6.2
2. Android sdk tools rev 21, platform tools rev 16
3. API level 17 supported for JB 4.2
4. I have 2 devices ( one running android 2.3.3 and another android 4.2.2) b... | 2013/11/07 | [
"https://Stackoverflow.com/questions/19829952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2949720/"
] | ***You can create your own Video Recording Screen***
Try like this, First Create a Custom Recorder using `SurfaceView`
```
public class VideoCapture extends SurfaceView implements SurfaceHolder.Callback {
private MediaRecorder recorder;
private SurfaceHolder holder;
public Context context;
private C... | This way is using fragments:
```
public class CaptureVideo extends Fragment implements OnClickListener, SurfaceHolder.Callback{
private Button btnStartRec;
MediaRecorder recorder;
SurfaceHolder holder;
boolean recording = false;
private int randomNum;
public void onCreate(Bundle savedInstanc... | 14,037 |
64,018,103 | I've been working in a project for about 6 months, and I've been adding more urls each time. Right now, I'm coming into the problem that when I'm using `extend 'base.html'` into another pages, the CSS overlap, and I'm getting a mess.
My question is: Which are the best practices when using `extend` for CSS files? Shoul... | 2020/09/22 | [
"https://Stackoverflow.com/questions/64018103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13821665/"
] | Django provides django.contrib.staticfiles which is tasked with static files(CSS,JavaScript,media).In a nut shell each template in the app will inherit the base static folder in your app
[Read the below doc and see how to configure the static files](https://docs.djangoproject.com/en/3.1/howto/static-files/) | you can add your static files in your template:
```
{% extends 'pythonApp/base.html' %}
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'pathtostaticfile' %}" />
...
``` | 14,040 |
65,278,114 | I'm a beginner currently working on a small python project. It's a dice game in which there is player 1 and player 2. Players take turns to roll the dice and a game is 10 rounds in total(5 rounds for each player). The player with the highest number of points wins.
I am trying to validate the first input so that when f... | 2020/12/13 | [
"https://Stackoverflow.com/questions/65278114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13824901/"
] | Wrap that section of input in a `while True` loop. break the loop when the input is correct, otherwise keep looping for more input.
```
while True:
b = int(input ("is player a Computer (0) or a human (1)?"))
if b == 0:
# player is a computer ...
# do computer stuff
break
elif b == 1... | Because elif is not a loop , compiler just checks the condition and then it moves forward executing the statement.
You can solve this by just adding a \*\*\*while loop \*\*\* before first if condition like this :
for i in range (players):
a = input("name of player: ")
b = int(input ("is player a Computer (0) or a hum... | 14,042 |
65,940,602 | I'm new to python and I'm using the book called "Automate the Boring Stuff with Python".
I was entering the following code (which was the same as the book):
```
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
``... | 2021/01/28 | [
"https://Stackoverflow.com/questions/65940602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14883326/"
] | Its perfectly fine just check your indentation | I think it's because of an **indentation**'s mistake.
copy & paste the code below and check if it solves your problem or not.
```
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
```
indentations are so critical in python programming. you should a... | 14,044 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.