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
58,117,763
First of all, sorry for any newbie mistakes that I've made. But I couldn't figure out and couldn't find a source specifically for [deeppavlov (NER)](http://docs.deeppavlov.ai/en/master/features/models/ner.html) library. I'm trying to train ner\_ontonotes\_bert\_mult as described [here](http://docs.deeppavlov.ai/en/mast...
2019/09/26
[ "https://Stackoverflow.com/questions/58117763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10183880/" ]
There are at least two problems here: 1. instead of `validation.txt` there should be a `valid.txt` file; 2. you are trying to retrain a model that was pretrained on a different dataset with a different set of tags, it's not necessary. To train your model from scratch you can do something like: ```py import jso...
I tried deeppavlov training, and successfully trained the 'ner' model I also got the same error at first while training, then I overcome by researching more about it things to know before training - -> you can find the 'ner\_ontonotes\_bert\_multi.json' config file link in deeppavlov doc, which gives the dataset pat...
4,466
33,114,202
I'm currently testing docker on a Debian 8.2 server and I'm seeking help from mor experienced people. I've followed the official documentation to install docker (<http://docs.docker.com/installation/debian/>) and I'm now trying docker compose (<https://docs.docker.com/compose/>). I've installed compose using pip as de...
2015/10/13
[ "https://Stackoverflow.com/questions/33114202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5243755/" ]
You are on the right track. The first approach just needs two things: * a dot at the beginning to make it [context-specific](http://doc.scrapy.org/en/latest/topics/selectors.html#working-with-relative-xpaths) * `text()` at the end Fixed version: ``` selector.xpath('.//div[@class="score unvoted"]/text()').extract() ...
this should work - ``` selector.xpath('//div[contains(@class, "score unvoted")]/text()').extract() ```
4,467
59,711,699
I run my python scrapy project shows the error `no module named 'requests'` So I type `pip install requests` and then terminal information: ``` Requirement already satisfied: requests in ./Library/Python/2.7/lib/python/site-packages (2.22.0) Requirement already satisfied: chardet<3.1.0,>=3.0.2 in ./Library/Python/2....
2020/01/13
[ "https://Stackoverflow.com/questions/59711699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6902961/" ]
Install `python3` and `pip3` and then `pip3 install requests` if you are on ubuntu `python3` is installed by default you should first install `pip3` by `apt install python3-pip` and then `pip3 install requests`
If you are using two different versions of Python, it should explain why you can't use your module. To install the module on Python 3, try: ``` pip3 install requests ``` And make sure, you are using the correct version.
4,468
70,192,924
I have a discord bot running on a python script, and its token is stored in a `.txt` file. If I read from the file using: ``` with open('Stored Discord Token.txt') as storedToken: TOKEN = storedToken.readlines() ``` I can get the discord bot token. The problem is that the discord bot token looks like this: `[' ...
2021/12/02
[ "https://Stackoverflow.com/questions/70192924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12966704/" ]
First of all, `read()` will just return the whole file contents as a string, so you could use `TOKEN = storedToken.read()`. Lists in Python can be accessed using `[index]` so to access the first line in the file you can do `TOKEN = storedToken.readlines()[0]`. If say you wanted to access the `n`th line you could do `s...
As @Brian suggested, slicing out the substring solves the problem. If we simply add one line of code, like this: ``` with open('Stored Discord Token.txt') as file: fileContents = file.readlines() TOKEN = fileContents[-1] ``` we remove the `[`, `]`, `'`, and characters, and can now successfully pass that str...
4,471
56,009,890
Authors of an xml document did not include all the text inside an element that will be converted to a hyperlink. I would like to process or pre-process the xml to include the necessary text. I find this hard to describe but a simple example should show what I'm attempting. I'm using XSLT 2.0. I already do regular expre...
2019/05/06
[ "https://Stackoverflow.com/questions/56009890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107690/" ]
The existing answer has the right approach but I would sharpen the regular expression pattern and the match patterns: ``` <xsl:param name="pattern" as="xs:string">\s\(Sheet \d\)</xsl:param> <xsl:variable name="pattern2" as="xs:string" select="'^' || $pattern"/> <xsl:variable name="pattern3" as="xs:string" selec...
You can use these two templates in combination with the *Identity template*: ``` <xsl:template match="glink"> <xsl:copy> <xsl:copy-of select="@*|text()" /> <xsl:text> </xsl:text> <xsl:value-of select="normalize-space(replace(following::text()[1],'\s(\(Sheet \d\)).*',' $1'))" /> </xsl:co...
4,473
64,026,529
I'm trying to accomplish a basic image processing. Here is my algorithm : Find n., n+1., n+2. pixel's RGB values in a row and create a new image from these values. [![Algorithm](https://i.stack.imgur.com/uFwT2.png)](https://i.stack.imgur.com/uFwT2.png) Here is my example code in python : ``` import glob import ntpa...
2020/09/23
[ "https://Stackoverflow.com/questions/64026529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14326860/" ]
Here is an approach: ``` import cv2 import numpy as np # Load input image im = cv2.imread('input.png') # Calculate new first layer - it is every 3rd pixel of the first layer of im n1 = im[:, ::3, 0] # Calculate new second layer - it is every 3rd pixel of the second layer of im, starting with an offset of 1 pixel n2...
As far as I understood from the question, you want to shift the pixel values of each channel of the input image in the output image. So, here is my approach. ``` im = cv2.cvtColor(cv2.imread('my_image.jpg'), cv2.COLOR_BGR2RGB) im = np.pad(im, [(3, 3),(3,3),(0,0)], mode='constant', constant_values=0) # Add padding for ...
4,476
62,281,696
I have been doing some googling but I can't really find a good python3 solution to my problem. Given the following HTML code, how do I extract 2019, 0.7 and 4.50% using python3? ``` <td rowspan='2' style='vertical-align:middle'>2019</td><td rowspan='2' style='vertical-align:middle;font-weight:bold;'>4.50%</td><td row...
2020/06/09
[ "https://Stackoverflow.com/questions/62281696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3702643/" ]
A solution using [`BeautifulSoup`](https://www.crummy.com/software/BeautifulSoup/bs4/doc/): ``` from bs4 import BeautifulSoup txt = '''<td rowspan='2' style='vertical-align:middle'>2019</td><td rowspan='2' style='vertical-align:middle;font-weight:bold;'>4.50%</td><td rowspan='2' style='vertical-align:middle;font-weig...
I think this might be helpful if does not exactly answer your question: ``` from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_data(self, data): print(data) parser = MyHTMLParser() parser.feed("<Your HTML here>") ``` For your particular case this will return: 2019 4.50% SGD ...
4,477
58,736,295
I have the following `boto3` draft script ```py #!/usr/bin/env python3 import boto3 client = boto3.client('athena') BUCKETS='buckets.txt' DATABASE='some_db' QUERY_STR="""CREATE EXTERNAL TABLE IF NOT EXISTS some_db.{}( BucketOwner STRING, Bucket STRING, RequestDateTime STRING, Rem...
2019/11/06
[ "https://Stackoverflow.com/questions/58736295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2409793/" ]
First of all, `response` simply tells you that your request has been successfully submitted. Method `create_named_query()` creates a snippet of your query, which then can be seen/access in AWS Athena console in **Saved Queries** tab. [![enter image description here](https://i.stack.imgur.com/3rZ5I.png)](https://i.sta...
To reproduce your situation, I did the following: * In the Athena console, I ran: ```sql CREATE DATABASE foo ``` * In the Athena console, I selected `foo` in the Database drop-down * To start things simple, I ran this Python code: ```py import boto3 athena_client = boto3.client('athena', region_name='ap-southeast...
4,478
32,954,110
I have the following string in python: ``` foo = 'a_b_c' ``` How do I split the string into 2 parts: `'a_b'` and `'c'`? I.e, I want to split at the second `'_'` `str.split('_')` splits into 3 parts: `'a'`, `'b'` and `'c'`.
2015/10/05
[ "https://Stackoverflow.com/questions/32954110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/308827/" ]
Use the [`str.rsplit()` method](https://docs.python.org/2/library/stdtypes.html#str.rsplit) with a limit: ``` part1, part2 = foo.rsplit('_', 1) ``` `str.rsplit()` splits from the right-hand-side, and the limit (second argument) tells it to only split once. Alternatively, use [`str.rpartition()`](https://docs.python...
``` import re x = "a_b_c" print re.split(r"_(?!.*_)",x) ``` You can do it through `re`.Here in `re` with the use of `lookahead` we state that split by `_` after which there should not be `_`.
4,479
19,390,828
I am working on tree based program on python. I need to rewrite this function using recursion and liquidate all of these for-loops: Example of my function: ``` def items_on_level(full_tree, level): for key0, value0 in full_tree.items(): for key1, value1 in value0.items(): for key2, value2 in v...
2013/10/15
[ "https://Stackoverflow.com/questions/19390828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2863834/" ]
``` def itemsOnLevel(root, level): if not level: return list(root.keys()) else: return list(itertools.chain.from_iterable([itemsOnLevel(v, level-1) for k,v in root.items()])) ```
``` itemsOnLevel = lambda r, l: ( lambda f, r, l: f (f, r, l) ) ( lambda f, r, l: [_ for _ in r.keys () ] if not l else [i for k in r.values () for i in f (f, k, l - 1) ], r, l) ```
4,480
45,650,904
I am using celery to do a long-time task. The task will create a subprocess using `subprocess.Popen`. To make the task abortable, I write the code below: ``` from celery.contrib import abortable @task(bind=True, base=abortable.AbortableTask) def my_task(self, *args): p = subprocess.Popen([...]) while True: ...
2017/08/12
[ "https://Stackoverflow.com/questions/45650904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3278171/" ]
You are passing `Int` though the actual type required is `CustomSegmentedControl`. To simply solve this problem just create the `IBOutlet` for your `CustomSegmentedControl` and pass it as parameter to `Button_CustomSegmentValueChanged` method. ``` func SwipedRight(swipe : UISwipeGestureRecognizer){ if currentSelec...
Assuming your `CustomSegmentedControl` is a subclass of `UISegmentedControl`, I have modified few lines of code ``` @IBAction func button_CustomSegmentValueChanged(_ sender: UISegmentedControl?) { // guard sender for nil before use } ``` and when calling this ``` func swipedRight(swipe : UISwipeGestureRecogniz...
4,485
1,081,698
I have a problem of upgrading python from 2.4 to 2.6: I have CentOS 5 (Full). It has python 2.4 living in /usr/lib/python2.4/ . Additional modules are living in /usr/lib/python2.4/site-packages/ . I've built python 2.6 from sources at /usr/local/lib/python2.6/ . I've set default python to python2.6 . Now old modules f...
2009/07/04
[ "https://Stackoverflow.com/questions/1081698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133068/" ]
They are not broken, they are simply not installed. The solution to that is to install them under 2.6. But first we should see if you really should do that... Yes, Python will when installed replace the python command to the version installed (unless you run it with --alt-install). You don't exactly state what your pr...
There are a couple of options... 1. If the modules will run under Python 2.6, you can simply create symbolic links to them from the 2.6 site-packages directory to the 2.4 site-packages directory. 2. If they will not run under 2.6, then you may need to re-compile them against 2.6, or install up-to-date versions of them...
4,487
46,121,057
I'm new to bash and was tasked with scripting a check for a compliance process. From bash (or if python is better), I need to script an ssh connection from within the host running the script. For example: ssh -l testaccount localhost But I need to run this 52 times so that it is trapped by an IPS. When running this...
2017/09/08
[ "https://Stackoverflow.com/questions/46121057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8581142/" ]
In contrast to CSS, JS and HTML files which can be [gzipped using dispatcher](https://docs.adobe.com/content/docs/en/dispatcher/disp-config.html), images can be compressed only by reducing quality or resizing them. It is a quite common case for AEM projects and there are a couple of options to do that, some of them ar...
AEM offers options for "image optimisation" but this is a broad topic so there is no "magic" switch you can turn to "optimise" your images. It all boils down to the amount of kilo- or megabytes that are transferred from AEM to the users browser. The size of an asset is influenced by two things: 1. Asset dimension (wi...
4,490
60,751,007
I am trying to build a simple dictionary of all us english vs uk english differences for a web application I am working on. Is there a non-hacky way to build a dictionary where both the value and key can be looked up in python as efficiently as possible? I'd prefer not to loop through the dict by values for us spell...
2020/03/19
[ "https://Stackoverflow.com/questions/60751007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/872097/" ]
You have a raw `@JoinColumn` in `RolePrivilege`, change it, so that the name of the column is configured: `@JoinColumn(name = "roleId")`. Also you're saving `RolePrivilege`, but the changes are not cascading, change the mapping to: ``` @ManyToOne(cascade = CascadeType.ALL) ``` P.S.: Prefer `List`s over `Set`s in -t...
Firstly, do not return String(wrap it to class for example to `RolePriviligueResponse` with `String status` as response body), secondly you dont need `@ResponseBody` annotation, your `@PostMapping` annotation already has it, third - dont use `Integer` for ID, better use `Long` type. And you did not provide the name of ...
4,495
14,657,433
How do I calculate correlation matrix in python? I have an n-dimensional vector in which each element has 5 dimension. For example my vector looks like ``` [ [0.1, .32, .2, 0.4, 0.8], [.23, .18, .56, .61, .12], [.9, .3, .6, .5, .3], [.34, .75, .91, .19, .21] ] ``` In this case dimension of the vector ...
2013/02/02
[ "https://Stackoverflow.com/questions/14657433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1964587/" ]
Using [numpy](http://www.numpy.org/), you could use [np.corrcoef](http://docs.scipy.org/doc/numpy/reference/generated/numpy.corrcoef.html): ``` In [88]: import numpy as np In [89]: np.corrcoef([[0.1, .32, .2, 0.4, 0.8], [.23, .18, .56, .61, .12], [.9, .3, .6, .5, .3], [.34, .75, .91, .19, .21]]) Out[89]: array([[ 1....
Here is a [pretty good example](http://www.tradinggeeks.net/2015/08/calculating-correlation-in-python/) of calculating a correlations matrix form multiple time series using Python. Included source code calculates correlation matrix for a set of Forex currency pairs using Pandas, NumPy, and matplotlib to produce a graph...
4,496
6,213,336
I'm reading lines from a file to then work with them. Each line is composed solely by float numbers. I have pretty much everything sorted up to convert the lines into arrays. I basically do (pseudopython code) ``` line=file.readlines() line=line.split(' ') # Or whatever separator array=np.array(line) #And then i...
2011/06/02
[ "https://Stackoverflow.com/questions/6213336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486262/" ]
Quick answer: ``` arrays = [] for line in open(your_file): # no need to use readlines if you don't want to store them # use a list comprehension to build your array on the fly new_array = np.array((array.float(i) for i in line.split(' '))) arrays.append(new_array) ``` If you process often this kind of d...
How about the following: ``` import numpy as np arrays = [] for line in open('data.txt'): arrays.append(np.array([float(val) for val in line.rstrip('\n').split(' ') if val != ''])) ```
4,501
47,057,572
I tried to use pytesseract: ``` import pytesseract from PIL import Image pytesseract.pytesseract.tesseract_cmd = 'C:\\Python27\\scripts\\pytesseract.exe' im = Image.open('Download.png') print pytesseract.image_to_string(im) ``` But I got this error: ``` Traceback (most recent call last): ...
2017/11/01
[ "https://Stackoverflow.com/questions/47057572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8500407/" ]
You need to install tesseract using windows installer available [here](https://github.com/UB-Mannheim/tesseract/wiki). Then you should install the python wrapper as: ``` pip install pytesseract ``` Then you should also set the tesseract path in your script after importing pytesseract library as below (Please do not ...
I think there is something wrong with your path 'C:\Python27\scripts\pytesseract.exe', This seems to point to the pytessaract.py code (hence the error has pytessaract.py on it - the exact error is mentioned in the main function of pytessaract.py which runs only if **name** == "**main**" ). The path must actually poin...
4,511
65,040,971
I setup a new Debian 10 (Buster) instance on AWS EC2, and was able to install a pip3 package that depended on netifaces, but when I came back to it the next day the package is breaking reporting an error in netifaces. If I try to run pip3 install netifaces I get the same error: ``` ~$ pip3 install netifaces Collecting...
2020/11/27
[ "https://Stackoverflow.com/questions/65040971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439005/" ]
`HTMLParser().unescape` was removed in Python 3.9. Compare [the code in Python 3.8](https://github.com/python/cpython/blob/v3.8.0/Lib/html/parser.py#L466) vs [Python 3.9](https://github.com/python/cpython/blob/v3.9.0/Lib/html/parser.py). The error seems to be a bug in `setuptools`. Try to upgrade `setuptools`. Or use ...
I was facing this issue in PyCharm 2018. Apart from upgrading `setuptools` as mentioned above, I also had to upgrade to `PyCharm 2020.3.4` to solve this issue. Related bug on PyCharm issue tracker: <https://youtrack.jetbrains.com/issue/PY-39579> Hope this helps someone avoid spending hours trying to debug this.
4,512
8,778,865
I was writing a program in python ``` import sys def func(N, M): if N == M: return 0.00 else: if M == 0: return pow(2, N+1) - 2.00 else : return 1.00 + (0.5)*func(N, M+1) + 0.5*func(N, 0) def main(*args): test_cases = int(raw_input()) while test_cases: ...
2012/01/08
[ "https://Stackoverflow.com/questions/8778865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1032610/" ]
Floats in Python are IEEE doubles: they are not unlimited precision. But if your computation only needs integers, then just use integers: they are unlimited precision. Unfortunately, I think your computation does not stay within the integers. There are third-party packages built on GMP that provide arbitrary-precision...
Consider using an arbitrary precision floating-point library, for example the [bigfloat](http://packages.python.org/bigfloat/) package, or [mpmath](http://code.google.com/p/mpmath/).
4,517
63,002,403
Is this as expected? I thought in Python, variables are pointers to objects in memory. If I modify the python list that a variable points to once, the memory reference changes. But if I modify it again, the memory reference is the same? ``` >>> id(mylist) Traceback (most recent call last): File "<stdin>", line 1, in...
2020/07/20
[ "https://Stackoverflow.com/questions/63002403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552698/" ]
You are correct in that the memory references should change. Take a careful look at the memory addresses: they're not identical. Edit: Regarding your edit, the memory address only changes on reassignment of the variable. The memory of the variable stays the same if you mutate the list.
Take a look of the id's you provided . There are completely different. 4338643744 != 4338953744. Look the first 5 numbers: 43386 != 43389. Everything is working as expects due to memory reference is changing properly.
4,519
73,648,264
I have a json like this but much longer: ``` [ { "id": "123", "name": "home network configuration", "description": "home utilities", "definedRanges": [ { "id": "6500b67e", "name": "100-200", "beginIPv4Address": "192.168.090.100", "endIPv4Address": "192.168.090.20...
2022/09/08
[ "https://Stackoverflow.com/questions/73648264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066865/" ]
Well, you were close. Here's how you put those together: ``` map({name, definedRanges: .definedRanges | map({name, beginIPv4Address, endIPv4Address})}) ``` [Online demo](https://jqplay.org/s/tHkRlLUV3K-)
Here's my shot at solutions to produce one or the other desired output: ``` map( { name } + (.definedRanges[] | { "definedRanges.name": .name, "definedRanges.beginIPv4Address": .beginIPv4Address, "definedRanges.endIPv4Address": .endIPv4Address })) ``` Output: ```json [ { "name": "home ...
4,525
295,028
I have a very tricky situation (for my standards) in hand. I have a script that needs to read a script variable name from [ConfigParser](https://docs.python.org/2/library/configparser.html). For example, I need to read ``` self.post.id ``` from a .cfg file and use it as a variable in the script. How do I achieve thi...
2008/11/17
[ "https://Stackoverflow.com/questions/295028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2220518/" ]
test.ini: ``` [head] var: self.post.id ``` python: ``` import ConfigParser class Test: def __init__(self): self.post = TestPost(5) def getPost(self): config = ConfigParser.ConfigParser() config.read('/path/to/test.ini') newvar = config.get('head', 'var') print eval(newvar) class...
This is a bit silly. You have a dynamic language, distributed in source form. You're trying to make what amounts to a change to the source. Which is easy-to-read, plain text Python. Why not just change the Python source and stop messing about with a configuration file? It's a lot easier to have a block of code like...
4,527
45,533,019
I was making a permutation script with python an i looked for how to make a multidimensional array, but the only way i could find was `array3 = [ [ "" for i in range(12) ] for j in range(4) ]` Is there any way i can make it so it's defined as multidimensional but not the size of it? I also found that it's possible to ...
2017/08/06
[ "https://Stackoverflow.com/questions/45533019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7848729/" ]
Use `itertools.chain.from_iterable` and `itertools.product`: ``` from itertools import chain, product for first, second in product(chain.from_iterable(array), chain.from_iterable(array2)): print("{}{}".format(first, second)) ``` Since `array` and `array2` are lists and not arbitrary...
If I understand you correctly You'll need a 4th degree nesting: ``` array = [["a","b","c","d","e","f"],["7","8","9","0","11","12"]] array2 = [["1","2","3","4","5","6"],["g","h","i","j","k","l"]] for row in array: # iterate "rows" for cell in row: # iterate "cells" in a specific "row" for row_2 in array2...
4,528
40,032,276
I have a dataframe similar to: ``` id | date | value --- | ---------- | ------ 1 | 2016-01-07 | 13.90 1 | 2016-01-16 | 14.50 2 | 2016-01-09 | 10.50 2 | 2016-01-28 | 5.50 3 | 2016-01-05 | 1.50 ``` I am trying to keep the most recent values for each id, like this: ``` id | date | value --- | ...
2016/10/13
[ "https://Stackoverflow.com/questions/40032276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4641956/" ]
The window operator as suggested works very well to solve this problem: ``` from datetime import date rdd = sc.parallelize([ [1, date(2016, 1, 7), 13.90], [1, date(2016, 1, 16), 14.50], [2, date(2016, 1, 9), 10.50], [2, date(2016, 1, 28), 5.50], [3, date(2016, 1, 5), 1.50] ]) df = rdd.toDF(['id',...
If you have items with the same date then you will get duplicates with the dense\_rank. You should use row\_number: ```py from pyspark.sql.window import Window from datetime import date ​import pyspark.sql.functions as F rdd = spark.sparkContext.parallelize([ [1, date(2016, 1, 7), 13.90], [1, date(2016, 1, 7...
4,529
36,341,553
Lets say I want to use `gcc` from the command line in order to compile a C extension of Python. I'd structure the call something like this: ``` gcc -o applesauce.pyd -I C:/Python35/include -L C:/Python35/libs -l python35 applesauce.c ``` I noticed that the `-I`, `-L`, and `-l` options are absolutely necessary, or el...
2016/03/31
[ "https://Stackoverflow.com/questions/36341553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3689198/" ]
The easiest way to compile extensions is to use `distutils`, [like this](https://docs.python.org/2/distutils/examples.html); ``` from distutils.core import setup from distutils.extension import Extension setup(name='foobar', version='1.0', ext_modules=[Extension('foo', ['foo.c'])], ) ``` Keep in mi...
If you look at the source of [`build_ext.py`](http://svn.python.org/projects/python/trunk/Lib/distutils/command/build_ext.py) from `distutils` in the method `finalize_options` you will find code for different platforms used to locate libs.
4,532
65,365,486
I'm trying to locate an element using python selenium, and have the html below: ``` <input class="form-control" type="text" placeholder="University Search"> ``` I couldn't locate where to type what I want to type. ``` from selenium import webdriver import time driver = webdriver.Chrome(executable_path=r"D:\Python\...
2020/12/19
[ "https://Stackoverflow.com/questions/65365486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11405347/" ]
You are attempting to use [find\_element\_by\_name](https://selenium-python.readthedocs.io/locating-elements.html#locating-by-name) and yet this element has no `name` attribute defined. You need to look for the element with the specific `placeholder` attribute you are interested in - you can use [find\_element\_by\_xpa...
Very close, try the XPath when all else fails: ``` text_area = driver.find_element_by_xpath("//*[@id='qs-rankings']/thead/tr[3]/td[2]/div/input") ``` You can copy the full/relative XPath to clipboard if you're inspecting the webpage's html.
4,533
10,264,460
I am looking for some words in a file in python. After I find each word I need to read the next two words from the file. I've looked for some solution but I could not find reading just the next words. ``` # offsetFile - file pointer # searchTerms - list of words for line in offsetFile: for word in searchTerms: ...
2012/04/22
[ "https://Stackoverflow.com/questions/10264460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/776614/" ]
An easy way to deal with this is to read the file using a generator that yields one word at a time from the file. ``` def words(fileobj): for line in fileobj: for word in line.split(): yield word ``` Then to find the word you're interested in and read the next two words: ``` with open("offse...
If you need to retrieve only two first words, just do it: ``` offsetFile.readline().split()[:2] ```
4,536
67,167,886
I have installed `TensorFlow` on an M1 (**ARM**) Mac according to [these instructions](https://github.com/apple/tensorflow_macos/issues/153). Everything works fine. However, model training is happening on the `CPU`. How do I switch training to the `GPU`? ``` In: tensorflow.config.list_physical_devices() Out: [Physica...
2021/04/19
[ "https://Stackoverflow.com/questions/67167886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/626537/" ]
Update ------ The [tensorflow\_macos tf 2.4](https://github.com/apple/tensorflow_macos) repository has been archived by the owner. For `tf 2.5`, refer to [here](https://developer.apple.com/metal/tensorflow-plugin/). --- It's probably not useful to disable the eager execution fully but to `tf. functions`. Try this an...
Try with turning off the eager execution... via following ``` import tensorflow as tf tf.compat.v1.disable_eager_execution() ``` Let me know if it works.
4,539
59,520,376
I came across a scenario where i need to run the function parallely for a list of values in python. I learnt executor.map from `concurrent.futures` will do the job. And I was able to parallelize the function using the below syntax `executor.map(func,[values])`. But now, I came across the same scenario (i.e the functi...
2019/12/29
[ "https://Stackoverflow.com/questions/59520376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9452253/" ]
If you have an iterable of `sites` that you want to `map` and you want to pass the same `search_term` and `pages` argument to each call. You can use `zip` to create an iterable that returns tuples of 3 elements where the first is your list of sites and the 2nd and 3rd are the other parameters just repeating using `iter...
Here is a useful way of using kwargs in `executor.map`, by simply using a `lambda` function to pass the kwargs with the `**kwargs` notation: ```py from concurrent.futures import ProcessPoolExecutor def func(arg1, arg2, ...): .... items = [ { 'arg1': 0, 'arg2': 3 }, { 'arg1': 1, 'arg2': 4 }, { 'arg1':...
4,540
1,713,015
I installed Yahoo BOSS (it's a Python installation that allows you to use their search features). I followed everything perfectly. However, when I run the example to confirm that it works, I get this: ``` $ python ex3.py Traceback (most recent call last): File "ex3.py", line 16, in ? from yos.yql import db Fil...
2009/11/11
[ "https://Stackoverflow.com/questions/1713015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179736/" ]
Use Python 2.5 or above: xml.etree.ElementTree was added in 2.5. <http://docs.python.org/library/xml.etree.elementtree.html>
A google search reveals that you need to install the [effbot elementtree](http://effbot.org/downloads/#elementtree) Python module.
4,541
34,804,612
so im writing a login system with python and i would like to know if i can search a text document for the username you put in then have it output the line it was found on and search a password document. if it matches the password that you put in with the string on that line then it prints that you logged in. any and al...
2016/01/15
[ "https://Stackoverflow.com/questions/34804612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5382035/" ]
fucntion to get the line number. You can use this how you want ``` def getLineNumber(fileName, searchString): with open(fileName) as f: for i,line in enumerate(f, start=1): if searchString in line: return i raise Exception('string not found') ```
Pythonic way for your answer ``` f = open(filename) line_no = [num for num,line in enumerate(f) if 'searchstring' in line][0] print line_no+1 ```
4,542
45,049,312
How do I CONSOLIDATE the following using python COMPREHENSION **FROM (list of dicts)** ``` [ {'server':'serv1','os':'Linux','archive':'/my/folder1'} ,{'server':'serv2','os':'Linux','archive':'/my/folder1'} ,{'server':'serv3','os':'Linux','archive':'/my/folder2'} ,{'server':'serv4','os':'AIX','archive':'/my/folder...
2017/07/12
[ "https://Stackoverflow.com/questions/45049312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2288573/" ]
the need to be able to set default values to your dictionary and to have the same key several times may make a dict-comprehension a bit clumsy. i'd prefer something like this: a [`defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict) may help: ``` from collections import defaultdic...
It's difficult to achieve with list comprehension because of the accumulation effect. However, it's possible using `itertools.groupby` on the list sorted by your keys (use the same `key` function for both sorting and grouping). Then extract the server info in a list comprehension and prefix by the group key. Pass the ...
4,543
1,091,756
> > **Possible Duplicate:** > > [How many Python classes should I put in one file?](https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file) > > > Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio be...
2009/07/07
[ "https://Stackoverflow.com/questions/1091756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2494/" ]
the book [Expert Python Programming](http://www.packtpub.com/expert-python-programming/book) has something related discussion Chapter 4: Choosing Good Names:"Building the Namespace Tree" and "Splitting the Code" My line crude summary: collect some related class to one module(source file),and collect some related...
There is no specific convention for this - do whatever makes your code the most readable and maintainable.
4,544
45,043,961
I'm getting the following error when trying to run `$ bazel build object_detection/...` And I'm getting ~20 of the same error (1 for each time it attempts to build that). I think it's something with the way I need to configure bazel to recognize the py\_proto\_library, but I don't know where, or how I would do this. ...
2017/07/11
[ "https://Stackoverflow.com/questions/45043961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2544449/" ]
The solution ended up being running this command, like the instructions say: ``` $ protoc object_detection/protos/*.proto --python_out=. ``` and then running this command, like the instructions say.: ``` $ export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim ```
Are you using `load` in the `BUILD` file you're building? `load("@protobuf//:protobuf.bzl", "py_proto_library")`? The error seems to indicate the symbol `py_proto_library` isn't loaded into skylark.
4,554
68,630,769
I have a list of strings in python and want to run a recursive grep on each string in the list. Am using the following code, ``` import subprocess as sp for python_file in python_files: out = sp.getoutput("grep -r python_file . | wc -l") print(out) ``` The output I am getting is the grep of the string "pyth...
2021/08/03
[ "https://Stackoverflow.com/questions/68630769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16582585/" ]
Your code has several issues. The immediate answer to what you seem to be asking was given in a comment, but there are more things to fix here. If you want to pass in a variable instead of a static string, you have to use some sort of string interpolation. `grep` already knows how to report how many lines matched; us...
Your intent isn't totally clear from the way you've written your question, but the first argument to `grep` is the **pattern** (`python_file` in your example), and the second is the **file(s)** `.` in your example You could write this in native Python or just use grep directly, which is probably easier than using both...
4,555
62,295,148
I am new to lambda functions. I am trying to get the sum of elements in a list, but facing this issue repeatedly. [![enter image description here](https://i.stack.imgur.com/9k7gu.png)](https://i.stack.imgur.com/9k7gu.png) When following up with tutorials online([Tutorial-link](https://realpython.com/python-lambda/))...
2020/06/10
[ "https://Stackoverflow.com/questions/62295148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2663091/" ]
The [findOne](https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOne) function in the node.js driver has a slightly different definition than the one in the shell. Try ``` db.collection("inventory").findOne({ _id: 1 }, {projection:{ "size": 0 }}, (err, result) => { ```
May you should try this `db.collection("inventory").findOne({ _id: 1 }). select("-size"). exec((err, ``result) => {//body of the fn}) ;`
4,556
67,047,424
In this code, I am trying to insert a code block using [react-quilljs](https://github.com/gtgalone/react-quilljs#usage) ``` import React, { useState } from 'react'; import hljs from 'highlight.js'; import { useQuill } from 'react-quilljs'; import 'quill/dist/quill.snow.css'; // Add css for snow theme export default...
2021/04/11
[ "https://Stackoverflow.com/questions/67047424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10134463/" ]
Your code *is* getting marked up by `highlight.js` with CSS classes: ``` <span class="hljs-keyword">const</span> ``` You are not seeing the impact of those CSS classes because you don't have a stylesheet loaded to handle them. You need to choose the theme that you want from [the available styles](https://highlightjs...
Look at the css in the editor mode. It depends on two class names ql-snow and ql-editor. You can fix this issue by wrapping it around one more div with className ql-snow. ``` <div className='ql-snow'> <div className='ql-editor' dangerouslySetInnerHTML={{ __html: content }}> <div/> </div> ``` This should wor...
4,557
10,509,293
> > **Possible Duplicate:** > > [Why aren't Python's superclass **init** methods automatically invoked?](https://stackoverflow.com/questions/3782827/why-arent-pythons-superclass-init-methods-automatically-invoked) > > > For example: ``` class Pet(object): def __init__(self, name, species): self.na...
2012/05/09
[ "https://Stackoverflow.com/questions/10509293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1241100/" ]
Having the language force the super class to initialize before or after means that you lose functionality. A subclass may depend on a superclass's initialization to be run first, or vice versa. In addition, it wouldn't have any way of knowing what arguments to pass -- subclasses decide what values are passed to an ini...
You can make species a class attribute like this ``` class Pet(object): species = None def __init__(self, name): self.name = name def getName(self): return self.name def getSpecies(self): return self.species def __str__(self): return "%s is a %s" % (self.name, se...
4,559
67,377,043
What is the reason why I cannot access a specific line number in the already split string? ``` a = "ABCDEFGHIJKLJMNOPRSTCUFSC" barcode = "2" import textwrap prazno = textwrap.fill(a,width=5) podeli = prazno.splitlines() ``` Here the output is correct: ``` print(podeli) ABCDE FGHI...
2021/05/03
[ "https://Stackoverflow.com/questions/67377043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15827381/" ]
You can solve your immediate problem by rebuilding the list, but I fear you have a more general problem that you haven't told us. ``` if barcode[0] == '1': podeli[1] += ' MATA' elif barcode[0] == '2': podeli[1] += ' MATA' line2 = textwrap.fill(podeli[2], width=3).splitlines() po...
Try this, it should split a string you specified by a width of 3: ``` n = 3 [((podeli[2])[i:i+n]) for i in range(0, len(podeli[2]), n)] ```
4,560
40,882,899
I am using python+bs4+pyside in the code ,please look the part of the code below: ``` enter code here #coding:gb2312 import urllib2 import sys import urllib import urlparse import random import time from datetime import datetime, timedelta import socket from bs4 import BeautifulSoup import lxml.html from PySide.QtGu...
2016/11/30
[ "https://Stackoverflow.com/questions/40882899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7229399/" ]
try changing your foreach loop to this. ``` foreach ($list as $key => $value) { echo $value->title." || "; echo $value->link." "; echo nl2br("\n"); } ``` Hope this Works for you.
What you did is looping the keys and values seperated and than you tried to get the values from the keys of the stdClass, what you need to do is looping it as an object. I also used `json_decode($json_str, true)` to get the result as an array instead of an stdClass. ``` $json_str = '[{"title":"root","link":"one"},{"ti...
4,561
66,012,040
Running this DAG in airflow gives error as Task exited with return code Negsignal.SIGABRT. I am not sure what is wrong I have done ``` from airflow import DAG from airflow.providers.snowflake.operators.snowflake import SnowflakeOperator from airflow.utils.dates import days_ago SNOWFLAKE_CONN_ID = 's...
2021/02/02
[ "https://Stackoverflow.com/questions/66012040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10110307/" ]
I ran into the same error on Mac OSX - which looks like the OS you are using based on the local file path. Adding the following to my Airflow *scheduler* session fixed the problem: ``` export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES ``` The cause is described in the [Airflow docs](https://airflow.apache.org/blog/air...
You are executing: ``` snowflake_op_with_params = SnowflakeOperator( task_id='snowflake_op_with_params', dag=dag, snowflake_conn_id=SNOWFLAKE_CONN_ID, sql=SQL_INSERT_STATEMENT, parameters={"id": 56}, warehouse=SNOWFLAKE_WAREHOUSE, database=SNOWFLAKE_DATABASE, # schema=SNOWFLAKE_SCHEMA, ...
4,564
32,103,424
Coming from [Python recursively appending list function](https://stackoverflow.com/questions/32102420/python-recursively-appending-list-function) Trying to recursively get a list of permissions associated with a file structure. I have this function: ``` def get_child_perms(self, folder, request, perm_list): ...
2015/08/19
[ "https://Stackoverflow.com/questions/32103424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4941891/" ]
The basic issue occurs you are only returning the `folder permission` , when folder does not have any children , when it has children, you are not including the `folder.has_read_permission(request)` in your return result , which is most probably causing you issue. You need to do - ``` def get_child_perms(self, folder,...
why not [os.walk](https://docs.python.org/3/library/os.html?highlight=walk#os.walk) > > When topdown is True, the caller can modify the dirnames list in-place > (perhaps using del or slice assignment), and walk() will only recurse > into the subdirectories whose names remain in dirnames; this can be > used to pru...
4,569
26,643,903
I'm trying to use python requests to PUT a .pmml model to a local openscoring server. This works (from directory containing DecisionTreeIris.pmml): ``` curl -X PUT --data-binary @DecisionTreeIris.pmml -H "Content-type: text/xml" http://localhost:8080/openscoring/model/DecisionTreeIris ``` This doesn't: ``` impor...
2014/10/30
[ "https://Stackoverflow.com/questions/26643903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/829332/" ]
You are trying to store Components in the same variable. This is wrong: ``` var enemy1Clone : Transform = Instantiate(enemy1, transform.position, transform.rotation); enemy1Clone.GetComponent("enemyscript"); enemy1Clone.GetComponent(Animator); ``` `enemy1Clone` is of type `Transform`, don't try putting `enemyscript...
if the **Animator** is not initialized, you have to re-order the components, put the **Animator** component right below the **Transform** component and you should be fine.
4,570
56,496,458
The [logging docs](https://docs.python.org/2/library/logging.html) don't mention what the default logger obtained from [`basicConfig`](https://docs.python.org/2/library/logging.html#logging.basicConfig) writes to: stdout or stderr. What is the default behavior?
2019/06/07
[ "https://Stackoverflow.com/questions/56496458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1804173/" ]
If no `filename` argument is passed to [logging.basicconfig](https://docs.python.org/2/library/logging.html#logging.basicConfig) it will configure a `StreamHandler`. If a `stream` argument is passed to `logging.basicconfig` it will pass this on to `StreamHandler` otherwise `StreamHandler` defaults to using `sys.stderr`...
Apparently the default is stderr. A quick check: Using a minimal example ```py import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) logger.info("test") ``` and running it with `python test.py 1> /tmp/log_stdout 2> /tmp/log_stderr` results in an empty stdout file, but a non-em...
4,571
9,222,129
I have three python functions: ``` def decorator_function(func) def wrapper(..) return func(*args, **kwargs) return wrapper def plain_func(...) @decorator_func def wrapped_func(....) ``` inside a module A. Now I want to get all the functions inside this module A, for which I do: ``` for fname, func in in...
2012/02/10
[ "https://Stackoverflow.com/questions/9222129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/334909/" ]
If all you want is to keep the original function name visible from "the outside" I think that you can do that with ``` @functools.wraps ``` as a decorator to your decorator here's the example from the standard docs ``` >>> from functools import wraps >>> def my_decorator(f): ... @wraps(f) ... def wrapper(*...
You can access the pre-decorated function with: ``` wrapped_func.func_closure[0].cell_contents() ``` For example, ``` def decorator_function(func): def wrapper(*args, **kwargs): print('Bar') return func(*args, **kwargs) return wrapper @decorator_function def wrapped_func(): print('Foo') wra...
4,572
13,400,876
> > **Possible Duplicate:** > > [Python’s most efficient way to choose longest string in list?](https://stackoverflow.com/questions/873327/pythons-most-efficient-way-to-choose-longest-string-in-list) > > > I have a list L ``` L = [[1,2,3],[5,7],[1,3],[77]] ``` I want to return the length of the longest subli...
2012/11/15
[ "https://Stackoverflow.com/questions/13400876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538364/" ]
`max(L,key=len)` will give you the object with the longest length (`[1,2,3]` in your example) -- To actually get the length (if that's all you care about), you can do `len(max(L,key=len))` which is a bit ugly -- I'd break it up onto 2 lines. Or you can use the version supplied by ecatamur. All of these answers have lo...
Try a comprehension: ``` max(len(l) for l in L) ```
4,573
50,506,478
i am gaurav and i am learning programming. i was reading regular expressions in dive into python 3,so i thought to try myself something so i wrote this code in eclipse but i got a lot of errors.can anyone pls help me ``` import re def add_shtner(add): return re.sub(r"\bROAD\b","RD",add) print(add_shtner("100,BROA...
2018/05/24
[ "https://Stackoverflow.com/questions/50506478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5925439/" ]
This is supported from version `@angular/cli@6.1.0-beta.2`. --- **Update** (November 2019): **[The `fileReplacements` solution does not work with Angular CLI 8.0.0 anymore](https://github.com/angular/angular-cli/issues/14599#issuecomment-527131237)** Change `angular.json` to set your production `index.html` instea...
I'm using Angular 8 and I don't know why it doesn't work on my side. But I can specify the location for the `index.html` for any build configuration (and looks like also `serve`) <https://stackoverflow.com/a/57274333/3473303>
4,574
63,997,745
```py string = "This is a test string. It has 44 characters." #Line1 for i in range(len(string) // 10): #Line2 result= string[10 * i:10 * i + 10] #Line3 print(result) #Line4 ``` I want to understand the above code so that I can achiev...
2020/09/21
[ "https://Stackoverflow.com/questions/63997745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14311349/" ]
You can do: ``` colSums(df) != 0 A B C TRUE TRUE FALSE ```
Maybe `apply()` can be useful: ``` #Data df = data.frame("A" = c("TRUE","FALSE","FALSE","FALSE"), "B" = c("FALSE","TRUE","TRUE","FALSE"), "C" = c("FALSE","FALSE","FALSE","FALSE")) #Apply apply(df,2,function(x) any(x=='TRUE')) ``` Output: ``` A B C TRUE TRUE FALSE ```...
4,583
1,621,521
Is there a program which I can run like this: ``` py2py.py < orig.py > smaller.py ``` Where orig.py contains python source code with comments and doc strings, and smaller.py contains identical, runnable source code but without the comments and doc strings? Code which originally looked like this: ``` #/usr/bin/pyth...
2009/10/25
[ "https://Stackoverflow.com/questions/1621521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196255/" ]
[This Python minifier](https://pypi.python.org/pypi/pyminifier) looks like it does what you need.
I recommend [minipy](https://github.com/gareth-rees/minipy). The most compelling reason is that it does proper analysis of the source code abstract syntax tree so the minified code is much more accurate. I've found that the more well known [pyminifier](https://pypi.python.org/pypi/pyminifier) tends to generate code wit...
4,586
29,853,907
I was working with django-1.8.1 and everything was good but when I tried again to run my server with command bellow, I get some errors : command : `python manage.py runserver` errors appeared in command-line : ``` > Traceback (most recent call last): File "C:\Python34\lib\wsgiref\handlers.py", line 137, in run ...
2015/04/24
[ "https://Stackoverflow.com/questions/29853907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4701816/" ]
Looks like a mixed solution for me. Typically `TcpListener listener = new TcpListener(8888)` awaits for the connection on given port. Then, when it accepts the connection from client, it establishes connection on different socket `Socket socket = listener.AcceptSocket()` so that listening port remains awaiting for oth...
The term client has two definitions. At the application level you have a client and server application. The client is the master and the server is the slave. At the socket level, both the client application and server application have a client (also called a socket). The server socket listens at the loopback address 12...
4,587
16,251,016
Hi all i want to web based GUI Testing tool. I found dogtail is written using python. but i didnot get any good tutorial and examples to move further. Please Guide me weather dogtail is perfect or something better than this in python is there?. and if please share doc and example. My requirement: A DVR continuous sho...
2013/04/27
[ "https://Stackoverflow.com/questions/16251016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2017556/" ]
[Selenium](https://pypi.python.org/pypi/selenium) is designed exactly for this, it allows you to control the browser in Python, and check if things are as expected (e.g check if a specific element exists, submit a form etc) There's [some more examples in the documentation](http://selenium-python.readthedocs.org/en/lat...
Selenium provides a python interface rather than just record your mouse movements, see <http://selenium-python.readthedocs.org/en/latest/api.html> If you need to check your video frames your can record them locally and OCR the frames looking for some expected text or timecode.
4,588
52,928,809
Hi I am a beginner in python coding! This is my code: ``` while True: try: x=raw_input("Please enter a word: ") break except ValueError: print( "Sorry it is not a word. try again") ``` The main aim of this code is to check the input. If the input is string than OK, but when the input ...
2018/10/22
[ "https://Stackoverflow.com/questions/52928809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10540371/" ]
Try using KV0, it works for me: ``` - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [[AVAudioSession sharedInstance] setActive:YES error:nil]; [[AVAudioSession sharedInstance] addObserver:self forKeyPath:@"outputVolume" options:0 context:nil]; ...
Apparently, my code worked ok. The problem was with my laptop - it had some volume issue, some when I was changing the volume on the simulator, the volume didn't really changed. When I switched to a real device, everything worked properly
4,591
57,745,554
I am trying to write a script in python so I can find in 1 sec the COM number of the USB serial adapter I have plugged to my laptop. What I need is to isolate the COMx port so I can display the result and open putty with that specific port. Can you help me with that? Until now I have already written a script in batch/...
2019/09/01
[ "https://Stackoverflow.com/questions/57745554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4964403/" ]
this is a follow up answer from @MacrosG i tried a minimal example with properties from Device ``` from infi.devicemanager import DeviceManager dm = DeviceManager() dm.root.rescan() devs = dm.all_devices print ('Size of Devs: ',len(devs)) for d in devs: if "USB" in d.description : print(d.description...
If Python says the strings are not the same I dare say it's quite likely they are not. You can compare with: ``` if "USB Serial Port" in devs[i]: ``` Then you should be able to find not a complete letter by letter match but one that contains a USB port. There is no need to use numpy, `devs` is already a list and...
4,592
55,007,820
I've the following problem : I'm actually making a script for an ovirt server to automatically delete virtual machine which include unregister them from the DNS. But for some very specific virtual machine there is multiple FQDN for an IP address example: ``` myfirstfqdn.com IN A 10.10.10.10 mysecondfqdn.com IN A 10.10...
2019/03/05
[ "https://Stackoverflow.com/questions/55007820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8919169/" ]
That's outright impossible. If I am in the right mood, I could add an entry to my DNS server pointing to your IP address. Generally, you cannot find it out (except for some hints in some protocols like http(s)).
Given a zone file in the above format, you could do something like... ``` from collections import defaultdict zone_file = """myfirstfqdn.com IN A 10.10.10.10 mysecondfqdn.com IN A 10.10.10.10""" # Build mapping for lookups ip_fqdn_mapping = defaultdict(list) for record in zone_file.split("\n"): fqdn, record_cla...
4,595
52,588,535
I was trying to pass some arguments via PyCharm when I noticed that it's behaving differently that my console. When I pass arguments with no space in between all works fine, but when my arguments contains spaces inside it the behavior diverge. ``` def main(): """ Main function """ for i, arg in enumera...
2018/10/01
[ "https://Stackoverflow.com/questions/52588535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3584765/" ]
You can use [`String.prototype.trim()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim): ```js const title1 = "DisneyLand-Paris"; const title2 = "DisneyLand-Paris "; const trimmed = title2.trim(); console.log(title1 === title2); // false console.log(title1 === trimmed...
You need to use trim() method ``` const string1 = "DisneyLand-Paris"; const string2 = "DisneyLand-Paris "; const string3 = ""; if(string1 === string2.trim()){ string3 = `it's the same titles ` ; //here you have to use template literals because of it’s console.log(string3); } ```
4,596
11,329,212
I have started to look into python and am trying to grasp new things in little chunks, the latest goal i set for myself was to read a tab seperate file of floats into memory and compare values in the list and print the values if difference was as large as the user specified. I have written the following code for it so ...
2012/07/04
[ "https://Stackoverflow.com/questions/11329212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1093485/" ]
Try this in place of your list comprehension: ``` y = [float(i) for i in line.split()] ``` *Explanation*: The data you read from the file are strings, to convert them to other types you need to cast them. So in your case you want to cast your values to float via `float()` .. which you tried, but not quite correctly...
The list comprehension isn't doing what you think it's doing. It's simply assigning each string to the variable `float`, and returning it. Instead you actually want to use another name and call float on it: ``` y = [float(x) for x in line.split()] ```
4,597
46,824,700
With Rebol pick I can only get one element: ``` list: [1 2 3 4 5 6 7 8 9] pick list 3 ``` In python one can get a whole sub-list with ``` list[3:7] ```
2017/10/19
[ "https://Stackoverflow.com/questions/46824700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/310291/" ]
* [**AT**](http://www.rebol.com/docs/words/wat.html) can seek a position at a list. * [**COPY**](http://www.rebol.com/r3/docs/functions/copy.html) will copy from a position to the end of list, by default * the **/PART** refinement of COPY lets you add a limit to copying Passing an integer to /PART assumes how many thi...
``` >> list: [1 2 3 4 5 6 7 8 9] == [1 2 3 4 5 6 7 8 9] >> copy/part skip list 2 5 == [3 4 5 6 7] ``` So, you can skip to the right location in the list, and then copy as many consecutive members as you need. If you want an equivalent function, you can write your own.
4,599
20,383,924
What I am trying to do is access the traffic meter data on my local netgear router. It's easy enough to login to it and click on the link, but ideally I would like a little app that sits down in the system tray (windows) that I can check whenever I want to see what my network traffic is. I'm using python to try to acc...
2013/12/04
[ "https://Stackoverflow.com/questions/20383924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1777330/" ]
Okay, I found the solution and it was way easier than I thought. I did try John1024's suggestion and was able to download the proper webpage from the router using wget. However I didn't like the fact that wget saved the result to a file, which I would then have to open and parse. I ended up going back to the original ...
The web interface for my Netgear router (WNDR3700) is also filled with javascript. Yours may differ but I have found that my scripts can get all the info they need without javascript. The first step is finding the correct URL. Using FireFox, I went to the traffic page and then used "This Frame -> Show only this frame"...
4,600
29,516,084
Getting the following error when trying to install Pandas (0.16.0), which is in my requirements.txt file, on AWS Elastic Beanstalk EC2 instance: ``` building 'pandas.msgpack' extension gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-si...
2015/04/08
[ "https://Stackoverflow.com/questions/29516084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1177562/" ]
For pandas being compiled on Elastic Beanstalk, make sure to have both packages: `gcc-c++` *and* `python-devel` ``` packages: yum: gcc-c++: [] python-devel: [] ```
Install `python-dev` ``` sudo apt-get install python-dev ``` For `python3` ``` sudo apt-get install python3-dev ```
4,601
68,341,995
I have a python file that basically runs a main() function which scrapes data given a given keyword. I am trying to do multiprocessing so my main function in my Jupyter Notebook looks like ``` p1 = multiprocessing.Process(target=main, args=['cosmetics']) p2 = multiprocessing.Process(target=main, args=['airpod pro case...
2021/07/12
[ "https://Stackoverflow.com/questions/68341995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16404222/" ]
No, it's not that running the module using a terminal won't save files, that's actually the way you run python modules. Check your main() whether it is actually writing the CSV file or not.
the only question i saw in here was `Does running python file on termina/cmd not allow saving csv files?` the answer is no... its fine to save csv files in the command line typically ``` open("output.csv","w") as f: f.write("this,is\na,csv") ```
4,605
5,436,227
I have a sandbox PAYPAL area, My language is python - Django and I use django-paypal ipn tes on my server works but when someone try to buy something, after paypal process in sandbox I don't receive signal and in my paypal\_ipn I don't see the transaction. So the problem is that I don't receive the signal. This is my s...
2011/03/25
[ "https://Stackoverflow.com/questions/5436227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/677220/" ]
I think you can use the Paypal Test Tools to send fake notifactions to your notify url. That might make it easier to debug. <http://www.friendly-stranger.com/pictures/paypal.jpg> What you can also do is run the tests that come with django-paypal. It should be something like ``` python manage.py test paypal ``` Yo...
I had a similar problem. In my case, I could see from access logs that PayPal *is* accessing my payment notification URL, and the requests are 200 OK, but no signals triggered on Django side. Turned out that payments had "Pending" status instead of "Completed" (and I wasn't listening on `paypal.standard.ipn.signals.pa...
4,607
12,138,298
I am trying to use "With open()" with python 2.6 and it is giving error(Syntax error) while it works fine with python 2.7.3 Am I missing something or some import to make my program work! Any help would be appreciated. Br My code is here: ``` def compare_some_text_of_a_file(self, exportfileTransferFolder, exportfile...
2012/08/27
[ "https://Stackoverflow.com/questions/12138298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864924/" ]
The `with open()` statement is supported in Python 2.6, you must have a different error. See [PEP 343](http://www.python.org/dev/peps/pep-0343/) and the python [File Objects documentation](http://docs.python.org/library/stdtypes.html#file-objects) for the details. Quick demo: ``` Python 2.6.8 (unknown, Apr 19 2012, ...
The `with open()` syntax is supported by Python 2.6. On Python 2.4 it is not supported and gives a syntax error. If you need to support PYthon 2.4, I would suggest something like: ``` def readfile(filename, mode='r'): f = open(filename, mode) try: for line in f: yield f except e: ...
4,610
63,805,737
i am trying to implement the following code but it is throwing an error TypeError ``` Traceback (most recent call last) <ipython-input-29-6ed67c712ed4> in <module>() 28 return model 29 ---> 30 model = nvidia_model() 31 print(model.summary()) 32 # dead relu problem: when a node i...
2020/09/09
[ "https://Stackoverflow.com/questions/63805737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14206313/" ]
I was stuck on the same error. Here's what I found: `Convolution2D` is a Keras v1 API (docs: <https://faroit.com/keras-docs/1.2.2/layers/convolutional/>) `Conv2D` is the newer v2 API (docs: <https://faroit.com/keras-docs/2.0.5/layers/convolutional/>). I got it working with the following changes: 1. Changed `import ...
Try using pooling instead of subsample. Usually that will work.
4,613
12,521,189
I'm familiar with programming but new to python: > > mem = [0] \* memloadsize > > > what does the '[0]' represent? Is it a built-in array?
2012/09/20
[ "https://Stackoverflow.com/questions/12521189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493578/" ]
The `[` and `]` characters, in this context, are used to construct array literals: ``` >>> [] [] >>> [0] [0] >>> ['a', 'b', 'c'] ['a', 'b', 'c'] ``` Multiplying arrays is idiomatic, and generates an array gotten by repeating the elements in the array by the given factor: ``` >>> ['a'] * 4 ['a', 'a', 'a', 'a'] >>> [...
It just means a one element `list` containing just a 0. Multiplying by `memloadsize` gives you a `list` of `memloadsize` zeros.
4,618
6,522,281
I've got a program that downloads part01, then part02 etc of a rar file split across the internet. My program downloads part01 first, then part02 and so on. After some tests, I found out that using, on example, UnRAR2 for python I can extract the first part of the file (an .avi file) contained in the archive and I'm ab...
2011/06/29
[ "https://Stackoverflow.com/questions/6522281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774236/" ]
You are talking about an .avi file inside the rar archives. Are you sure the archives are actually compressed? [Video files released by the warez scene do not use compression:](http://en.wikipedia.org/wiki/Standard_%28warez%29#Packaging) > > Ripped movies are still packaged due to the large filesize, but compression ...
I highly doubt it. By nature of compression (from my understanding), every bit is needed to uncompress it. It seems that the source of where you are downloading from has intentionally broken the avi into pieces before compression, but by the time you apply compression, whatever you compressed is now one atomic unit. So...
4,621
57,604,719
I was trying to install thrift(0.11.0) over my system(macOs 10.14.5).For which I downloaded and extracted tar file. Then I ran following commands : ``` ./bootstrap.sh ./configure make make install ``` But **make install** throwed the following error : ``` error: could not create '/usr/lib/python2.7/site-packages': ...
2019/08/22
[ "https://Stackoverflow.com/questions/57604719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6729549/" ]
1.open thrift's subfolder lib/py/ and modify the Makefile as follow: PY\_PREFIX=/usr change to PY\_PREFIX = /Users/amy/python 2.sudo make install
I faced the same problem trying to install thrift on Mac OS. I found a separate guide for installing thrift on Mac OS, I tried it and it finally worked successfully: 1- Download the boost library from [boost.org](http://www.boost.org/) untar compile with ``` ./bootstrap.sh sudo ./b2 threading=multi address-model=64...
4,624
17,577,403
I am trying to write an HTML parser in Python that takes as its input a URL or list of URLs and outputs specific data about each of those URLs in the format: URL: data1: data2 The data points can be found at the exact same HTML node in each of the URLs. They are consistently between the same starting tags and ending ...
2013/07/10
[ "https://Stackoverflow.com/questions/17577403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2479631/" ]
``` import urllib2 from bs4 import BeautifulSoup url = 'http://www.youtube.com/watch?v=QOdW1OuZ1U0' f = urllib2.urlopen(url) data = f.read() soup = BeautifulSoup(data) span = soup.find('span', attrs={'class':'watch-view-count'}) print '{}:{}'.format(url, span.text) ``` If you do not want to use `BeautifulSoup`, you...
I prefer `HTMLParser` over `re` for this type of task. However, `HTMLParser` can be a bit tricky. I use immutable objects to store data... I'm sure this this the wrong way of doing it. But its worked with several projects for me in the past. ``` import urllib2 from HTMLParser import HTMLParser import csv position =...
4,625
55,700,995
I have. directory with ~250 .txt files in it. Each of these files has a title like this: `Abraham Lincoln [December 01, 1862].txt` `George Washington [October 25, 1790].txt` etc... However, these are terrible file names for reading into python and I want to iterate over all of them to change them to a more suitable...
2019/04/16
[ "https://Stackoverflow.com/questions/55700995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10587373/" ]
Please try the straightforward (tedious) bash script: ``` #!/bin/bash declare -A map=(["January"]="01" ["February"]="02" ["March"]="03" ["April"]="04" ["May"]="05" ["June"]="06" ["July"]="07" ["August"]="08" ["September"]="09" ["October"]="10" ["November"]="11" ["December"]="12") pat='^([^[]+) \[([A-Za-z]+) ([0-9]+)...
I like to pull the filename apart, then put it back together. Also GNU date can parse-out the time, which is simpler than using `sed` or a big `case` statement to convert "October" to "10". ``` #! /usr/bin/bash if [ "$1" == "" ] || [ "$1" == "--help" ]; then echo "Give a filename like \"Abraham Lincoln [December...
4,626
70,627,862
How can i build a nested python dictionary, based on **number** of levels, like this? How can be the recursive function passing int of levels? ``` { "aggs": { "cat_level_1": { "terms": { "field": "cat_level_1" }, "aggs": { "cat_level_2": {...
2022/01/07
[ "https://Stackoverflow.com/questions/70627862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8881622/" ]
We can build the dictionary from the deepest level, wrapping the previously built dictionary on each level. ```py def dict_with_depth_of(n): return { "aggs": { f"cat_level_{n}": { "terms": { "field": f"cat_level_{n}" } } } ...
This is the right answer ``` def dict_with_depth_of(n): return { "aggs": { f"cat_level_{n}": { "terms": { "field": f"cat_level_{n}" } } } } def nested_dict(n): d = None for i in reversed(range(1, n + 1)): ...
4,628
32,194,643
So I am trying to use jinja2 for a simple html template but I keep getting this error when I call `render()`: ``` Warning: IronPythonEvaluator.EvaluateIronPythonScript operation failed. Traceback (most recent call last): File "C:\Program Files (x86)\IronPython 2.7\Lib\jinja2\jinja2\loaders.py", line 125, in load Fil...
2015/08/25
[ "https://Stackoverflow.com/questions/32194643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3263488/" ]
Button should be of custom type to set an image. Verify your code once again. Set the button to custom type in Storyboard.
I can see you are using IBOutlet of a button this means you are using button from nib, then you should change background image from Attributes Inspector on right side of your xcode otherwise if you still need it to be changed programmatically then try this ``` [self.color1 setBackgroundImage:[UIImage imageNamed:@"57_...
4,629
72,596,436
I've read about and understand [floating point round-off issues](https://docs.python.org/3/tutorial/floatingpoint.html) such as: ``` >>> sum([0.1] * 10) == 1.0 False >>> 1.1 + 2.2 == 3.3 False >>> sin(radians(45)) == sqrt(2) / 2 False ``` I also know how to work around these issues with [math.isclose()](https://do...
2022/06/12
[ "https://Stackoverflow.com/questions/72596436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/424499/" ]
The key to the solution is to build a wrapper that overrides the `__eq__` method and replaces it with an approximate match: ``` import cmath class Approximately(complex): def __new__(cls, x, /, **kwargs): result = complex.__new__(cls, x) result.kwargs = kwargs return result def __eq_...
Raymond's answer is very fancy and ergonomic, but seems like a lot of magic for something that could be much simpler. A more minimal version would just be to capture the calculated value and just explicitly check whether the things are "close", e.g.: ``` import math match 1.1 + 2.2: case x if math.isclose(x, 3.3)...
4,631
5,684,010
I want to change this string `<p><b> hello world </b></p>. I am playing <b> python </b>` to: `<bold><bold>hello world </bold></bold>, I am playing <bold> python </bold>` I used: ``` import re pattern = re.compile(r'\<p>(.*?)\</p>|\<b>(.*?)\</b>') print re.sub(pattern, r'<bold>\1</bold>', "<p><b>hello world</b>...
2011/04/16
[ "https://Stackoverflow.com/questions/5684010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/293487/" ]
If you choose not to use regex, then it simple as this: ``` d = {'<p>':'<bold>','</p>':'</bold>','<b>':'<bold>','</b>':'</bold>'} s = '<p><b> hello world </b></p>. I am playing <b> python </b>' for k,v in d.items(): s = s.replace(k,v) ```
The problem is because the first group is the one within `<p></p>` and the second group is within `<b></b>` in the regexp. However, in your substitution you are referring to the first group when, if it matched to `<b></b>`, there wasn't one. I offer a couple of solutions. First, ``` >>> pattern = re.compile(r'<(p|b...
4,632
5,931,386
I help to maintain a package for python called nxt-python. It uses metaclasses to define the methods of a control object. Here's the method that defines the available functions: ``` class _Meta(type): 'Metaclass which adds one method for each telegram opcode' def __init__(cls, name, bases, dict): supe...
2011/05/09
[ "https://Stackoverflow.com/questions/5931386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/495504/" ]
For plain functions: ``` def f(): # for demonstration pass f.__doc__ = "Docstring!" help(f) ``` This works in both python2 and python3, on functions with and without docstrings defined. You can also do `+=`. Note that it is `__doc__` and not `__docs__`. For methods, you need to use the `__func__` attribute of...
You may also use [setattr](http://docs.python.org/library/functions.html#setattr) on the class/function object and set the docstring. ``` setattr(foo,'__doc__',"""My Doc string""") ```
4,634
41,252,289
What's the syntax for *exclusive* `min` and `max` arguments for redis `zcount` command in python (redis-py)? It's not alluded to in the [documentation](https://redis-py.readthedocs.io/en/latest/). Would it be: ``` minimum = time.time() - 2000 maximum = time.time() my_server.zadd(sorted_set, '('+str(minimum), maximum...
2016/12/20
[ "https://Stackoverflow.com/questions/41252289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4936905/" ]
The [unit tests](https://github.com/andymccurdy/redis-py/blob/eae07e76b6524e6772be60169549766e7826419a/tests/test_commands.py) gives some examples: ``` def test_zcount(self, r): r.zadd('a', a1=1, a2=2, a3=3) assert r.zcount('a', '-inf', '+inf') == 3 assert r.zcount('a', 1, 2) == 2 assert r.zcount('a', ...
What about using `sys.float_info.epsilon`? This is the smallest comparable difference between two numbers: ``` minimum = time.time() - 2000 maximum = time.time() my_server.zadd(sorted_set, minimum + sys.float_info.epsilon, maximum) ``` Or, with `-` for maximum: ``` minimum = time.time() - 2000 maximum = time.time()...
4,635
35,422,156
This is the code that I am working with: ``` import pandas as pd z = pd.Series(data = [1,2,3,4,5,6,7], index = xrange(1,8)) array = [] for i in range(1,8): array.append(z[i]*2) print array ``` It does exactly what I tell it to because I can't figure out how to do a simple iteration. This is the printed outp...
2016/02/16
[ "https://Stackoverflow.com/questions/35422156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5020060/" ]
You want to use the last value of the accumulation list in the expression. For example: ``` data = [ -3.2 , 30.66, 7.71, 9.87] # the input list for `sample` In [686]: test=[100000] In [687]: for i in range(4): test.append(test[-1]*(1+data[i]/100)) In [688]: test Out[688]: [100000, 96800.0, 126478.88, 1...
I think that what you're trying to do is to compute powers of two, instead of multiplications of two: ``` array.append(2**z[i]) ```
4,636
20,993,084
I am new to python and been stuck with an issue, any one please help me to solve this issue. Requirement is I have created a sqlite database and created a table and also inserted values to it but the problem is I am not getting how to display that data from database in table view in python so please help me out from th...
2014/01/08
[ "https://Stackoverflow.com/questions/20993084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2440020/" ]
This is a short, albeit complete example on how to achieve the expected result. The trick is to define a [QSqlQueryModel](http://srinikom.github.io/pyside-docs/PySide/QtSql/QSqlQueryModel.html?highlight=qsqlquerymodel#PySide.QtSql.QSqlQueryModel) and pass it to a [QTableView](http://srinikom.github.io/pyside-docs/PySid...
I know this question has been a long time ago and the accepted one is for PyQt4. Because the API has been changed a bit on PyQt5, hope my answer can help someone using PyQt5. ``` from PyQt5 import QtWidgets, QtSql # connect to postgresql db = QtSql.QSqlDatabase.addDatabase("QPSQL") db.setHostName(**) db.setDatabaseNam...
4,637
62,713,159
I have a csv file with names (last\_name, name, age) and I want to convert all age attributes into integers. This is a way but I guess there is a more pythonic way to do so? I tried to do it with list comprehension but it didn't quite worked as I wanted. ``` import csv with open("names.csv") as names_file: head ,...
2020/07/03
[ "https://Stackoverflow.com/questions/62713159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13607895/" ]
Best way to handle this: ``` import pandas as pd df = pd.read_csv('names.csv') df["age"] = pd.to_numeric(df["age"]) ``` If you want a list just do this: ```py list_ = df['age'].to_list() print(list_) ```
I would do: ``` names = [['A', 'B', '20'], ['C', 'D', '30'], ['E', 'F', '40']] # sample data for i in names: i[2] = int(i[2]) print(names) ``` Which is more succint than: ``` for i in range(len(names)): names[i][2] = int(names[i][2]) ``` If you have to use list-comprehension then you might do: ``` names...
4,638
33,982,834
I have been trying to convert some code into a try statement but I can't seem to get anything working. Here is my code in pseudo code: ``` start run function check for user input ('Would you like to test another variable? (y/n) ') if: yes ('y') restart from top elif: no ('n') exit program (loop is at end of progra...
2015/11/29
[ "https://Stackoverflow.com/questions/33982834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5552713/" ]
If you want to make your code neater, you should consider having `while run:` instead of `while run == True:` and also remove the last two lines, because setting `run` and `cont` to `True` again isn't necessary (their value didn't change). Furthermore, I think that a `try - except` block would be useful in the ca...
> > Ok so as a general case I will try to avoid try...except blocks > > > Don't do this. Use the right tool for the job. Use `raise` to signal that your code can't (or shouldn't) deal with the scenario. Use `try-except` to process that *signal*. > > Now what is the proper way for me to convert this into a tr...
4,640
14,286,480
I tagged python and perl in this only because that's what I've used thus far. If anyone knows a better way to go about this I'd certainly be willing to try it out. Anyway, my problem: I need to create an input file for a gene prediction program that follows the following format: ``` seq1 5 15 seq1 20 34 seq2 50 48 s...
2013/01/11
[ "https://Stackoverflow.com/questions/14286480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1784467/" ]
In Unix: ``` grep <file.gff3 " exon " | sed "s/^\([^ ]+\) +[.] +exon +\([0-9]+\) \([0-9]+\).*$/\1 \2 \3/" ```
For pedestrians: (this is Python) ``` with open(data_file) as f: for line in f: tokens = line.split() if len(tokens) > 3 and tokens[2] == 'exon': print tokens[0], tokens[3], tokens[4] ``` which prints ``` PITG_00002 2 397 PITG_00004 1 1275 PITG_00004 1397 1969 ```
4,641
6,254,713
How can I create a numpy matrix with its elements being a function of its indices? For example, a multiplication table: `a[i,j] = i*j` An Un-numpy and un-pythonic would be to create an array of zeros and then loop through. There is no doubt that there is a better way to do this, without a loop. However, even better ...
2011/06/06
[ "https://Stackoverflow.com/questions/6254713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349043/" ]
Here's one way to do that: ``` >>> indices = numpy.indices((5, 5)) >>> a = indices[0] * indices[1] >>> a array([[ 0, 0, 0, 0, 0], [ 0, 1, 2, 3, 4], [ 0, 2, 4, 6, 8], [ 0, 3, 6, 9, 12], [ 0, 4, 8, 12, 16]]) ``` To further explain, `numpy.indices((5, 5))` generates two arra...
I'm away from my python at the moment, but does this one work? ``` array( [ [ i*j for j in xrange(5)] for i in xrange(5)] ) ```
4,646
6,975,808
I like to store my data after a longish python program as dictionaries in a new script. This then allows me to import the program (and hence data) easily for further manipulation. I write something like this (an old example): ``` file = open(p['results']+'asa_contacts.py','w') print>>file, \ ''' \''' This file stores...
2011/08/07
[ "https://Stackoverflow.com/questions/6975808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299000/" ]
Unless there's a specific reason that you need source code -- and I suspect there isn't, you just want to serialize and deserialize data from disk -- a better option would be Python's [`pickle` module](http://docs.python.org/library/pickle.html).
[Lossy's suggestion](https://stackoverflow.com/questions/6975808/outputting-data-as-dictionaries-in-a-new-python-file/6975843#6975843) of `repr` happens to work, but `repr` isn't *specifically* designed for serialization. I think it would be slightly more robust to use a tool designed for that purpose; and since you wa...
4,653
48,765,260
Object oriented python, I want to create a static method to convert hours, minutes and seconds into seconds. I create a class called Duration: ``` class Duration: def __init__(self, hours, minutes, seconds): self.hours = hours self.minutes = minutes self.seconds = secon...
2018/02/13
[ "https://Stackoverflow.com/questions/48765260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6715237/" ]
You're almost there. Instead of passing the result of `duration1.info()` to `duration1.static_method()`, you simply pass the whole object: ``` duration1 = Duration(29, 7, 10) print(duration1.info()) # 29-07-10 print(duration1.static_method(duration1)) # 104830 ``` And since it's a static method, you could just as w...
A static method is *explicitly* a function which is tied to a class rather than an instance. `self` in Python represents an instance of a class in Python. These are not simpatico. You can make your code work by passing `duration1` to your static method and changing the name of its accepted parameter from `self` to ...
4,655
33,432,426
I am trying to import `requests` module, but I got this error my python version is 3.4 running on ubuntu 14.04 ``` >>> import requests Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/requests/packages/urllib3/connectionpool.py", line 10, in <module> from queue import LifoQueue, Em...
2015/10/30
[ "https://Stackoverflow.com/questions/33432426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5104452/" ]
`import queue` is **lowercase** `q` in Python 3. Change `Q` to `q` and it will be fine. (See code in <https://stackoverflow.com/a/29688081/632951> for smart switching.)
It's because of the Python version. In Python 2.x it's `import Queue as queue`; on the contrary in Python 3 it's `import queue`. If you want it for both environments you may use something below as mentioned [here](https://stackoverflow.com/questions/46363871/no-module-named-queue?noredirect=1&lq=1) ``` try: import ...
4,656
57,229,074
I am trying to import an existing database into my **Django** project, so I run `python manage.py migrate --fake-initial`, but I get this error: ``` operations to perform: Apply all migrations: ExcursionsManagerApp, GeneralApp, InvoicesManagerApp, OperationsManagerApp, PaymentsManagerApp, RatesMan agerApp, ReportsMa...
2019/07/27
[ "https://Stackoverflow.com/questions/57229074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6843153/" ]
Just by running the following [command](https://docs.djangoproject.com/en/3.1/ref/django-admin/#cmdoption-migrate-fake) would solve the problem: ``` python manage.py migrate --fake ```
Steps you can follow to make migrations from an existing database. Firstly empty the django migration table from the database. ```sql delete from django_migrations ``` 1. Remove migrations from your migrations folder for the app ```sh rm -rf <app>/migrations/ ``` 2. Reset the migration for builtin apps(like admin...
4,666
26,327,497
**WHAT IS WORKING** I'm following [wsgi documentation to run django](http://uwsgi-docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html#test-your-django-project). I'm testing that it's all working before start to use nginx. I succeeded running manage.py and loading the webpage in my browser: ``` python manag...
2014/10/12
[ "https://Stackoverflow.com/questions/26327497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2010764/" ]
**SOLUTION:** An incorrect configuration in wsgi.py was making uWSGI unable to call the application. I solved it using this wsgi.py: ``` import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "metrics.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() ``` And runnin...
1): Highly recommend run uwsgi in emperor mode. ``` /usr/bin/uwsgi --emperor /etc/uwsgi --pidfile /var/run/uwsgi.pid --daemonize /var/log/uwsgi.log ``` 2) Example wsgi.py for your project: ``` import os import sys ADD_PATH = ['/home/ubuntu/web/metrics.com/app/',] for item in ADD_PATH: sys.path.insert (0, item) ...
4,668
46,895,876
I have a script `wordcount.py` I used setuptools to create an entry point, named `wordcount`, so now I can call the command from anywhere in the system. I am trying to execute it via spark-submit (command: `spark-submit wordcount`) but it is failing with the following error: `Error: Cannot load main class from J...
2017/10/23
[ "https://Stackoverflow.com/questions/46895876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7963251/" ]
This is pretty similar to Jaap's comment, but a little more spelled out and uses the row names explicitly: ``` mat = as.matrix(dat[, 2:5]) row.names(mat) = dat$MUN mat = rbind(mat, colSums(mat[c("Angra dos Reis (RJ)", "Areal (RJ)"), ], na.rm = T)) row.names(mat)[nrow(mat)] = "X" mat # X1990 X19...
A solution can be using sqldf package. If the name of the data frame is `df`, you can do it likes the following: ``` library(sqldf) result <- sqldf("SELECT * FROM df UNION SELECT 'X', SUM(X1990), SUM(X1991), SUM(X1992), SUM(X1993) FROM df WHERE MUN IN ('Angra dos Reis (RJ)', 'Areal (RJ)')") ```
4,669
4,119,054
I'm looking for a finance library in python which offers a method similar to the MATLAB's [portalloc](http://www.mathworks.com/help/toolbox/finance/portalloc.html) . It is used to optimize a portfolio.
2010/11/07
[ "https://Stackoverflow.com/questions/4119054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/409701/" ]
If you know linear algebra, there is a simple function for solving the optimization problem which any library should support. Unfortunately, it's been so long since I researched it I can't tell you the formula nor a library that supports it, but a little research should reveal it. The main point is that any linear alge...
Maybe you could use this [library](http://www.downv.com/Mac/download-Python-statlib-10009752.htm) (statlib) or this [one](http://www.downv.com/Mac/download-Mystic-10004716.htm) (Mystic) to help you.
4,674
71,929,367
Please don't delete this. this is so simple but I'm banging my head making this work for last two hours. As displayed. I want to import python file module\_dir into module\_sub\_dir.py, but its giving erros. all **init**.py are empty.[![enter image description here](https://i.stack.imgur.com/MYBST.png)](https://i.stac...
2022/04/19
[ "https://Stackoverflow.com/questions/71929367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11268322/" ]
Add `sys.path.append("..")` to the very beginning then importlib will be able to reach the file in parent directories of CWD. But I recommend you not to use such ugly solution in your projects.
Update as I have figured out the issue myslef. So the issue is how VS Code runs .py file individually as oppose to running entire package like Pycharm. It works in Pycharm. To make it work in VS Code sys.import.path('..') works.
4,678
58,455,061
Suppose python dictionary is like D = {'a':1,'a':2} Can I get those 2 values with same key Because I want write a function so I can get dictionary like above?
2019/10/18
[ "https://Stackoverflow.com/questions/58455061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5961544/" ]
Dictionary keys in Python are unique. Python will resolve `D = {'a':1,'a':2}` as `D = {'a': 2}` You can effectively store multiple values under the same key by storing a list under that key. In your case, ``` D = {'a': [1, 2]} ``` This would allow you to access the elements of 'a' by using ``` D['a'][elementIdx]...
You cannot. I set up an identical dictionary, and when attempting to print the key `'a'`, I received the secondary value, i.e., `2`. Keys are meant to be unique. You could try something like: ``` x = {} for i in range(2): x[f"a{i}"] = i ``` Which would output key values like `a0, a1, etc.`
4,679
1,062,803
Take two lists, second with same items than first plus some more: ``` a = [1,2,3] b = [1,2,3,4,5] ``` I want to get a third one, containing only the new items (the ones not repeated): ``` c = [4,5] ``` The solution I have right now is: ``` >>> c = [] >>> for i in ab: ... if ab.count(i) == 1: ... c.append(i...
2009/06/30
[ "https://Stackoverflow.com/questions/1062803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65459/" ]
at the very least use a list comprehension: ``` [x for x in a + b if (a + b).count(x) == 1] ``` otherwise use the [set](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset) class: ``` list(set(a).symmetric_difference(set(b))) ``` there is also a more compact form: ``` list(set(a) ^ set(b)) ```
Items in b that aren't in a, if you need to preserve order or duplicates in b: ``` >>> a = [1, 2, 3] >>> b = [1, 2, 3, 4, 4, 5] >>> a_set = set(a) >>> [x for x in b if x not in a_set] [4, 4, 5] ``` Items in b that aren't in a, not preserving order, and not preserving duplicates in b: ``` >>> list(set(b) - set(a)) [...
4,680
70,992,422
When running xlwings 0.26.1 (latest for Anaconda 3.83) or 0.10.0 (using for compatibility reasons) with the latest version of `Office 365 Excel`, I get an error after moving a sheet when running `app.quit()`: ``` import xlwings as xw import pythoncom pythoncom.CoInitialize() app = xw.apps.add() app.display_alerts = F...
2022/02/04
[ "https://Stackoverflow.com/questions/70992422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952542/" ]
I found the problem If `mcr.microsoft.com/windows/nanoserver:1809` image is used then arguments should be used in %arg% format. If `mcr.microsoft.com/dotnet/framework/sdk:4.8` image is used then arguments should be used in $env:arg format. It is confusing and I haven't found where it is documented.
This looks like it might be a bug. When you have a build arg with the same name as an already existing environment variable, Docker will use the already set environment variable instead of the build arg. The framework image you use already has an environment variable called DOTNET\_VERSION, so you can't access the bu...
4,690
53,092,936
I need some help with a assignment for python. The task is to convert a .csv file to a dictionary, and do some changes. The problem is that the .csv file only got 1 column, but 3 rows. The .csv file looks like this in excel ``` A B 1.male Bob West 2.female Hannah South 3.male B...
2018/10/31
[ "https://Stackoverflow.com/questions/53092936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10470153/" ]
You can use dict comprehension and enumerate the `csv` object, ``` import csv reader = csv.reader(open("filename.csv")) x = {num+1:name[0].split(" ",1)[-1].rstrip() for (num, name) in enumerate(reader)} print(x) # output, {1: 'Bob West', 2: 'Hannah South', 3: 'Bruce North'} ``` Or you can do it without using `csv...
This should work for the given input: data.csv: ========= ``` 1.male Bob West, 2.female Hannah South, 3.male Bruce North, ``` Code: ===== ``` import csv reader = csv.reader(open("data.csv")) d = {} for row in reader: splitted = row[0].split('.') # print splitted[0] # print ' '.join(splitted[1].split(' ')[...
4,691
13,788,688
I'm using a python code to get data from my server. However, I keep getting a "u" as a prefix to each key in the JSON as follows: ``` "{u'BD': 271, u'PS': 48, u'00': 177, u'CA': 5, u'DE': 15, u'FR': 18, u'UM': 45, u'KR': 6, u'IL': 22181, u'GB': 15}" ``` My python code is as follows: ``` from json import dumps ans ...
2012/12/09
[ "https://Stackoverflow.com/questions/13788688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432779/" ]
The `u''` means the value is a unicode literal. Everything is working as intended, you don't need to get rid of those. JSON is a standard that supports Unicode values natively, and thus the `json` module accepts unicode strings when converting a Python value to JSON: ``` >>> import json >>> ans={u'BD': 271, u'PS': 48...
I think something got mixed up here. The result you've posted looks like a Python representation of a dict. To be precise: json.dumps returns a string, so its result should be enclosed in quotes, like this: ``` >>> import json >>> json.dumps({'foo': 'bar'}) '{"foo": "bar"}' ```
4,698
32,540,092
I have a jinja2 template designed to print out the IP addresses of ec2 instances (tagged region: au) : ``` {% for host in groups['tag_region_au'] %} ``` My problem is I can't for the life of me work out how to include only hosts that exist in one group and NOT another (however each host may be in two or more groups)...
2015/09/12
[ "https://Stackoverflow.com/questions/32540092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264897/" ]
You can use built-in `group_names` variable in this case. `group_names` variable is a list of all groups that the current host is a member of. My `hosts` file: ``` [tag_region_au] host1 host2 host3 [tag_state_live] host2 host3 host4 ``` My template file `test.j2`: ``` {% for host in groups['tag_region_au'] %} {...
A really clean way to do it if you don't mind starting a new play for the templating stuff is to use a group expression in the play target (which is exactly what they're for). For example: ``` - hosts: tag_region_au:!tag_state_live tasks: - template: (bla) ``` Then in your template, you'd reference the `play_host...
4,699
7,549,403
How can I tell python to scan the current directory for a file called "filenames.txt" and if that file isn't there, to extract it from a zip file called "files.zip"? I know how to work zipfile, I just don't know how to scan the current directory for that file and use if/then loops with it..
2011/09/25
[ "https://Stackoverflow.com/questions/7549403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/715578/" ]
``` import os, zipfile if 'filenames.txt' in os.listdir('.'): print 'file is in current dir' else: zf = zipfile.ZipFile('files.zip') zf.extract('filenames.txt') ```
From the documentation ```none $ pydoc os.path.exists Help on function exists in os.path: os.path.exists = exists(path) Test whether a path exists. Returns False for broken symbolic links ```
4,700
11,209,646
Is there a python module that will do a waterfall plot like MATLAB does? I googled 'numpy waterfall', 'scipy waterfall', and 'matplotlib waterfall', but did not find anything.
2012/06/26
[ "https://Stackoverflow.com/questions/11209646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/908924/" ]
You can do a waterfall in matplotlib using the [PolyCollection](https://matplotlib.org/api/collections_api.html?highlight=polycollection#matplotlib.collections.PolyCollection) class. See this specific [example](https://matplotlib.org/examples/mplot3d/polys3d_demo.html) to have more details on how to do a waterfall usin...
Have a look at [mplot3d](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#wireframe-plots): ``` # copied from # http://matplotlib.sourceforge.net/mpl_examples/mplot3d/wire3d_demo.py from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax =...
4,702
61,575,311
I am trying to open up data from a CSV file in my Visual Studio terminal and receive: '''' ``` Traceback (most recent call last): File "/home/jubal/ CrashCourse Python Notes/Chapter 16 CC/Downloading Date/csv format/highs_lows.py", line 7, in <module> with open(filename) as f: FileNotFoundError: [Errno 2] No s...
2020/05/03
[ "https://Stackoverflow.com/questions/61575311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10457351/" ]
So the question says that `N` can be upto 10000, but your code assumes that it is no bigger than 100.
Regarding LTE, you are almost there. Try to replace the ``` for (int j = i + 1; j <= i + (p - 1); j++) tmp += skill[i] - skill[j]; ``` loop with the constant time expression. Hint: when the most skillful player leaves the window, by how much the training time for the rest players gets decreased?
4,707
64,397,933
I have a simple webpage that uses that okta web api: ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/...
2020/10/17
[ "https://Stackoverflow.com/questions/64397933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14465519/" ]
If you have created a custom mass update script you would have created parameters accessed like : ``` runtime.getCurrentScript().getParameter({name:'custscript....'}); ``` If so and you are then triggering the work flow via: ``` workflow.initiate({ recordType:'customer', ... ``` then you might do something li...
Create parameters in your script then when you are calling the custom action script in the workflow, pass the workflow field values to the script parameters.
4,708
31,361,482
I'm writing a porting a basic python script and creating a similarly basic Flask application. I have a file consisting of a bunch of functions that I'd like access to within my Flask application. Here's what I have so far for my views: ``` from flask import render_template from app import app def getRankingList(): ...
2015/07/11
[ "https://Stackoverflow.com/questions/31361482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316501/" ]
Simply have another python script file (for example `helpers.py`) in the same directory as your main flask .py file. Then at the top of your main flask file, you can do `import helpers` which will let you access any function in helpers by adding `helpers.` before it (for example `helpers.exampleFunction()`). Or you can...
Just import your file as usual and use functions from it: ``` # foo.py def bar(): return 'hey everyone!' ``` And in the main file: ``` # main.py from flask import render_template from app import app from foo import bar def getRankingList(): return 'hey everyone!' @app.route("/") @app.route("/index") def ...
4,709
33,775,658
So I have this operation in python `x = int(v,base=2)` which takes `v`as a Binary String. What would be the inverse operation to that? For example, given `1101000110111111011001100001` it would return `219936353`, so I want to get this binary string from the `219936353` number. Thanks
2015/11/18
[ "https://Stackoverflow.com/questions/33775658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3770881/" ]
Try out the bin() function. ``` bin(yourNumber)[2:] ``` will give you string containing bits for your number.
``` num = 219936353 print("{:b}".format(num)) --output:-- 1101000110111111011001100001 ``` The other solutions are all wrong: ``` num = 1 string = bin(1) result = int(string, 10) print(result) --output:-- Traceback (most recent call last): File "1.py", line 4, in <module> result = int(string, 10) ValueError:...
4,710