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 |
|---|---|---|---|---|---|---|
57,624,355 | I deploy a Python app to Google Cloud Functions and got this very vague error message:
```
$ gcloud functions deploy parking_photo --runtime python37 --trigger-http
Deploying function (may take a while - up to 2 minutes)...failed.
ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Fun... | 2019/08/23 | [
"https://Stackoverflow.com/questions/57624355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/502780/"
] | Most likely your function is raising a `FileNotFound` error, and Cloud Functions interprets this as `main.py` not existing. A minimal example that will cause the same error:
```
$ cat main.py
with open('missing.file'):
pass
def test(request):
return 'Hello World!'
```
You should check to make sure that any ... | Iβve tried to reproduce the error that you are describing by deploying a new Cloud Function without any function with the name of the CF and I got the following error:
ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Function failed on loading user code. Error message: File main.py is expected to contai... | 455 |
62,579,243 | I know my question has a lot of answers on the internet but it's seems i can't find a good answer for it, so i will try to explain what i have and hope for the best,
so what i'm trying to do is reading a big json file that might be has more complex structure "nested objects with big arrays" than this but for simple ex... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62579243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440284/"
] | >
> and my question how can i get any peace and navigate between nodes of this data with the most efficient way that will not take much RAM and CPU, i can't read the file line by line because i need to get any peace of data when i have to,
>
>
>
It's plain text JSON and you have no indexes, so it's impossible to p... | **Try Reducing You Bulk Data Complexity For Faster File I/O**
JSON is a great format to store data in, but it comes at the cost of needing to read the entire file to parse it.
Making your data structure simpler but more spread out across several files can allow you to read a file line-by-line which is much faster tha... | 457 |
39,942,061 | I'm having a weird problem with a piece of python code.
The idea how it should work:
1. a barcode is entered (now hardcode for the moment);
2. barcode is looked up in local mysqldb, if not found, the barcode is looked up via api from datakick, if it's not found there either, step 3
3. i want to add the barcode to my l... | 2016/10/09 | [
"https://Stackoverflow.com/questions/39942061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6944323/"
] | `UNORDERED` essentially means that the collector is both associative (required by the spec) and commutative (not required).
Associativity allows splitting the computation into subparts and then combining them into the full result, but requires the combining step to be strictly ordered. Examine this snippet from the [... | The inner `Collector.Characteristics` class itself is fairly terse in its description, but if you spend a few seconds exploring the context you will notice that the containing [Collector](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html) interface provides additional information
>
> For colle... | 467 |
15,526,996 | After installing the latest [Mac OSX 64-bit Anaconda Python distribution](http://continuum.io/downloads.html), I keep getting a ValueError when trying to start the IPython Notebook.
Starting ipython works fine:
```
3-millerc-~:ipython
Python 2.7.3 |Anaconda 1.4.0 (x86_64)| (default, Feb 25 2013, 18:45:56)
Type "copy... | 2013/03/20 | [
"https://Stackoverflow.com/questions/15526996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655733/"
] | I summarize here the solution to be found on: <http://blog.lobraun.de/2009/04/11/mercurial-on-mac-os-x-valueerror-unknown-locale-utf-8/>
I added these lines to my `.bash_profile`:
```
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
```
I reloaded the profile:
```
source ~/.bash_profile
```
I then ran `ipython... | As your `LC_CTYPE` is wrong, you should find out where that wrong value is set and change it to something like `en_US.UTF-8`. | 469 |
26,005,454 | I am creating a fast method of generating a list of primes in the range(0, limit+1). In the function I end up removing all integers in the list named removable from the list named primes. I am looking for a fast and pythonic way of removing the integers, knowing that both lists are always sorted.
I might be wrong, but... | 2014/09/23 | [
"https://Stackoverflow.com/questions/26005454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3987360/"
] | This is quite fast and clean, it does `O(n)` set membership checks, and in amortized time it runs in `O(n)` (first line is `O(n)` amortized, second line is `O(n * 1)` amortized, because a membership check is `O(1)` amortized):
```
removable_set = set(removable)
primes = [p for p in primes if p not in removable_set]
`... | The most important thing here is to remove the quadratic behavior. You have this for two reasons.
First, calling `remove` searches the entire list for values to remove. Doing this takes linear time, and you're doing it once for each element in `removable`, so your total time is `O(NM)` (where `N` is the length of `pri... | 475 |
59,160,291 | Is there a way how to simplify this static methods in python? I'm looking to reduce typing of the arguments every time I need to use a function.
```
class Ibeam:
def __init__ (self, b1, tf1, tw, h, b2, tf2, rt, rb):
self.b1 = b1
self.tf1 = tf1
self.tw = tw
self.h = h
self.b2 = b2
self.tf2 = t... | 2019/12/03 | [
"https://Stackoverflow.com/questions/59160291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448859/"
] | You could use good default values if such exist.
```py
def area(b1=None, tf1=None, tw=None, h=None, b2=None, tf2=None, rt=None, rb=None):
....
```
An even better solution would be to design your class in a way that it does not require so many parameters. | When having functions with many arguments it might be useful to think about "related" arguments and group them together. For example, consider a function that calculates the distance between two points. You could write a function like the following:
```
def distance(x1, y1, x2, y2):
...
return distance
print(di... | 476 |
59,493,383 | I'm currently working on a project and I am having a hard time understanding how does the Pandas UDF in PySpark works.
I have a Spark Cluster with one Master node with 8 cores and 64GB, along with two workers of 16 cores each and 112GB. My dataset is quite large and divided into seven principal partitions consisting e... | 2019/12/26 | [
"https://Stackoverflow.com/questions/59493383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5932364/"
] | >
> Does Spark try to convert one whole partition at once (78M lines) ?
>
>
>
That's exactly what happens. Spark 3.0 adds support for chunked UDFs, which operate on iterators of Pandas `DataFrames` or `Series`, but if *operations on the dataset, that can only be done using Python, on a Pandas dataframe*, these mi... | To answer the general question about using a Pandas UDF on a large pyspark dataframe:
If you're getting out-of-memory errors such as
`java.lang.OutOfMemoryError : GC overhead limit exceeded` or `java.lang.OutOfMemoryError: Java heap space` and increasing memory limits hasn't worked, ensure that pyarrow is enabled. It ... | 479 |
20,317,792 | I want my interactive bash to run a program that will ultimately do things like:
echo Error: foobar >/dev/tty
and in another(python) component tries to prompt for and read a password from /dev/tty.
I want such reads and writes to fail, but not block.
Is there some way to close /dev/tty in the parent script and then... | 2013/12/01 | [
"https://Stackoverflow.com/questions/20317792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727810/"
] | You are doing a [UNION ALL](http://dev.mysql.com/doc/refman/5.0/en/union.html)
`at_tot` results are being appended to `a_tot`.
`at_prix` results are being appended to `a_tva`.
`at_pax` results are being appended to `v_tot`.
`at_vente` results are being appended to `v_tva`.
The [SQL UNION ALL](http://www.w3s... | When you use UNION , the alias that end up in the result are the one from the first select in the union. So `at_tot` (from second select of union) is replaced with a\_tot.
What you do is the same as doing:
```sql
SELECT SUM(IF(status=0,montant,0)) AS a_tot,
SUM(IF(status=0, montant * (tvaval/100),0)) AS a_tva... | 480 |
49,757,771 | So I wrote a python file creating the single topology ( just to check if custom topology works) without using any controller at first. the code goes:
```
#!/usr/bin/python
from mininet.node import CPULimitedHost, Host, Node
from mininet.node import OVSSwitch
from mininet.topo import Topo
class Single1(Topo):
"Singl... | 2018/04/10 | [
"https://Stackoverflow.com/questions/49757771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7463091/"
] | This is an older question and probably no longer of interest to the original poster, but I landed here from a mininet related search so I thought I'd provide a working example in case other folks find there way here in the future.
First, there are a number of indentation problems with the posted code, but those are si... | The hosts must be in same subnet in order to avoid routing protocols. Otherwise you need static routes | 481 |
2,332,164 | I use python debugger pdb. I use emacs for python programming. I use python-mode.el. My idea is to make emacs intuitive. So I need the following help for python programs (.py)
1. Whenever I press 'F9' key, the emacs should put "import pdb; pdb.set\_trace();" statements in the current line and move the current line to ... | 2010/02/25 | [
"https://Stackoverflow.com/questions/2332164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | to do 1)
```
(defun add-py-debug ()
"add debug code and move line down"
(interactive)
(move-beginning-of-line 1)
(insert "import pdb; pdb.set_trace();\n"))
(local-set-key (kbd "<f9>") 'add-py-debug)
```
to do 2) you probably have to change the syntax highlighting of the python mode, or ... | I've found that [Xah's Elisp Tutorial](http://xahlee.info/emacs/emacs/elisp.html) is an excellent starting point in figuring out the basics of Emacs Lisp programming. [There](https://sites.google.com/site/steveyegge2/effective-emacs) [are](https://steve-yegge.blogspot.com/2008/01/emergency-elisp.html) [also](https://st... | 484 |
41,936,098 | I am trying to install the `zipline` module using `"pip install zipline"` but I get this exception:
```
IOError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/editor.pyc'` - any help would be greatly appreciated
Failed building wheel for numexpr
Running setup.py clean for numexpr
Fa... | 2017/01/30 | [
"https://Stackoverflow.com/questions/41936098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7283601/"
] | AS you are not root. You can use sudo to obtain superuser permissions:
```
sudo pip install zipline
```
Or else
**For GNU/Linux :**
On Debian-derived Linux distributions, you can acquire all the necessary binary dependencies from apt by running:
```
$ sudo apt-get install libatlas-base-dev python-dev gfortran pkg... | Avoid using `sudo` to install packages with `pip`. Use the `--user` option instead or, even better, use virtual environments.
See [this SO answer](https://stackoverflow.com/a/42021993/3577054). I think this question is a duplicate of that one. | 485 |
60,917,385 | My aim:
To count the frequency of a user entered word in a text file.(in python)
I tried this.But it gives the frequency of all the words in the file.How can i modify it to give the frequency of a word entered by the user?
```
from collections import Counter
word=input("Enter a word:")
def word_count(test6):
w... | 2020/03/29 | [
"https://Stackoverflow.com/questions/60917385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13140422/"
] | Hi I just solved the problem.
After you run
`docker build .`
run the `docker-compose build` instead of `docker-compose up`.
And then finally run `docker-compose up` | instead of
```
COPY Pipfile Pipfile.lock /code/
RUN pip install pipenv && pipenv install --system
```
you may use:
```
RUN pip install pipenv
COPY pipfile* /tmp
RUN cd /tmp && pipenv lock --requirements > requirements.txt
RUN pip install -r /tmp/requirements.txt
```
this is a snippet from [here](https://pythonspe... | 486 |
42,216,370 | Installation of python-devel fails with attached message
Configuration is as follows:
- CentOS 7.2
- Python 2.7 Installed
1. I re-ran with yum load as suggested in output and it failed with same message.
2. yum info python ==> Installed package python 2.7.5 34.el7
3. yum info python-devel ==> NOT installed. Avail... | 2017/02/14 | [
"https://Stackoverflow.com/questions/42216370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5070752/"
] | From the yum documentation, here's the safest way to handle each of your 5 errors:
First remove duplicates and resolve any errors after running this:
```
package-cleanup --cleandupes
```
If the above comes with a missing package-cleanup error, then run this first:
```
yum install yum-utils
```
Then address the o... | Removed packages python-argparse and redhat-upgrade-tool.
Then did a yum install python-devel and it succeed's this time. I am thinking there is a hard dependency for those 2 packages on older python 2.6.
Sudhir Nallagangu | 487 |
46,480,621 | I upgraded my ansible to 2.4 and now I cannot manage my CentOS 5 hosts which are running python 2.4. How do I fix it?
<http://docs.ansible.com/ansible/2.4/porting_guide_2.4.html> says ansible 2.4 will not support any versions of python lower than 2.6 | 2017/09/29 | [
"https://Stackoverflow.com/questions/46480621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4055115/"
] | After I upgraded to ansible 2.4 I was not able to manage hosts running python 2.6+. These were CentOS 5 hosts and this is how I fixed the problem.
First, I installed `python26` from epel repo. After enabling epel repo, `yum install python26`
Then in my hosts file, for the CentOS 5 hosts, I added `ansible_python_inter... | And what about python26-yum package? It is required to use yum module to install packages using Ansible. | 489 |
57,588,744 | How do you quit or halt a python program without the error messages showing?
I have tried quit(), exit(), systemexit(), raise SystemExit, and others but they all seem to raise an error message saying the program has been halted. How do I get rid of this? | 2019/08/21 | [
"https://Stackoverflow.com/questions/57588744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11939397/"
] | you can structure your program within a function then `return` when you wish to halt/end the program
ie
```
def foo():
# your program here
if we_want_to_halt:
return
if __name__ == "__main__":
foo()
``` | You would need to handle the exit in your python program.
For example:
```
def main():
x = raw_input("Enter a value: ")
if x == "a value":
print("its alright")
else:
print("exit")
exit(0)
```
Note: This works in python 2 because raw\_input is included by default there but the con... | 492 |
60,327,453 | I am new to tensorflow and Convolutional Neural Networks, and I would like to build an AI that learns to find the mode of floating point numbers. But whenever I try to run the code, I run into some errors.
Here is my code so far:
```
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers imp... | 2020/02/20 | [
"https://Stackoverflow.com/questions/60327453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Finally **SOLVED**:
**HTML:**
```
<mat-form-field>
<mat-label>Course</mat-label>
<mat-select
[formControl]="subjectControl"
[attr.data-tag]="this.subjectControl.value"
required
>
<mat-option>-- None --</mat-option>
<mat-optgroup *ngFor="l... | Your code looks correct to me. I tried adding it to an existing stackblitz example, and it showed up in the HTML. Maybe it will help to figure it out:
<https://stackblitz.com/edit/angular-material-select-compare-with?embed=1&file=app/app.html>
```
<mat-option class="mat-option ng-star-inserted" data-tag="Three" role=... | 497 |
51,878,354 | Is there a built-in function that works like zip(), but fills the results so that the length of the resulting list is the length of the longest input and fills the list **from the left** with e.g. `None`?
There is already an [answer](https://stackoverflow.com/a/1277311/2648551) using [zip\_longest](https://docs.python... | 2018/08/16 | [
"https://Stackoverflow.com/questions/51878354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648551/"
] | Use **`zip_longest`** but reverse lists.
**Example**:
```
from itertools import zip_longest
header = ["title", "firstname", "lastname"]
person_1 = ["Dr.", "Joe", "Doe"]
person_2 = ["Mary", "Poppins"]
person_3 = ["Smith"]
print(dict(zip_longest(reversed(header), reversed(person_2))))
# {'lastname': 'Poppins', 'first... | Simply use `zip_longest` and read the arguments in the reverse direction:
```
In [20]: dict(zip_longest(header[::-1], person_1[::-1]))
Out[20]: {'lastname': 'Doe', 'firstname': 'Joe', 'title': 'Dr.'}
In [21]: dict(zip_longest(header[::-1], person_2[::-1]))
Out[21]: {'lastname': 'Poppins', 'firstname': 'Mary', 'title'... | 498 |
25,438,170 | Input:
```
A B C
D E F
```
This file is NOT exclusively tab-delimited, some entries are space-delimited to look like they were tab-delimited (which is annoying). I tried reading in the file with the `csv` module using the canonical tab delimited option hoping it wouldn't mind a few spaces (needless to sa... | 2014/08/22 | [
"https://Stackoverflow.com/questions/25438170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3878253/"
] | Just use .split():
```
csv='''\
A\tB\tC
D E F
'''
data=[]
for line in csv.splitlines():
data.append(line.split())
print data
# [['A', 'B', 'C'], ['D', 'E', 'F']]
```
Or, more succinctly:
```
>>> [line.split() for line in csv.splitlines()]
[['A', 'B', 'C'], ['D', 'E', 'F']]
```
For a file, something... | Why not just roll your own splitter rather than the CSV module?
```
delimeters = [',', ' ', '\t']
unique = '[**This is a unique delimeter**]'
with open(fileName) as f:
for l in f:
for d in delimeters: l = unique.join(l.split(d))
row = l.split(unique)
``` | 504 |
46,964,509 | I am following a tutorial on using selenium and python to make a web **scraper** for twitter, and I ran into this error.
```
File "C:\Python34\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 62, in __init__
self.service.start()
File "C:\Python34\lib\site-packages\selenium\webdriver\common\service... | 2017/10/26 | [
"https://Stackoverflow.com/questions/46964509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7922147/"
] | Another way is download and uzip [chromedriver](https://chromedriver.storage.googleapis.com/index.html?path=2.33/) and put 'chromedriver.exe' in C:\Python27\Scripts and then you need not to provide the path of driver, just
```
driver= webdriver.Chrome()
```
will work | If you take a look to your exception:
```
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
```
At the [indicated url](https://sites.google.com/a/chromium.org/chromedriver/home), you can see the ... | 507 |
4,663,024 | Hey, I would like to be able to perform [this](https://stackoverflow.com/questions/638048/how-do-i-sum-the-first-value-in-each-tuple-in-a-list-of-tuples-in-python) but with being selective for which lists I sum up. Let's say, that same example, but with only adding up the first number from the 3rd and 4th list. | 2011/01/11 | [
"https://Stackoverflow.com/questions/4663024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556344/"
] | Something like:
```
sum(int(tuple_list[i][0]) for i in range(3,5))
```
range(x, y) generates a list of integers from x(included) to y(excluded) and 1 as the step. If you want to change the `range(x, y, step)` will do the same but increasing by step.
You can find the official documentation [here](http://docs.python.... | If you want to limit by some property of each element, you can use [`filter()`](http://docs.python.org/library/functions.html#filter) before feeding it to the code posted in your link. This will let you write a unique filter depending on what you want. This doesn't work for the example you gave, but it seemed like you ... | 508 |
64,773,690 | I'm new to python and I'm trying to use the census geocoding services API to geocode addresses then convert the output to a dataframe. I've been able to read in my address file and I can see the output, but I can't seem to figure out how to import it into a dataframe. I provided the code I used below as well as the con... | 2020/11/10 | [
"https://Stackoverflow.com/questions/64773690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14614221/"
] | To address both the legend and palette issue at the same time. First you could convert the data frame into long format using `pivot_longer()`, then add a column that specifies the colour you want with the associated variable. You can map those colours using `scale_colour_manual()`. Not the most elegant solution but I f... | Since @EJJ's reply did not work for some reason, I used a similar approach but using `melt()`. Here is the code and the plot:
```
colnames(df) <- c("date","Act_day","Rest_day","Act_night","Rest_night")
df <- melt(df, id.vars=c("date"))
colnames(df) <- c("date","State","value")
Plot <- ggplot(df,aes(x = date, ... | 513 |
26,345,185 | Iβm having trouble using pythonβs multiprocessing module. This is the first time Iβve tried using the module. Iβve tried simplifying my processing to the bare bones, but keep getting the same error. Iβm using python 2.7.2, and Windows 7.
The script Iβm trying to run is called `learnmp.py`, and the error message says t... | 2014/10/13 | [
"https://Stackoverflow.com/questions/26345185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2241053/"
] | I know it's been a while, but I ran into this same error, also using the version of Python distributed with ArcGIS, and I've found a solution which at least worked in my case.
The problem that I had was that I was calling my program name, Test.py, as test.py. Note the difference in case.
```
c:\python27\arcgisx6410.2... | Looks like you might be going down a rabbit-hole looking into `multiprocessing`. As the traceback shows, your python install is trying to look in the ArcGIS version of python before actually looking at your system install.
My guess is that the version of python that ships with ArcGIS is slightly customized for some re... | 514 |
74,113,894 | I have a request respond from api and it looks like this:
```
'224014@@@1;1=8.4=0;2=33=0;3=9.4=0@@@2;1=15=0;2=3.3=1;3=4.2=0;4=5.7=0;5=9.4=0;6=22=0@@@3;1=17=0;2=7.4=0;3=27=0@@@4;1=14=0;2=7.8=0;3=5.9=0;4=23=0;5=4.0=1'
```
I had splited them for your EASY READING with some explaination:
```
[1]The 6 digital numbers st... | 2022/10/18 | [
"https://Stackoverflow.com/questions/74113894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19998897/"
] | firstly, `sum` is a protected keyword since it is the list sum function, so don't call any variables "sum".
to split the string, try:
```py
sum=0
sq=""
for i in range (0+2,1000+1,2):
sum+=i
if i<1000:
sq=sq+str(i)+", "
else:
sq=sq+str(i)
if i % 40 == 0:
sq += "\n"
print(sq, end="\n")
p... | #### solution
```py
sum=0
for i in range(2,1001,2):
sum+=i
if i%20 == 2: print("\n{}".format(i),end="") # print new line per 20 numbers
else: print(", {}".format(i),end="")
print("\nSum of all even numbers within 1 and 1000 =",sum)
```
* Output:
```bash
2, 4, 6, 8, 10, 12, 14, 16, 18, 20
22, 24, 26,... | 516 |
44,211,461 | What is the fastest way to combine 100 CSV files with headers into one with the following setup:
1. The total size of files is 200 MB. (The size is reduced to make the
computation time visible)
2. The files are located on an SSD with a maximum speed of 240 MB/s.
3. The CPU has 4 cores so multi-threading and multiple p... | 2017/05/26 | [
"https://Stackoverflow.com/questions/44211461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3596337/"
] | According to the benchmarks in the question the fastest method is pure Python with undocumented "next()" function behavior with binary files. The method was proposed by [Stefan Pochmann](https://stackoverflow.com/users/1672429/stefan-pochmann)
Benchmarks:
**Benchmarks (Updated with the methods from comments and posts... | `sed` is probably the fastest. I would also propose an `awk` alternative
```
awk 'NR==1; FNR==1{next} 1' file* > output
```
prints the first line from the first file, then skips all other first lines from the rest of the files.
Timings:
I tried 10,000 lines long 100 files each around 200MB (not sure). Here is a wor... | 519 |
42,544,150 | I am using python-3.x, and I am trying to do mutation on a binary string that will flip one bit of the elements from 0 to 1 or 1 to 0 by random, I tried some methods but didn't work I don't know where is the problem:
```
x=[0, 0, 0, 0, 0]
def mutation (x, muta):
for i in range(len(x)):
if random.random() ... | 2017/03/01 | [
"https://Stackoverflow.com/questions/42544150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7632116/"
] | If you want that your object don't pass from other object then, you should use colldier without [**isTrigger**](https://docs.unity3d.com/ScriptReference/Collider-isTrigger.html) check (isTrigger should be false) and use [OnCollisionEnter](https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter.html) Eve... | you just using `Bounds` insteads of making many collider. | 520 |
18,014,633 | Consider the following simple python code:
```
f=open('raw1', 'r')
i=1
for line in f:
line1=line.split()
for word in line1:
print word,
print '\n'
```
In the first for loop i.e "for line in f:", how does python know that I want to read a line and not a word or a character?
The second loop is cleare... | 2013/08/02 | [
"https://Stackoverflow.com/questions/18014633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2625987/"
] | Python has a notation of what are called "iterables". They're things that know how to let you traverse some data they hold. Some common iterators are lists, sets, dicts, pretty much every data structure. Files are no exception to this.
The way things become iterable is by defining a method to return an object with a `... | In python the **for..in** syntax is used over iterables (elements tht can be iterated upon). For a file object, the iterator is the file itself.
Please refer [here](http://docs.python.org/release/2.5.2/lib/bltin-file-objects.html) to the documentation of **next()** method - excerpt pasted below:
>
> A file object is... | 521 |
32,127,602 | After instantiating a deck (`deck = Deck()`), calling `deck.show_deck()` just prints out "two of diamonds" 52 times. The 'copy' part is as per [this answer](https://stackoverflow.com/questions/2196956/add-an-object-to-a-python-list), but doesn't seem to help. Any suggestions?
```
import copy
from card import Card
cla... | 2015/08/20 | [
"https://Stackoverflow.com/questions/32127602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2372996/"
] | The problem here is that the `Card` class has a name variable which is shared with all instances of the `Card` class.
When you have:
```
class Card:
card_name = ''
```
This means that all `Card` objects will have the same name (`card_name`) which is almost surely not what you want.
You have to make the name b... | To expand on what shuttle87 said:
```
class Card:
card_name = ''
```
makes `card_name` a static variable (shared between all instances of that class)
Once you make the variable non-static (by using `self.card_name` in the `__init__` method) you won't have to worry about the copy part as each instance of the ca... | 522 |
47,701,629 | Is there a way to run an `ipython` like debug console in VC Code that would allow tab completion and other sort of things? | 2017/12/07 | [
"https://Stackoverflow.com/questions/47701629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2058333/"
] | Meanwhile, I have become a big fan of [PDB++](https://pypi.org/project/pdbpp/) debugger for python. It works like the iPython CLI, so I think the question has become obsolete specifically for me, but still may have some value for others. | It seems this is a desired feature for VS Code but not yet implemented. See this post: <https://github.com/DonJayamanne/vscodeJupyter/issues/19>
I'm trying to see if one could use the config file of VS Code to define an ipython debug configuration e.g.:
`{
"name": "ipython",
"type": "python",
"request": "launch",
... | 523 |
57,689,479 | I am converting pdfs to text and got this code off a previous post:
[Extracting text from a PDF file using PDFMiner in python?](https://stackoverflow.com/questions/26494211/extracting-text-from-a-pdf-file-using-pdfminer-in-python)
When I print(text) it has done exactly what I want, but then I need to save this to a ... | 2019/08/28 | [
"https://Stackoverflow.com/questions/57689479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11759292/"
] | The problem is your third argument. Third positional argument accepted by `open` is buffering, not encoding.
Call `open` like this:
```
open('GMCAECON.txt', 'w', encoding='utf-8')
```
and your problem should go away. | when you do `file = open('GMCAECON.txt', 'w', 'utf-8')` you pass positional arguments to `open()`. Third argument you pass is `encoding`, however the third argument it expect is `buffering`. You need to pass `encoding` as keyword argument, e.g.
`file = open('GMCAECON.txt', 'w', encoding='utf-8')`
Note that it's much b... | 531 |
58,466,174 | We would like to remove the key and the values from a YAML file using python, for example
```
- misc_props:
- attribute: tmp-1
value: 1
- attribute: tmp-2
value: 604800
- attribute: tmp-3
value: 100
- attribute: tmp-4
value: 1209600
name: temp_key1
attr-1: 20
attr-2: 1
- misc_props:
- a... | 2019/10/19 | [
"https://Stackoverflow.com/questions/58466174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5596456/"
] | It is not sufficient to delete a key-value pair to get your desired output.
```
import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML()
with open('input.yaml') as fp:
data = yaml.load(fp)
del data[1]['misc_props']
yaml.dump(data, sys.stdout)
```
as that gives:
```
- misc_props:
- attribute: tmp-1
value: ... | Did you try using the yaml module?
```
import yaml
with open('./old.yaml') as file:
old_yaml = yaml.full_load(file)
#This is the part of the code which filters out the undesired keys
new_yaml = filter(lambda x: x['name']!='temp_key2', old_yaml)
with open('./new.yaml', 'w') as file:
documents = yaml.dump(new... | 532 |
11,211,650 | I'm using Python 2.7 on Windows and I am writing a script that uses both time and datetime modules. I've done this before, but python seems to be touchy about having both modules loaded and the methods I've used before don't seem to be working. Here are the different syntax I've used and the errors I am currently getti... | 2012/06/26 | [
"https://Stackoverflow.com/questions/11211650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1070061/"
] | You can use **as** while importing time.
```
import time as t
from datetime import datetime
...
t.sleep(2)
``` | Don't use `from ... import *` β this is a convenience syntax for interactive use, and leads to confusion in scripts.
Here' a version that should work:
```
import time
import datetime
...
checktime = datetime.datetime.today() - datetime.timedelta(days=int(2))
checktime = checktime.timetuple()
...
filetimesecs = os.pat... | 533 |
19,034,959 | I need to install some modules for python on Ubuntu Linux 12.04. I want pygame and livewires but I'm not sure how to install them.
I have the py file for livewires, which has been specially edited (from a book I'm reading) and I want to install it but I'm not sure how to, I also want to install pygame. | 2013/09/26 | [
"https://Stackoverflow.com/questions/19034959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2765940/"
] | There are two nice ways to install Python packages on Ubuntu (and similar Linux systems):
```
sudo apt-get install python-pygame
```
to use the Debian/Ubuntu package manager APT. This only works for packages that are shipped by Ubuntu, unless you change the APT configuration, and in particular there seems to be no P... | You can use several approaches:
1 - Download the package by yourself. This is what I use the most. If the package follows the specifications, you should be able to install it by moving to its uncompressed folder and typing in the console:
```
python setup.py build
python setup.py install
```
2 - Use pip. Pip is pre... | 543 |
54,396,228 | I am trying to build a chat app with Django but when I try to run it I get this error
```
No application configured for scope type 'websocket'
```
my routing.py file is
```
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter , URLRouter
import chat.routing
application = ... | 2019/01/28 | [
"https://Stackoverflow.com/questions/54396228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10974783/"
] | Your xpath can be more specific, would suggest you go with incremental approach, first try with:
```
driver.find_element_by_xpath('//*[@id="form1"]//div[@class="screen-group-content"]')
```
If above returns True
```
driver.find_element_by_xpath('//*[@id="form1"]//div[@class="screen-group-content"]//table[@class="a... | did you have try using regular expressions?
Using **Selenium**:
```
import re
from selenium import webdriver
#n = webdriver.Firefox() or n.webdriver.Chrome()
n.get_url( your_url )
html_source_code = str(n.page_source)
# Using a regular expression
# The element that you want to fetch/collect
# will be inside of t... | 552 |
21,318,968 | I have a textfield in a database that contains the results of a python `json.dumps(list_instance)` operation. As such, the internal fields have a `u'` prefix, and break the browser's `JSON.parse()` function.
An example of the JSON string is
```
"density": "{u'Penobscot': 40.75222856500098, u'Sagadahoc':
122.270833... | 2014/01/23 | [
"https://Stackoverflow.com/questions/21318968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214892/"
] | Updated solution: `replace(/u'/g, "'"));` => `replace(/u'(?=[^:]+')/g, "'"));`.
Tested with the following:
`"{u'Penobscot': 40.75222856500098, u'Sagadahoc': 122.27083333333333, u'Lincoln': 67.97977755308392, u'Kennebec': 123.12237174095878, u'Waldo': 48.02117802779616, u'Cumberland': 288.9285325791363, u'Piscataquis'... | a little bit old in the answer but if there is no way to change or access the server response try with:
```
var strExample = {'att1':u'something with u'};
strExample.replace(/u'[\}|\,]/g, "Γ§'").replace(/u'/g, "'").replace(/Γ§'/g, "u'");
//{'att1':'something with u'};
```
The first replace will handle the u' that ar... | 555 |
20,332,359 | Im trying to use python's default logging module in a multiprocessing scenario.
I've read:
1. [Python MultiProcess, Logging, Various Classes](https://stackoverflow.com/questions/17582155/python-multiprocess-logging-various-classes)
2. [Logging using multiprocessing](https://stackoverflow.com/questions/10665090/logging... | 2013/12/02 | [
"https://Stackoverflow.com/questions/20332359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3057996/"
] | I'm coming late, so you probably don't need the answer anymore. The problem comes from the fact that you already have a handler set in your main process, and in your worker you are adding another one. This means that in your worker process, two handlers are in fact managing your data, the one in pushing the log to queu... | All your `Worker`s share the same root logger object (obtained in `Worker.__init__` -- the `getLogger` call always returns the same logger). However, every time you create a `Worker`, you add a handler (`QueueHandler`) to that logger.
So if you create 10 Workers, you will have 10 (identical) handlers on your root logg... | 559 |
32,209,155 | I'm working through <http://www.mypythonquiz.com>, and [question #45](http://www.mypythonquiz.com/question.php?qid=255) asks for the output of the following code:
```
confusion = {}
confusion[1] = 1
confusion['1'] = 2
confusion[1.0] = 4
sum = 0
for k in confusion:
sum += confusion[k]
print sum
```
The output i... | 2015/08/25 | [
"https://Stackoverflow.com/questions/32209155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2401331/"
] | First of all: the behaviour is documented explicitly in the docs for the [hash](https://docs.python.org/3.5/library/functions.html#hash) function:
>
> **`hash(object)`**
>
>
> Return the hash value of the object (if it has one). Hash values are
> integers. They are used to quickly compare dictionary keys during a
... | Frankly, the opposite is dangerous! `1 == 1.0`, so it's not improbable to imagine that if you had them point to different keys and tried to access them based on an evaluated number then you'd likely run into trouble with it because the ambiguity is hard to figure out.
Dynamic typing means that the value is more import... | 562 |
8,758,354 | I've been using Python 3 for some months and I would like to create some GUIs. Does anyone know a good GUI Python GUI framework I could use for this?
I don't want to use [TkInter](http://wiki.python.org/moin/TkInter) because I don't think it's very good. I also don't want to use [PyQt](http://wiki.python.org/moin/PyQt... | 2012/01/06 | [
"https://Stackoverflow.com/questions/8758354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1114830/"
] | Hummm. . . .
Hard to believe that Qt is forbidden for commercial use, as it has been created by some of the most important companies in the world . . . <http://qt.nokia.com/>
Go for pyQt ;) | Pyside might be the best bet for you :
<http://www.pyside.org/>
It is basically Qt but under the LGPL license, which means you can use it in your commercial application. | 572 |
68,935,814 | I would like to know how to run the following cURL request using python (I'm working in Jupyter notebook):
```
curl -i -X GET "https://graph.facebook.com/{graph-api-version}/oauth/access_token?
grant_type=fb_exchange_token&
client_id={app-id}&
client_secret={app-secret}&
fb_exchange_token={your-access-toke... | 2021/08/26 | [
"https://Stackoverflow.com/questions/68935814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16757711/"
] | `decode(String)` returns a `byte[]`, you need to convert that to a string using a `String` constructor and not the `toString()` method:
```java
byte[] bytes = java.util.Base64.getDecoder().decode(encodedstring);
String s = new String(bytes, java.nio.charset.StandardCharsets.UTF_8);
``` | It looks like you need mime decoder message
```js
java.util.Base64.Decoder decoder = java.util.Base64.getMimeDecoder();
// Decoding MIME encoded message
String dStr = new String(decoder.decode(encodedstring));
System.out.println("Decoded message: "+dStr);
``` | 580 |
58,706,091 | I am using cplex .dll file in python to solve a well-formulated lp problem using pulp solver. Here is the code
here model is pulp object created using pulp library
====================================================
When I run a.actualSolve(Model) I get following error from subprocess.py file.
OSError: [WinError 19... | 2019/11/05 | [
"https://Stackoverflow.com/questions/58706091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6369726/"
] | Like the error says, you need to put the closing curly brace on the same line as the subsequent block after the `else`:
```
if (err.status === 'not found') {
cb({ statusCode: 404 })
return
} else { // <--- now } is on same line as {
cb({ statusCode: 500 })
return
}
```
From an example from [the docs](https... | **Use below format when you face above error in typescript eslint.**
```
if (Logic1) {
//content1
} else if (Logic2) {
//content2
} else if (Logic3) {
//content3
} else {
//content4
}
``` | 581 |
6,369,697 | When I run `python manage.py shell`, I can print out the python path
```
>>> import sys
>>> sys.path
```
What should I type to introspect all my django settings ? | 2011/06/16 | [
"https://Stackoverflow.com/questions/6369697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/450278/"
] | ```
from django.conf import settings
dir(settings)
```
and then choose attribute from what `dir(settings)` have shown you to say:
```
settings.name
```
where `name` is the attribute that is of your interest
Alternatively:
```
settings.__dict__
```
prints all the settings. But it prints also the module standard... | To show all django settings (including default settings not specified in your local settings file):
```
from django.conf import settings
dir(settings)
``` | 582 |
8,114,826 | Hi I'm working on converting perl to python for something to do.
I've been looking at some code on hash tables in perl and I've come across a line of code that I really don't know how it does what it does in python. I know that it shifts the bit strings of page by 1
```
%page_table = (); #page table is a h... | 2011/11/13 | [
"https://Stackoverflow.com/questions/8114826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044593/"
] | The only thing confusing is that page table is a hash of hashes. $page\_table{$v} contains a hashref to a hash that contains a key 'page' whose value is an integer. The loop bitshifts that integer but is not very clear perl code. Simpler would be:
```
foreach my $v (@ram) {
$page_table{$v}->{page} >>= 1;
}
```
N... | Woof! No wonder you want to try Python!
Yes, Python can do this because Python dictionaries (what you'd call hashes in Perl) can contain other arrays or dictionaries without doing references to them.
However, I **highly** suggest that you look into moving into object oriented programming. After looking at that assign... | 591 |
62,393,428 | ```
drivers available with me
**python shell**
'''In [2]: pyodbc.drivers()'''
**Output:**
**Out[2]: ['SQL Server']**
code in settings.py django:
**Settings.py in django**
'''# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
... | 2020/06/15 | [
"https://Stackoverflow.com/questions/62393428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13458554/"
] | Though the documentation suggests using the framework `SearchView`, I've always found that the support/androidx `SearchView` plays nicer with the library components β e.g., `AppCompatActivity`, `MaterialToolbar`, etc. β though I'm not sure exactly what causes these little glitches. Indeed, using `androidx.appcompat.wid... | the above method does not work for me. I don't know why but a tried this and succeed.
Refer to the search hint icon through SearchView and set it's visibility to GONE:
```
ImageView icon = (ImageView) mSearchView.findViewById(androidx.appcompat.R.id.search_mag_icon);
icon.setVisibility(View.GONE);
```
And then add t... | 594 |
28,986,131 | I need to load 1460 files into a list, from a folder with 163.360 files.
I use the following python code to do this:
```
import os
import glob
Directory = 'C:\\Users\\Nicolai\\Desktop\\sealev\\dkss_all'
stationName = '20002'
filenames = glob.glob("dkss."+stationName+"*")
```
This has been running fine so far, but... | 2015/03/11 | [
"https://Stackoverflow.com/questions/28986131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1972356/"
] | Presuming that `ls` on that same directory is just as slow, you can't reduce the total time needed for the directory listing operation. Filesystems are slow sometimes (which is why, yes, the operating system *does* cache directory entries).
However, there actually *is* something you can do in your Python code: You can... | Yes, it is a caching thing. Your harddisk is a slow peripheral, reading 163.360 filenames from it can take some time. Yes, your operating system caches that kind of information for you. Python has to wait for that information to be loaded before it can filter out the matching filenames.
You don't have to wait all that... | 595 |
21,869,675 | ```
list_ = [(1, 'a'), (2, 'b'), (3, 'c')]
item1 = 1
item2 = 'c'
#hypothetical:
assert list_.index_by_first_value(item1) == 0
assert list_.index_by_second_value(item2) == 2
```
What would be the fastest way to emulate the `index_by_first/second_value` method in python?
If you don't understand what's going on; if you... | 2014/02/19 | [
"https://Stackoverflow.com/questions/21869675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3002473/"
] | At first, I thought along [the same lines as Nick T](https://stackoverflow.com/a/21869852/418413). Your method is fine if the number of tuples (N) is short. But of course a linear search is O(N). As the number of tuples increases, the time increases directly with it. You can get O(1) lookup time with a dict mapping the... | Searching a list is O(n). Convert it to a dictionary, then lookups take O(1).
```
>>> list_ = [(1, 'a'), (2, 'b'), (3, 'c')]
>>> dict(list_)
{1: 'a', 2: 'b', 3: 'c'}
>>> dict((k, v) for v, k in list_)
{'a': 1, 'c': 3, 'b': 2}
```
If you want the original index you could enumerate it:
```
>>> dict((kv[0], (i, kv[1])... | 596 |
36,584,975 | I've a little problem with my code.
I tried to rewrite code from python to java.
In Python it's:
```
data = bytearray(filesize)
f.readinto(data)
```
Then I tried to write it in java like this:
```
try {
data = Files.readAllBytes(file.toPath());
} catch (IOException ex) {
Logger.getLogger(Encryp... | 2016/04/12 | [
"https://Stackoverflow.com/questions/36584975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6195753/"
] | Since `@metrics` is an array, it doesn't look like you're calling any code on your model at all so your model code isn't actually doing anything.
This code your controller will generate the output you're looking for:
```
CSV.generate do |csv|
@metrics.each { |item| csv << [item] }
end
``` | This is just a guess, but try formatting `@metrics` as an array of arrays: so each element of `@metrics` is its own array. It seems likely that `to_csv` treats an array like a row, so you need an array of arrays to generate new lines.
```
[["Group Name,1"], ["25"], ["44,2,5"]]
```
**UPDATE**
Looking at your code ag... | 604 |
31,767,709 | What's a good command from term to render all images in a dir into one browser window?
Looking for something like this:
`python -m SimpleHTTPServer 8080`
But instead of a list ...
... Would like to see **all the images rendered in a single browser window**, just flowed naturally, at natural dimensions, just scroll ... | 2015/08/02 | [
"https://Stackoverflow.com/questions/31767709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1618304/"
] | I found a perl CGI script to do this:
```
#!/usr/bin/perl -wT
# myscript.pl
use strict;
use CGI;
use Image::Size;
my $q = new CGI;
my $imageDir = "./";
my @images;
opendir DIR, "$imageDir" or die "Can't open $imageDir $!";
@images = grep { /\.(?:png|gif|jpg)$/i } readdir DIR;
# @images = grep { /\.(?:png|g... | This is quite easy, you can program something like this in a couple of minutes.
Just create an array of all the images in ./ create a var s = '' and appen for each img in ./ '>
' and send it to the webbrowser the server->google is your friend | 605 |
41,708,458 | I have many bash scripts to help set my current session environment variables. I need the env variables set so I can use the subprocess module to run commands in my python scripts. This is how I execute the bash scripts:
```
. ./file1.sh
```
Below is the beginning of the bash script:
```
echo "Setting Environment V... | 2017/01/17 | [
"https://Stackoverflow.com/questions/41708458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7259469/"
] | ### Using `shell=True` With Your Existing Script
First, in terms of the *very simplest thing* -- if you're using `shell=True`, you can tell the shell that starts to run the contents of your preexisting script unmodified.
That is to say -- if you were initially doing this:
```
subprocess.Popen(['your-command', 'arg1'... | You should consider the Python builtin `os` [module](https://docs.python.org/2/library/os.html). The attribute
`os.environ` is a dictionary of environment variables that you can *read*, e.g.
```
import os
os.environ["USER"]
```
You cannot, however, *write* bash environment variables from the child process (see e.g.,... | 606 |
58,225,904 | I have a multiline string in python that looks like this
```
"""1234 dog list some words 1432 cat line 2 1789 cat line3 1348 dog line 4 1678 dog line 5 1733 fish line 6 1093 cat more words"""
```
I want to be able to group specific lines by the animals in python. So my output would look like
```
dog
1234 dog list ... | 2019/10/03 | [
"https://Stackoverflow.com/questions/58225904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9476376/"
] | >
> Or maybe there is a simpler way of archiving this?
>
>
>
Consider *option would be to have a function for each type* that is called by *the same function*.
```
void testVariableInput_int(const int *a, const int *b, int *out, int m) {
while (m > 0) {
m--;
out[m] = a[m] + b[m];
}
}
// Like-wise for... | >
> Or maybe there is a simpler way of achieving this?
>
>
>
I like function pointers. Here we can pass a function pointer that adds two elements. That way we can separate the logic of the function from the abstraction that handles the types.
```
#include <stdlib.h>
#include <stdio.h>
void add_floats(const void ... | 608 |
64,771,870 | I am using a colab pro TPU instance for the purpose of patch image classification.
i'm using tensorflow version 2.3.0.
When calling model.fit I get the following error: `InvalidArgumentError: Unable to find the relevant tensor remote_handle: Op ID: 14738, Output num: 0` with the following trace:
```
--------
InvalidA... | 2020/11/10 | [
"https://Stackoverflow.com/questions/64771870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8777119/"
] | @Pooya448
I know this is quite late, but this may be useful for anyone stuck here.
Following is the function I use to connect to TPUs.
```py
def connect_to_tpu(tpu_address: str = None):
if tpu_address is not None: # When using GCP
cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(
... | I actually tried all the methods that are suggested in git and stackoverflow none of them worked for me. But what worked is I created a new notebook and connected it to the TPU and trained the model. It worked fine, so may be this is related to the problem of the notebook at the time when we created it. | 609 |
32,017,621 | I would like to connect and receive http response from a specific web site link.
I have many Python codes :
```
import urllib.request
import os,sys,re,datetime
fp = urllib.request.urlopen("http://www.python.org")
mybytes = fp.read()
mystr = mybytes.decode(encoding=sys.stdout.encoding)
fp.close()
```
when I pass th... | 2015/08/14 | [
"https://Stackoverflow.com/questions/32017621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5228214/"
] | first of all: <https://docs.python.org/2/tutorial/classes.html#inheritance>
At any rate...
```
GParent.testmethod(self) <-- calling a method before it is defined
class GParent(): <-- always inherit object on your base class to ensure you are using new style classes
def testmethod(self):
print "This is te... | You cannot call GParent's `testmethod` without an instance of `GParent` as its first argument.
**Inheritance**
```
class GParent(object):
def testmethod(self):
print "I'm a grandpa"
class Parent(GParent):
# implicitly inherit __init__() ... | 610 |
56,711,890 | If I had a function that had three or four optional keyword arguments is it best to use \*\*kwargs or to specify them in the function definition?
I feel as
`def foo(required, option1=False, option2=False, option3=True)`
is much more clumsy looking than
`def foo(required, **kwargs)`.
However if I need to use these ke... | 2019/06/22 | [
"https://Stackoverflow.com/questions/56711890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10206378/"
] | If the function is only using the parameters in its own operation, you should list them all explicitly. This will allow Python to detect if an invalid argument was provided in a call to your function.
You use `**kwargs` when you need to accept dynamic parameters, often because you're passing them along to other functi... | One easy way to pass in several optional parameters while keeping your function definition clean is to use a dictionary that contains all the parameters. That way your function becomes
```py
def foo(required, params):
print(required)
if 'true' in params and params['true']:
print(params['true'])
```
Y... | 611 |
26,625,845 | I work on a project in which I need a python web server. This project is hosted on Amazon EC2 (ubuntu).
I have made two unsuccessful attempts so far:
1. run `python -m SimpleHTTPServer 8080`. It works if I launch a browser on the EC2 instance and head to localhost:8080 or <*ec2-public-IP*>:8080. However I can't acces... | 2014/10/29 | [
"https://Stackoverflow.com/questions/26625845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3592547/"
] | you should open the 8080 port and ip limitation in security croups, such as:
All TCP TCP 0 - 65535 0.0.0.0/0
the last item means this server will accept every request from any ip and port, you also | You passble need to `IAM` in `AWS`.
`Aws` set security permission that need to open up port so you only `localhost` links your webservice
[aws link](http://aws.amazon.com/) | 612 |
51,733,698 | I have a program that right now grabs data like temperature and loads using a powershell script and the WMI. It outputs the data as a JSON file. Now let me preface this by saying this is my first time every working with JSON's and im not very familiar with the JSON python library. Here is the code to my program:
```
i... | 2018/08/07 | [
"https://Stackoverflow.com/questions/51733698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9801535/"
] | You can build a new dictionary in the shape you want like this:
```
...
data = {
element["Name"]: {
key: value for key, value in element.items() if key != "Name"
}
for element in json.loads(output)
}
fdata = json.dumps(data, indent=4)
...
```
Result:
```
{
"Memory": {
"SensorType": "... | ```
x="""[
{
"Name": "Memory 1",
"SensorType": "Load",
"Value": 53.3276978
},
{
"Name": "CPU Core #2",
"SensorType": "Load",
"Value": 53.3276978
}]"""
json_obj=json.loads(x)
new_list=[]
for item in json_obj:
name=item.pop('Name')
new_list.append({name:item})
print(json.dumps(n... | 613 |
24,888,691 | Well, I finally got cocos2d-x into the IDE, and now I can make minor changes like change the label text.
But when trying to add a sprite, the app crashes on my phone (Galaxy Ace 2), and I can't make sense of the debug output.
I followed [THIS](http://youtu.be/2LI1IrRp_0w) video to set up my IDE, and i've literally ju... | 2014/07/22 | [
"https://Stackoverflow.com/questions/24888691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3863962/"
] | ```
var new= "\"" + string.Join( "\",\"", keys) + "\"";
```
To include a double quote in a string, you escape it with a backslash character, thus "\"" is a string consisting of a single double quote character, and "\", \"" is a string containing a double quote, a comma, a space, and another double quote. | If performance is the key, you can always use a `StringBuilder` to concatenate everything.
[Here's a fiddle](https://dotnetfiddle.net/nptVEH) to see it in action, but the main part can be summarized as:
```
// these look like snails, but they are actually pretty fast
using @_____ = System.Collections.Generic.IEnumera... | 620 |
6,990,760 | I wrapped opencv today with simplecv python interface. After going through the official [SimpleCV Cookbook](http://simplecv.org/doc/cookbook.html) I was able to successfully [Load, Save](http://simplecv.org/doc/cookbook.html#loading-and-saving-images), and [Manipulate](http://simplecv.org/doc/cookbook.html#image-manipu... | 2011/08/09 | [
"https://Stackoverflow.com/questions/6990760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568884/"
] | since the error raised from Camera.py of SimpleCV, you need to debug the getImage() method. If you can edit it:
```
def getImage(self):
if (not self.threaded):
cv.GrabFrame(self.capture)
frame = cv.RetrieveFrame(self.capture)
import pdb # <-- add this line
pdb.set_trace() # <-- add this... | I'm geting the camera with OpenCV
```
from opencv import cv
from opencv import highgui
from opencv import adaptors
def get_image()
cam = highgui.cvCreateCameraCapture(0)
im = highgui.cvQueryFrame(cam)
# Add the line below if you need it (Ubuntu 8.04+)
#im = opencv.cvGetMat(im)
return im
``` | 622 |
69,383,255 | I am trying to calculate the distance between 2 points in python using this code :
```
import math
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Point({0}, {1})".format(self.x, self.y)
def __sub__(self, other):
return Point(... | 2021/09/29 | [
"https://Stackoverflow.com/questions/69383255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16743649/"
] | ```
let newFavorites = favorites;
```
This assigns newFavorites to point to favorites
```
newFavorites.push(newFav);
```
Because newFavorites points to favorites, which is an array in `state`, you can't push anything onto it and have that change render.
What you need to do, is populate a new array `newFavorites` ... | I would make some changes in your addFavourite function:
function addFavorite(name, id) {
let newFav = {name, id};
```
setFavorites([β¦favourites, newFav]);
```
}
This way, everytime you click favourite, you ensure a new array is being created with spread operator | 628 |
40,634,826 | I'm using Swig 3.0.7 to create python 2.7-callable versions of C functions that define constants in this manner:
```c
#define MYCONST 5.0
```
In previous versions of swig these would be available to python transparently:
```py
import mymodule
x = 3. * mymodule.MYCONST
```
But now this generates a message
```no... | 2016/11/16 | [
"https://Stackoverflow.com/questions/40634826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3263972/"
] | You can use [`split`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html), then cast column `year` to `int` and if necessary add `Q` to column `q`:
```
df = pd.DataFrame({'date':['2015Q1','2015Q2']})
print (df)
date
0 2015Q1
1 2015Q2
df[['year','q']] = df.date.str.split('Q', exp... | You could also construct a datetimeIndex and call year and quarter on it.
```
df.index = pd.to_datetime(df.date)
df['year'] = df.index.year
df['quarter'] = df.index.quarter
date year quarter
date
2015-01-01 2015Q1 2015 1
2015-04-01 2015Q2 2015 2
```
Not... | 634 |
51,567,959 | I am sort of new to python. I can open files in Windows with but am having trouble in Mac. I can open webbrowsers but I am unsure as to how I open other programs or word documents.
Thanks | 2018/07/28 | [
"https://Stackoverflow.com/questions/51567959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10147138/"
] | use this class `col-md-auto` to make width auto and `d-inline-block` to display column inline block (bootstrap 4)
```
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-md-auto col-lg-auto d-inline-block">
<label for="name">Com... | I think that you can see the example below,this may satisfy your need. Also,you can set the col-x-x property to place more that 3 input in one row.
[row-col example](http://%20https://v3.bootcss.com/components/#input-groups-buttons) | 635 |
63,627,160 | 1. I am trying to get a students attendance record set up in python. I have most of it figured out. I am stuck on one section and it is the attendane section. I am trying to use a table format (tksheets) to keep record of students names and their attendance. The issue I am having is working with tksheets. I can't seem ... | 2020/08/28 | [
"https://Stackoverflow.com/questions/63627160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4049491/"
] | Try Something like this-
```
';SELECT text
FROM notes
WHERE username = 'alice
``` | SQL Injection can be implemented by concatenating the SQL statement with the input parameters. For example, the following statement is vulnerable to SQL Injection:
```
String statement = "SELECT ID FROM USERS WHERE USERNAME = '" + inputUsername + "' AND PASSWORD = '" + hashedPassword + "'";
```
An attacker would en... | 636 |
63,283,368 | I've got the problem during setting up deploying using cloudbuild and dockerfile.
My `Dockerfile`:
```
FROM python:3.8
ARG ENV
ARG NUM_WORKERS
ENV PORT=8080
ENV NUM_WORKERS=$NUM_WORKERS
RUN pip install poetry
COPY pyproject.toml poetry.lock ./
RUN poetry config virtualenvs.create false && \
poetry install --no... | 2020/08/06 | [
"https://Stackoverflow.com/questions/63283368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11993534/"
] | Here is a working example of how you would attach the value of a configuration trait to another pallet's storage item.
Pallet 1
--------
Here is `pallet_1` which has the storage item we want to use.
>
> NOTE: This storage is marked `pub` so it is accessible outside the pallet.
>
>
>
```rust
use frame_support::{... | It is actually as creating a trait impl the struct and then in the runtime pass the struct to the receiver (by using the trait), what I did to learn this is to look at all of the pallets that are already there and see how the pass information
for instance this trait in authorship
<https://github.com/paritytech/substra... | 637 |
30,902,443 | I'm using vincent a data visualization package. One of the inputs it takes is path to data.
(from the documentation)
```
`geo_data` needs to be passed as a list of dicts with the following
| format:
| {
| name: data name
| url: path_to_data,
| feature: TopoJSON object s... | 2015/06/17 | [
"https://Stackoverflow.com/questions/30902443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4682755/"
] | It seems that you're using it in Jupyter Notebook. If no, my reply is irrelevant for your case.
AFAIK, vincent needs this topojson file to be available through web server (so javascript from your browser will be able to download it to build the map). If the topojson file is somewhere in the Jupyter root dir then it's ... | I know that this post is old, hopefully this helps someone. I am not sure what map you are looking for, but here is the URL for the world map
```
world_topo="https://raw.githubusercontent.com/wrobstory/vincent_map_data/master/world-countries.topo.json"
```
and the USA state maps
```
state_topo = "https://raw.github... | 638 |
17,975,795 | I'm sure this must be simple, but I'm a python noob, so I need some help.
I have a list that looks the following way:
```
foo = [['0.125', '0', 'able'], ['', '0.75', 'unable'], ['0', '0', 'dorsal'], ['0', '0', 'ventral'], ['0', '0', 'acroscopic']]
```
Notice that every word has 1 or 2 numbers to it. I want to substr... | 2013/07/31 | [
"https://Stackoverflow.com/questions/17975795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2001008/"
] | `''` cannot be converted to string.
```
bar = []
for a,b,c in foo:
d = float(a or 0) - float(b or 0)
bar.append((c,d))
```
However, that will not make a dictionary. For that you want:
```
bar = {}
for a,b,c in foo:
d = float(a or 0)-float(b or 0)
bar[c] = d
```
Or a shorter way using dictionary co... | Add a condition to verify if the string is empty like that '' and convert it to 0 | 639 |
21,188,579 | I'm stuck in a exercice in python where I need to convert a DNA sequence into its corresponding amino acids. So far, I have:
```
seq1 = "AATAGGCATAACTTCCTGTTCTGAACAGTTTGA"
for i in range(0, len(seq), 3):
print seq[i:i+3]
```
I need to do this without using dictionaries, and I was going for replace, but it seems... | 2014/01/17 | [
"https://Stackoverflow.com/questions/21188579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2884400/"
] | To translate you need a table of [codons](http://en.wikipedia.org/wiki/DNA_codon_table), so without dictionary or other data structure seems strange.
Maybe you can look into [biopython](http://biopython.org/DIST/docs/tutorial/Tutorial.html#sec26)? And see how they manage it.
You can also translate directly from the c... | You cannot practically do this without either a function or a dictionary. Part 1, converting the sequence into three-character codons, is easy enough as you have already done it.
But Part 2, to convert these into amino acids, you will need to define a mapping, either:
```
mapping = {"NNN": "X", ...}
```
or
```
def... | 643 |
37,986,367 | How I can overcome an issue with conditionals in python? The issue is that it should show certain text according to certain conditional, but if the input was No, it anyway indicates the data of Yes conditional.
```
def main(y_b,c_y):
ans=input('R u Phil?')
if ans=='Yes' or 'yes':
years=y_b-c_y
... | 2016/06/23 | [
"https://Stackoverflow.com/questions/37986367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6492505/"
] | `or` is inclusive. So the `yes` test will always pass because when `ans != 'Yes'` the other condition `yes` has a truthy value.
```
>>> bool('yes')
True
```
You should instead test with:
```
if ans in ('Yes', 'yeah', 'yes'):
# code
elif ans in ('No', 'Nah', 'no'):
# code
else:
# more code
``` | When you write if statements and you have multiple conditionals, you have to write both conditionals and compare them. This is wrong:
```
if ans == 'Yes' or 'yes':
```
and this is ok:
```
if ans == 'Yes' or ans == 'yes':
``` | 648 |
49,021,968 | I have a list of filenames in a directory and I'd like to keep only the latest versions. The list looks like:
`['file1-v1.csv', 'file1-v2.csv', 'file2-v1.txt', ...]`.
I'd like to only keep the newest csv files as per the version (part after `-` in the filename) and the txt files.
The output would be `[''file1-v2.... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49021968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2771315/"
] | Do this:
```
SELECT * FROM yourTable
WHERE DATE(punch_in_utc_time)=current_date;
```
For testing:
```
SELECT DATE("2018-02-28 09:32:00")=current_date;
```
See [DEMO on SQL Fiddle](http://sqlfiddle.com/#!9/9eecb/17666). | Should be able to do that using Date function, TRUNC timestamp to date then compare with the date field.
```
SELECT DATE("2018-02-28 09:32:00") = "2018-02-28";
```
The above dml will return 1 since the date part is equal. | 651 |
56,227,936 | I am getting the following error when I try to see if my object is valid using `full_clean()`.
```sh
django.core.exceptions.ValidationError: {'schedule_date': ["'%(value)s' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]}
```
I have tried all the formats recommended here, but ... | 2019/05/20 | [
"https://Stackoverflow.com/questions/56227936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9633315/"
] | The issue was with the logic of the code. I specified the time range that won't allow even one millionth second difference in the `schedule_date` and `timezone.now()`
After taking a look at the source code of `DateTimeField`, it seems like if I have my validator to throw code="invalid", it will just show the above err... | i solve this problem with this
```
datetime.strptime(request.POST['date'], "%Y-%m-%dT%H:%M")
``` | 654 |
64,799,578 | I am working on a python script, where I will be passing a directory, and I need to get all log-files from it. Currently, I have a small script which watches for any changes to these files and then processes that information.
It's working good, but it's just for a single file, and hardcoded file value. How can I pass ... | 2020/11/12 | [
"https://Stackoverflow.com/questions/64799578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1510701/"
] | You could use a generic / reusable approach based on the two-queries approach.
One SQL query to retrieve the entities' `IDs` and a second query with an `IN` predicate including the `IDs` from the second query.
Implementing a custom Spring Data JPA Executor:
```
@NoRepositoryBean
public interface AsimioJpaSpecificati... | I found a workaround myself. Based upon this:
[How can I avoid the Warning "firstResult/maxResults specified with collection fetch; applying in memory!" when using Hibernate?](https://stackoverflow.com/questions/11431670/how-can-i-avoid-the-warning-firstresult-maxresults-specified-with-collection-fe/46195656#4619565... | 655 |
28,814,455 | I am appending a file via python based on the code that has been input by the user.
```
with open ("markbook.txt", "a") as g:
g.write(sn+","+sna+","+sg1+","+sg2+","+sg3+","+sg4)
```
`sn`, `sna`, `sg1`, `sg2`, `sg3`, `sg4` have all been entered by the user and when the program is finished a line will be adde... | 2015/03/02 | [
"https://Stackoverflow.com/questions/28814455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4624147/"
] | Add a "\n" to the end of the write line.
So:
```
g.write(sn+","+sna+","+sg1+","+sg2+","+sg3+","+sg4+"\n")
``` | You're missing the new line character at the end of your string. Also, though string concatenation is completely fine in this case, you should be aware that Python has alternative options for formatting strings.
```
with open('markbook.txt', 'a') as g:
g.write('{},{},{},{},{},{}\n'
.format(s... | 657 |
37,518,997 | My question is related to this earlier question - [Python subprocess usage](https://stackoverflow.com/questions/17242828/python-subprocess-and-running-a-bash-script-with-multiple-arguments)
I am trying to run this command using python
**nccopy -k 4 "<http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysi... | 2016/05/30 | [
"https://Stackoverflow.com/questions/37518997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4033876/"
] | There's two dilemmas here.
One being that subprocess processes your arguments and tries to use `4` as a separate argument.
The other being that system calls still goes under normal shell rules, meaning that parameters and commands will be parsed for [metacharacters](http://www.tutorialspoint.com/unix/unix-quoting-m... | Instead of arg1 = "-k 4", use two arguments instead.
```
import subprocess
url = 'http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis2/pressure/air.2014.nc?air[408:603][2][20:34][26:40]'
outputFile = 'foo.nc'
arg1 = "-k"
arg2 = "4"
arg3 = url
arg4 = outputFile
subprocess.check_call(["nccopy", arg1... | 659 |
54,677,761 | The following code generates the warning in tensorflow r1.12 python API:
```
#!/usr/bin/python3
import tensorflow as tf
M = tf.keras.models.Sequential();
M.add(tf.keras.layers.Dense(2));
```
The complete warning text is this:
```
WARNING: Logging before flag parsing goes to stderr.
W0213 15:50:07.239809 140701996... | 2019/02/13 | [
"https://Stackoverflow.com/questions/54677761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7906266/"
] | You are running tensor flow 2.0 and it looks like VarianceScaling.**init** is deprecated. It might mean that Sequential will need to be more explicitly initialized in the future.
for example:
```py
model = tf.keras.Sequential([
# Adds a densely-connected layer with 64 units to the model:
layers.Dense(64, activation='... | This is just a warning based on the [changes in Tensorflow 2.0](https://www.tensorflow.org/beta/guide/effective_tf2).
If you don't want to see these warnings, upgrade to TensorFlow 2.0. You can install the beta version via pip:
```
pip install tensorflow==2.0.0-beta1
``` | 662 |
2,641,665 | I've got a Django app that accepts uploads from [jQuery uploadify](http://www.uploadify.com/), a jQ plugin that uses flash to upload files and give a progress bar.
Files under about 150k work, but bigger files always fail and almost always at around 192k (that's 3 chunks) completed, sometimes at around 160k. The Excep... | 2010/04/14 | [
"https://Stackoverflow.com/questions/2641665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/246265/"
] | Html.DropDownList() accepts a SelectList as a parameter which has a SelectedValue property. Specify the selected item when you create the SelectList and pass the SelectList to the Html.DropDownList(). | Here's an example that has 7 drop downs on the page, each with the same 5 options. Each drop down can have a different option selected.
In my view, I have the following code inside my form:
```
<%= Html.DropDownListFor(m => m.ValueForList1, Model.AllItems)%>
<%= Html.DropDownListFor(m => m.ValueForList2, Model.AllIte... | 664 |
73,662,597 | I have setup Glue Interactive sessions locally by following <https://docs.aws.amazon.com/glue/latest/dg/interactive-sessions.html>
However, I am not able to add any additional packages like HUDI to the interactive session
There are a few magic commands to use but not sure which one is apt and how to use
```
%addition... | 2022/09/09 | [
"https://Stackoverflow.com/questions/73662597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19958017/"
] | It is a bit hard t understand what problem you are actually facing, as this is very basic SQL.
Use `EXISTS`:
```
select *
from a
where type = 'F'
and exists (select null from b where b.id = a.id and dt >= date '2022-01-01');
```
Or `IN`:
```
select *
from a
where type = 'F'
and id in (select id from b where dt >= ... | ```
SELECT *
FROM A
WHERE type='F'
AND id IN (
SELECT id
FROM B
WHERE DATE>='2022-01-01'; -- '2022' imo should be enough, need to check
);
```
I don't think joining is necessary. | 667 |
48,497,092 | I implement multiple linear regression from scratch but I did not find slope and intercept, gradient decent give me nan value.
Here is my code and I also give ipython notebook file.
<https://drive.google.com/file/d/1NMUNL28czJsmoxfgeCMu3KLQUiBGiX1F/view?usp=sharing>
```
import pandas as pd
import numpy as np
import... | 2018/01/29 | [
"https://Stackoverflow.com/questions/48497092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5107898/"
] | This is not a programming issue, but an issue of your function. [Numpy can use different data types](https://docs.scipy.org/doc/numpy-1.10.1/user/basics.types.html). In your case it uses float64. You can check the largest number, you can represent with this data format:
```
>>>sys.float_info
>>>sys.float_info(max=1.79... | try scaling your x
```py
def scale(x):
for j in range(x.shape[1]):
mean_x = 0
for i in range(len(x)):
mean_x += x[i,j]
mean_x = mean_x / len(x)
sum_of_sq = 0
for i in range(len(x)):
sum_of_sq += (x[i,j] - mean_x)**2
stdev = sum_of_sq / (x.shap... | 668 |
70,964,456 | I had an issue like this on my Nano:
```
profiles = [ SERIAL_PORT_PROFILE ],
File "/usr/lib/python2.7/site-packages/bluetooth/bluez.py", line 176, in advertise_service
raise BluetoothError (str (e))
bluetooth.btcommon.BluetoothError: (2, 'No such file or directory')
```
I tried adding compatibility mode in the... | 2022/02/03 | [
"https://Stackoverflow.com/questions/70964456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18104741/"
] | You might want to have a look at the following article which shows how to do the connection with core Python Socket library
<https://blog.kevindoran.co/bluetooth-programming-with-python-3/>.
The way BlueZ does this now is with the [Profile](https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/profile-api.txt) A... | The solution was in the path of the bluetooth configuration file (inspired from this <https://developer.nvidia.com/embedded/learn/tutorials/connecting-bluetooth-audio>)
this answer : [bluetooth.btcommon.BluetoothError: (2, 'No such file or directory')](https://stackoverflow.com/questions/36675931/bluetooth-btcommon-bl... | 669 |
24,879,641 | I've been looking everywhere for a step-by-step explanation for how to set up the following on an EC2 instance. For a new user I want things to be clean and correct but all of the 'guides' have different information and are really confusing.
My first thought is that I need to do the following
* Upgrade to latest vers... | 2014/07/22 | [
"https://Stackoverflow.com/questions/24879641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3195487/"
] | I assume you may be unfamiliar with EC2, so I suggest going through this [FAQ](https://wiki.debian.org/Amazon/EC2/FAQ) before continuing with deploying an EC2 instance to run your Python2.7 application.
Anyway, now that you are somewhat more familiar with that, here's how I normally deploy a one-off instance through t... | A script to build python in case the version you need is not in an available repo:
<https://gist.github.com/AvnerCohen/3e5cbe09bc40231869578ce7cbcbe9cc>
```
#!/bin/bash -e
NEW_VERSION="2.7.13"
CURRENT_VERSION="$(python -V 2>&1)"
if [[ "$CURRENT_VERSION" == "Python $NEW_VERSION" ]]; then
echo "Python $NEW_V... | 670 |
40,145,127 | I'm trying to construct a URL based on what I get from a initial URL.
Example:
*URL1:*
```
http://some-url/rest/ids?configuration_path=project/Main/10-deploy
```
**Response here is** 123
*URL2:*
```
http://abc-bld/download/{RESPONSE_FROM_URL1_HERE}.latest_successful/artifacts/build-info.props
```
so my final U... | 2016/10/20 | [
"https://Stackoverflow.com/questions/40145127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5622743/"
] | First how you can import your variable without modifying extra.py, if really want too,
You would have to take help of sys module for getting reference to foo in extra module.
```
import sys
from extra import *
print('1. Foo in globals ? {0}'.format('foo' in globals()))
setfoo()
print('2. Foo in globals ? {0}'.format... | Modules have namespaces which are variable names bound to objects. When you do `from extra import *`, you take the objects found in `extra`'s namespace and bind them to new variables in the new module. If `setfoo` has never been called, then `extra` doesn't have a variable called `foo` and there is nothing to bind in t... | 671 |
25,585,785 | I'm using python 3.3. Consider this function:
```
def foo(action, log=False,*args) :
print(action)
print(log)
print(args)
print()
```
The following call works as expected:
```
foo("A",True,"C","D","E")
A
True
('C', 'D', 'E')
```
But this one doesn't.
```
foo("A",log=True,"C","D","E")
SyntaxErro... | 2014/08/30 | [
"https://Stackoverflow.com/questions/25585785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/888862/"
] | Consider the following:
```
def foo(bar="baz", bat=False, *args):
...
```
Now if I call
```
foo(bat=True, "bar")
```
Where does "bar" go? Either:
* `bar = "bar", bat = True, args = ()`, or
* `bar = "baz", bat = True, args = ("bar",)`, or even
* `bar = "baz", bat = "bar", args = ()`
and there's no obvious ch... | The function of keyword arguments is twofold:
1. To provide an interface to functions that does not rely on the order of the parameters.
2. To provide a way to reduce ambiguity when passing parameters to a function.
Providing a mixture of keyword and ordered arguments is only a problem when you provide the keyword ar... | 673 |
53,965,764 | Hi I'm learning to code in python and thought it would be cool to automate a task I usually do for my room mates. I write out a list of names and the date for each month so that everyone knows whos turn it is for dishes.
Here's my code:
```
def dish_day_cycle(month, days):
print('Dish Cycle For %s:' % month)
... | 2018/12/29 | [
"https://Stackoverflow.com/questions/53965764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10844873/"
] | You used a nested for loop, therefore for every day - each of the names is printed along with that day. Use only the outer loop, and calculate who's turn it is. should be something like:
```
for day in range(1, days):
print('%s %s : %s' % (month, day, dish_list[day % len(dish_list)]))
```
assuming your roomates ... | You can loop through both lists together and repeating the shorter with `itertools.cycle`:
```
import itertools
for day, person in zip(range(1, days), itertools.cycle(dish_list)):
print('{} {} : {}'.format(month, day, person))
```
Update:
`zip` will pair elements in the two iterables--`range` object of days an... | 674 |
44,861,989 | I have an xlsx file, with columns with various coloring.
I want to read only the white columns of this excel in python using pandas, but I have no clues on hot to do this.
I am able to read the full excel into a dataframe, but then I miss the information about the coloring of the columns and I don't know which colum... | 2017/07/01 | [
"https://Stackoverflow.com/questions/44861989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4402942/"
] | **(Disclosure: I'm one of the authors of the library I'm going to suggest)**
With [StyleFrame](https://github.com/DeepSpace2/StyleFrame) (that wraps pandas) you can read an excel file into a dataframe without loosing the style data.
Consider the following sheet:
[ and save the results
3. Create pa... | 676 |
51,165,672 | When I execute the code below, is there anyway to keep python compiler running the code without error messages popping up?
Since I don't know how to differentiate integers and strings,
when `int(result)` executes and `result` contains letters, it spits out an error message that stops the program.
Is there anyway a... | 2018/07/04 | [
"https://Stackoverflow.com/questions/51165672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10029884/"
] | Actually, with Python and many other languages, you can differentiate types.
When you execute `int(result)`, the `int` builtin assumes the parameter value is able to be turned into an integer. If not, say the string is `abc123`, it can not turn that string into an integer and will raise an exception.
An easy way arou... | You can put everything that might throw an error, in a try block, and have an except block that keeps the flow of the program.
btw I think, in your code it should be, `isinstance(result,int)` not `isinstance(result,str)`
In your case,
```
result = input('Type in your number,type y when finished.\n')
try:
result ... | 677 |
69,216,484 | Hello I'm trying to sort my microscpoy images.
I'm using python 3.7
File names' are like this. t0, t1, t2
```
S18_b0s17t0c0x62672-1792y6689-1024.tif
S18_b0s17t1c0x62672-1792y6689-1024.tif
S18_b0s17t2c0x62672-1792y6689-1024.tif
.
.
.
S18_b0s17t145c0x62672-1792y6689-1024
```
I tried "sorted" the list but it was like t... | 2021/09/17 | [
"https://Stackoverflow.com/questions/69216484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16075554/"
] | **Updated answer for your updated question:**
**The simple answer to your question is that you can use [string.Split](https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=net-5.0) to separate that string at the commas.** But the fact that you have to do this is indicative of a larger problem with your... | I'm editing the answer based on the new information.
I'd still consider using my Dapper wrapper package.
<https://www.nuget.org/packages/Cworth.DapperExtensions/#>
Create a model class that matches the filed returned in your select.
```
public class MyModel
{
public string Command { get; set; }
public string... | 680 |
59,126,742 | i am playing with wxPython and try to set position of frame:
```
import wx
app = wx.App()
p = wx.Point(200, 200)
frame = wx.Frame(None, title = 'test position', pos = p)
frame.Show(True)
print('frame position: ', frame.GetPosition())
app.MainLoop()
```
even though `print('frame position: ', frame.GetPosition())` ... | 2019/12/01 | [
"https://Stackoverflow.com/questions/59126742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3455890/"
] | I had the same problem under Windows and played around with the style flags. With wxICONIZE sytle set active the window finally used the positioning information | The position is provided to the window manager as a "hint". It is totally up to the window manager whether it will actually honor the hint or not. Check the openbox settings or preferences and see if there is anything relevant that can be changed. | 681 |
56,451,482 | Within my main window I have a table of class QTreeView. The second column contains subjects of mails. With a click of a push button I want to search for a specific character, let's say "Y". Now I want the table to jump to the first found subject beginning with the letter "Y".
See the following example.
[![enter imag... | 2019/06/04 | [
"https://Stackoverflow.com/questions/56451482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10598535/"
] | You have to do the following:
* Use the [`match()`](https://doc.qt.io/qt-5/qabstractitemmodel.html#match) method of view to find the QModelIndex given the text.
* Use the [`scrollTo()`](https://doc.qt.io/qt-5/qabstractitemview.html#scrollTo) method of view to scroll to QModelIndex
* Use the [`select()`](https://doc.qt... | I'll be honnest, I don't use GUI with python but here is how you could do by replacing my arbitrary functions by the needed ones with PyQT
```py
mostWantedChar = 'Y'
foundElements = []
for element in dataView.listElements():
if element[0] == mostWantedChar:
foundElements.Append(element + '@' + element.Lin... | 682 |
4,089,843 | I'm looking to implement a SOAP web service in python on top of IIS. Is there a recommended library that would take a given Python class and expose its functions as web methods? It would be great if said library would also auto-generate a WSDL file based on the interface. | 2010/11/03 | [
"https://Stackoverflow.com/questions/4089843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11208/"
] | There is an article by Doug Hellmann that evaluates various SOAP Tools
* <http://doughellmann.com/2009/09/01/evaluating-tools-for-developing-with-soap-in-python.html>
Other ref:
* <http://wiki.python.org/moin/WebServices>
* <http://pywebsvcs.sourceforge.net/> | Take a look at SOAPpy (<http://pywebsvcs.sourceforge.net/>). It allows you to expose your functions as web methods, but you have to add a line of code (manually) to register your function with the exposed web service. It is fairly easy to do. Also, it doesn't auto generate wsdl for you.
Here's an example of how to crea... | 683 |
11,387,575 | The [python sample source code](https://developers.google.com/drive/examples/python#complete_source_code) goes thru the details of authentication/etc. I am looking for a simple upload to the Google Drive folder that has public writable permissions. (Plan to implement authorization at a later point).
I want to replace... | 2012/07/08 | [
"https://Stackoverflow.com/questions/11387575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1055761/"
] | You can't. All requests to the Drive API need authentication (source: <http://developers.google.com/drive/about_auth>) | As Wooble said, you cannot do this without authentication. You can use this service + file-upload widget to let your website visitors upload files to your Google Drive folder: <https://github.com/cloudwok/file-upload-embed/> | 685 |
32,341,972 | I'm creating a small python program that iterates through a folder structure and performs a task on every audio file that it finds.
I need to identify which files are audio and which are 'other' (e.g. jpegs of the album cover) that I want the process to ignore and just move onto the next file.
From searching on Stack... | 2015/09/01 | [
"https://Stackoverflow.com/questions/32341972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1701514/"
] | This is likely happening because you are drawing your screenshot in your `Activity#onCreate()`. At this point, your View has not measured its dimensions, so `View#getDrawingCache()` will return null because width and height of the view will be 0.
You can move your screenshot code away from `onCreate()` or you could us... | got the solution from @ugo's suggestion
put this in a your onCreate function
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_share );
//
...
///
myLayout.getViewTreeObserv... | 686 |
60,410,173 | I have a pip requirements file that includes specific cpu-only versions of torch and torchvision. I can use the following pip command to successfully install my requirements.
```bash
pip install --requirement azure-pipelines-requirements.txt --find-links https://download.pytorch.org/whl/torch_stable.html
```
My requ... | 2020/02/26 | [
"https://Stackoverflow.com/questions/60410173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/575530/"
] | [This example](https://github.com/conda/conda/blob/54e4a91d0da4d659a67e3097040764d3a2f6aa16/tests/conda_env/support/advanced-pip/environment.yml) shows how to specify options for pip
Specify the global pip option first:
```
name: build
dependencies:
- python=3.6
- pip
- pip:
- --find-links https://d... | Found the answer in the pip documentation [here](https://pip.pypa.io/en/stable/reference/pip_install/#requirement-specifiers). I can add the `find-links` option to my requirements file, so my conda environment yaml file becomes
```yaml
name: build
dependencies:
- python=3.6
- pip
- pip:
- --requirement azure... | 687 |
45,894,208 | I'm using Spyder to do some small projects with Keras, and every now and then (I haven't pinned down what it is in the code that makes it appear) I get this message:
```
File "~/.local/lib/python3.5/site-packages/google/protobuf/descriptor_pb2.py", line 1771, in <module>
__module__ = 'google.protobuf.descriptor_... | 2017/08/26 | [
"https://Stackoverflow.com/questions/45894208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1718331/"
] | Ok, I found the cause: interrupting the execution before Keras fully loads.
As said before restarting Spyder (or just the console) solves it. | I had the same problem with Spyder, which happened when it was trying to reload modules that were already loaded. I solved it by disabling the UMR (User Module Reloader) option in "preferences -> python interpreter" . | 688 |
65,266,224 | I'm new to python so please kindly help, I don't know much.
I'm working on a project which asks for a command, if the command is = to "help" then it will say how to use the program. I can't seem to do this, every time I try to use the if statement, it still prints the help section wether the command exists or not.
**... | 2020/12/12 | [
"https://Stackoverflow.com/questions/65266224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14759499/"
] | If you are using gnu-efi, use `uefi_call_wrapper()` to call UEFI functions.
```c
RT->GetTime(time, NULL); // Program hangs
uefi_call_wrapper(RT->GetTime, 2, time, NULL); // Okay
```
The reason is the different calling convention between UEFI (which uses Microsoft x64 calling convention) and Linux (which uses Syste... | I think you missed to initialize RT.
```
RT = SystemTable->RuntimeServices;
```
Your code is very similar to one of the examples (the one at section 4.7.1) of the Unified Extensible Firmware Interface Specification 2.6. I doubth you haven't read it, but just in case.
<https://www.uefi.org/sites/default/files/resour... | 691 |
25,310,746 | I've large set of images. I wan't to chage their background to specific color. Lets say green. All of the images have transparent background. Is there a way to perform this action using python-fu scripting in Gimp. Or some other tool available to do this specific task in automated fashion. | 2014/08/14 | [
"https://Stackoverflow.com/questions/25310746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/811502/"
] | The fact is that when you query a model (via a QuerySet method, or indirectly via a ForeignKey) **you get non-polymorphic instances** - in contrast to SQLAlchemy, where you get polymorphic instances.
This is because the fetched data corresponds only to the data you're accessing (and it's ancestors since they are known... | According to Django Documentation:
`If you have a Place that is also a Restaurant, you can get from the Place object to the Restaurant object by using the lower-case version of the model name:`
```
p = Place.objects.get(id=12)
p.restaurant
```
Further to that:
>
> **However, if p in the above example was not a Re... | 692 |
5,627,954 | A simple program for reading a CSV file inside a ZIP archive:
```py
import csv, sys, zipfile
zip_file = zipfile.ZipFile(sys.argv[1])
items_file = zip_file.open('items.csv', 'rU')
for row in csv.DictReader(items_file):
pass
```
works in Python 2.7:
```none
$ python2.7 test_zip_file_py3k.py ~/data.zip
$
``... | 2011/04/11 | [
"https://Stackoverflow.com/questions/5627954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638434/"
] | You can wrap it in a [io.TextIOWrapper](http://docs.python.org/library/io.html#io.TextIOWrapper).
```
items_file = io.TextIOWrapper(items_file, encoding='your-encoding', newline='')
```
Should work. | [Lennart's answer](https://stackoverflow.com/questions/5627954/py3k-how-do-you-read-a-file-inside-a-zip-file-as-text-not-bytes/5631786#5631786) is on the right track (Thanks, Lennart, I voted up your answer) and it **almost** works:
```
$ cat test_zip_file_py3k.py
import csv, io, sys, zipfile
zip_file = zipfile.Z... | 694 |
55,633,118 | I would like to create an application running from CLI in windows like the awscli program.
It should be built with python script and when running that it showld perform soma action like
```
samplepgm login -u akhil -p raju
```
Like this, Could you guide me in creating this kind of cli application in Windows with ... | 2019/04/11 | [
"https://Stackoverflow.com/questions/55633118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1556933/"
] | Check out `argparse` for something basic:
<https://docs.python.org/3/library/argparse.html>
For a better library check out `Click`:
<https://click.palletsprojects.com/en/7.x/>
Others:
* <https://pypi.org/project/argh/>
* <http://docopt.org/> | I have implemented this using [Pyinstaller](https://pyinstaller.readthedocs.io/en/stable/) which will build an exe file of the python files. Will work with all versions of Python
First you need to create your python cli script for the task, then build the exe using
`pyinstaller --onefile -c -F -n Cli-latest action.p... | 703 |
54,435,024 | I have a 50 years data. I need to choose the combination of 30 years out of it such that the values corresponding to them reach a particular threshold value but the possible number of combination for `50C30` is coming out to be `47129212243960`.
How to calculate it efficiently?
```
Prs_100
Yrs ... | 2019/01/30 | [
"https://Stackoverflow.com/questions/54435024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5617580/"
] | This is `vendor.js` is working fine:
```
require('datatables.net');
require('datatables.net-bs4');
window.JSZip = require('jszip');
require('datatables.net-buttons');
require('datatables.net-buttons/js/buttons.flash.js');
require('datatables.net-buttons/js/buttons.html5.js');
``` | If you are not using Bootstrap, you should use this:
```
var table = $('#example').DataTable( {
buttons: [
'copy', 'excel', 'pdf'
] } );
table.buttons().container()
.appendTo( $('<#elementWhereYouNeddToShowThem>', table.table().container() ) );
``` | 704 |
53,529,807 | I am trying to balance my dataset, But I am struggling in finding the right way to do it. Let me set the problem. I have a multiclass dataset with the following class weights:
```
class weight
2.0 0.700578
4.0 0.163401
3.0 0.126727
1.0 0.009294
```
As you can see the dataset is pretty unb... | 2018/11/28 | [
"https://Stackoverflow.com/questions/53529807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6394941/"
] | Try something like this β¦
```
### Exporting SQL Server table to JSON
Clear-Host
#--Establishing connection to SQL Server --#
$InstanceName = "."
$connectionString = "Server=$InstanceName;Database=msdb;Integrated Security=True;"
#--Main Query --#
$query = "SELECT * FROM sysjobs"
$connection = New-Object System.... | The "rub" here is that the SQL command `FOR JSON AUTO` even with execute scalar, will truncate JSON output, and outputting to a variable with `VARCHAR(max)` will still truncate. Using SQL 2016 LocalDB bundled with Visual Studio if that matters. | 705 |
62,537,194 | I am trying to solve a problem in HackerRank and stuck in this.
Help me to write python code for this question
Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
Mat size must be X. ( is an odd natural number, and is times .)
The design should... | 2020/06/23 | [
"https://Stackoverflow.com/questions/62537194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13766802/"
] | Just a Simplified Version--
```
n,m = input().split()
n = int(n)
m = int(m)
#printing first half
for i in range(n//2):
t = int((2*i)+1)
print(('.|.'*t).center(m, '-'))
#printing middle line
print('WELCOME'.center(m,'-'))
#printing last half
for i in reversed(range(n//2)):
t = int((2*i)+1)
print(('.|.'... | I was curious to look if there was a better solution to this hackerrank problem than mine so I landed up here.
### My solution with a single `for` loop which successfully passed all the test cases:
```
# Enter your code here. Read input from STDIN. Print output to
if __name__ == "__main__":
row_num, column_num ... | 707 |
73,726,556 | is there a way to launch a script running on python3 via a python2 script.
To explain briefly I need to start the python3 script when starting the python2 script.
Python3 script is a video stream server (using Flask) and have to run simultaneously from the python2 script (not python3 script first and then python2 scr... | 2022/09/15 | [
"https://Stackoverflow.com/questions/73726556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19869727/"
] | Simply you can use;
```
const requestedTime=document.querySelector(".entry-date")?.value;
```
"." uses for class names, if you have "example" class you should define it as ".example"
"?" called as Optional chaining that means if there is no object like that return "undefined" not an error
".value" uses for getting... | There is no `getElementByClassName` method, only `getElementsByClassName`. So you would have to change your code to `.getElementsByClassName(...)[0]`.
```js
var children=document.getElementsByClassName("entry-date published")[0].textContent
console.log(children);
```
```html
<time class="updated" datetime="2022-09-14... | 717 |
17,846,964 | I used qt Designer to generate my code. I want to have my 5 text boxes to pass 5 arguments to a python function(the function is not in this code) when the run button is released. I'm not really sure how to do this, I'm very new to pyqt.
```
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8... | 2013/07/25 | [
"https://Stackoverflow.com/questions/17846964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2616664/"
] | It's because you're doing [array dereferencing](http://schlueters.de/blog/archives/138-Features-in-PHP-trunk-Array-dereferencing.html) which is only available in PHP as of version 5.4. You have it locally but your webhost does not. That's why you should always make sure your development environment matches your product... | It because you're using something called array dereferencing which basically means that you can access a value from an array returned by a function direct. this is only supported in php>=5.4
To solve your issue, do something like this:
```
function pem2der($pem_data) {
$exploded = explode('-----', $pem_data);
... | 720 |
21,495,524 | How to read only the first line of ping results using python? On reading ping results with python returns multiple lines. So I like to know how to read and save just the 1st line of output? The code should not only work for ping but should work for tools like "ifstat" too, which again returns multiple line results. | 2014/02/01 | [
"https://Stackoverflow.com/questions/21495524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3259921/"
] | Run the command using subprocess.check\_output, and return the first of splitlines():
```
import subprocess
subprocess.check_output(['ping', '-c1', '192.168.0.1']).splitlines()[0]
```
Andreas | You can use [`subprocess.check_output`](http://docs.python.org/2/library/subprocess.html#subprocess.check_output) and [`str.splitlines`](http://docs.python.org/2/library/stdtypes.html#str.splitlines). Here [`subprocess.check_output`](http://docs.python.org/2/library/subprocess.html#subprocess.check_output) runs the com... | 721 |
52,745,705 | so I'm trying to create an AI just for fun, but I've run into a problem. Currently when you say `Hi` it will say `Hi` back. If you say something it doesn't know, like `Hello`, it will ask you to define it, and then add it to a dictionary variable `knowledge`. Then whenever you say `Hello`, it translates it into `Hi` an... | 2018/10/10 | [
"https://Stackoverflow.com/questions/52745705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10481614/"
] | Firs thing you need is your initial dictionary with only `hi`. Then we say something to our friend. We check all the values, if our phrase is not in there, we ask for the phrase to be defined. We create a new key with that definition along with a default empty list. We then append the phase to that list. Else, we searc... | You could do something like this:
```
knowledge = {"hi": ["hi"]}
```
And when your AI learns that `new_word` means the same as `"hi"`:
```
knowledge["hi"].append(new_word)
```
So now, if you now say hi to your AI (this uses the random module):
```
print(random.choice(knowledge["hi"]))
``` | 723 |
57,655,112 | I want to remove some unwanted tags/images from various repositories of azure container registry. I want to do all these programmatically. For example, what I need is:
* Authenticate with ACR
* List all repositories
* List all tags of each repository
* Remove unwanted images with particular tags.
Normally these opera... | 2019/08/26 | [
"https://Stackoverflow.com/questions/57655112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10259516/"
] | Would this work?
```py
>>> for header in soup.find_all('h3'):
... if header.get_text() == '64-bit deb for Ubuntu/Debian':
... header.find_next_sibling()
...
<table align="center" border="1" width="600">
:
</table>
``` | bs4 4.7.1 + you can use `:contains` with adjacent sibling (+) combinator. No need for a loop.
```
from bs4 import BeautifulSoup as bs
html = '''<h3>Windows 64-bit</h3>
<table width="600" border="1" align="center">
:
</table>
:
<h3>64-bit deb for Ubuntu/Debian</h3>
<table width="600" border="1" align="center">
:'''
so... | 724 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.