Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
3,300
49,990,731
Iterate File Saving Blocks and Skipping Lines
<p>I have data in blocks with non-data lines between the blocks. This code has been working but is not <em>robust</em>. How do I extract blocks and skip non-data blocks without consuming a line in the index test? I'm looking for a straight python solution without loading packages.</p> <p>I've searched for a relevant e...
<p>In the code posted, the line 4 is read, and the condition <code>index == BLOCK_DATA_ROWS</code> is met, leaving the first loop towards the second one. As <code>f</code> is a <a href="https://wiki.python.org/moin/Generators" rel="nofollow noreferrer">generator</a>, when it is called in the second loop, it returns the...
python|python-2.7|iteration
1
3,301
66,515,449
Combine Pandas dataframes with similar columns
<p>If I have 2 Pandas DataFrames that look like this:</p> <p>dframe1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;"></th> <th style="text-align: center;">col_a</th> <th style="text-align: center;">col_b</th> <th style="text-align: center;">col_x</th> <th style=...
<p>Using <code>append</code>:</p> <pre><code>dframe2.append(dframe1).fillna(0) </code></pre> <p>Output:</p> <pre><code> col_a col_b col_c col_d col_x col_y col_z 0 6 7 8.0 9.0 10 11 0.0 0 1 2 0.0 0.0 3 4 5.0 </code></pre>
python|pandas
1
3,302
53,071,836
formulating a class to bring in new data while referencing a dictionary
<p>I have: </p> <p>if you wanted to accomplish this with classes instead of functions so you could import a csv and run it on new data.</p> <p>Which class would you make first and how would you iterate through the class to compare each piece of data as a part is in every building with different quantities but the mas...
<p>You would just make the dictionary a data member of the class</p> <pre><code>class Container: def __init__(self): self.data = {"part": [], # Data member of class "building": [], "qty": []} # Pass self to method of class, so it can access data members de...
python|pandas|class|oop
1
3,303
65,364,332
How to draw keras CNN architecture?
<p>I want to draw Keras CNN architecture using my code. Any idea hot to draw that model.</p> <p>Any help would be appreciated.</p> <p>Thanks in advance</p> <p><strong>code:</strong></p> <pre><code>import keras from keras.models import Sequential from keras.layers import Model, Conv2D, MaxPooling2D, Flatten, Dense,Batch...
<p>As far I know, keras.utils has a built-in method named <code>plot_model()</code></p> <p>Have you tried this one?</p> <pre><code>tf.keras.utils.plot_model( model, to_file=&quot;model.png&quot;, show_shapes=False, show_dtype=False, show_layer_names=True, rankdir=&quot;TB&quot;, expand_nest...
python|keras|deep-learning|architecture|conv-neural-network
1
3,304
62,777,505
Relative Path Error When Migrating From Eclipse (PyDev) into VS Code
<p>I am completely new to the VS Code - find it very easy to use compared with Eclipse so I am trying to migrate our existing projects from Eclipse into VS Code.</p> <p>By selecting the folder as the eclipse file, the interpolator seems to be selected automatically. But I do see the error as below.</p> <pre><code>Excep...
<p>Two solutions:</p> <p>One: change the &quot;../log/Hedger.log&quot; to &quot;./log/Hedger.log&quot;.</p> <p>Two: in launch.json file setting '&quot;cwd&quot;: &quot;${workspaceFolder}/src&quot;,' in &quot;configurations&quot;.</p> <p>Explains:</p> <p><a href="http://$%7Bcwd%7D%20-%20the%20task%20runner%27s%20current...
python|eclipse|visual-studio-code
1
3,305
67,542,084
Why <span> does not contain the text in BeautifulSoup despite the fact that exactly the same <span> from the website contains it?
<p>I have to scrape <strong>3 elements</strong> from this website:</p> <p><a href="http://www.altitude-maps.com/city/170_562,Poznan,Wielkopolskie,Poland" rel="nofollow noreferrer">http://www.altitude-maps.com/city/170_562,Poznan,Wielkopolskie,Poland</a></p> <p>I need <strong>latitude, longitude and elevation</strong>, ...
<pre><code>import httpx import trio import re async def main(): async with httpx.AsyncClient(timeout=None) as client: r = await client.get('http://www.altitude-maps.com/city/170_562,Poznan,Wielkopolskie,Poland') goal = re.findall(r&quot;(lati|long|elev).*?'(.+)'&quot;, r.text) print(goal) ...
python|html|web-scraping|beautifulsoup
2
3,306
67,383,138
ValueError: Compute method failed to assign (Python3 odoo)
<p>There are three compute functions in my code. But I got the error.</p> <pre><code>Odoo Server Error Traceback (most recent call last): File &quot;/vagrant/odoo/odoo/addons/base/models/ir_http.py&quot;, line 237, in _dispatch result = request.dispatch() File &quot;/vagrant/odoo/odoo/http.py&quot;, line 682, ...
<p>I think it's syntax error. You forget to put a quote around function name. Computed function name should be inside a quote – <strong>compute='compute_date'</strong>. So is search function.</p> <p>In your case,</p> <pre><code>date = fields.Date(compute='compute_date', search='search_date') request_srcmst_names = fiel...
python|python-3.x|odoo|odoo-14
0
3,307
63,407,428
Input arguments to CTC loss in TensorFlow
<p>I wanted to use CTC loss for a sequence model and decided to use Tensorflow API. But when I tried the ctc_loss function, there were 2 arguments label_length, logit_length I am unaware of.</p> <p>Can someone please give some details about what those parameters are?</p> <p>Thank you in advance.</p>
<p>Label_length is a tensor of length = <code>batch_size</code>, each of the values will denote the length of your labels.</p> <p>Logit_length is a tensor of length = <code>batch_size</code>, each of the values will denote the length of your inputs.</p>
tensorflow|neural-network|model|tensorflow2.0|loss-function
1
3,308
60,933,474
Trying to split csv column data into lists after reading in using pandas library
<p>I have a csv file containing 3 columns of data: column 1 = time vector, column 2 is untuned circuit response and column 3 is the tuned circuit response. I am reading in this csv data in python using pandas:</p> <pre><code>df = pd.read_csv(filename, delimiter = ",") </code></pre> <p>I am now trying to create 3 list...
<p>You can use pandas series tolist method:</p> <pre><code>time = df['time vector'].tolist() untuned = df['untuned circuit'].tolist() tuned = df['tuned circuit'].tolist() </code></pre>
python|pandas|csv
0
3,309
66,211,595
Why the legend moves when I save the fig?
<p>I would like to save a figure. I defined the legend as below:</p> <pre><code>handles, labels = ax.get_legend_handles_labels() fig.legend(handles, labels, ncol=1, fontsize='10', title='Nbr of \n countries:', bbox_to_anchor=(0.83, 0.4)) </code></pre> <p>You can see below what is displayed on my notebook:</p> <p><a hre...
<p>An option is too use &quot;bbox_inches='tight'&quot; when saving the figure:</p> <pre><code> fig.savefig(os.path.join(path_img, 'name_fig.pdf'), bbox_inches='tight') </code></pre> <p>Keep titles and legend at their right place!</p>
python|jupyter-notebook
0
3,310
69,189,685
np.array with xlsxwrite in specific excel cell
<p>i have a np.array which i want to save in a specific excel cell (for example in B14). The input in B14 should look like this: [[ 0, 540, 1920, 540]]. But i got this ERROR:</p> <blockquote> <p>TypeError: only size-1 arrays can be converted to Python scalars. Unsupported type &lt;class 'numpy.ndarray'&gt; in write()</...
<p>I'm not sure if you want to write the data in the list or a string representation of the array. I'll address the first option.</p> <p>To write a list with xlsxwriter you can use the worksheet <code>write_row()</code> or <code>write_column()</code> methods (depending on which direction you want to write the data).</p...
python|excel|xlsxwriter
1
3,311
59,364,450
Installing python-igraph with pip on Mac 10.14 fails with "library not found for -lstdc++"
<p>I am trying to install <code>python-igraph</code> using <code>pip3</code> on Mac OS X 10.14, but the installation fails with the following error message:</p> <pre><code>$ pip3 install python-igraph ...snip... gcc -bundle -undefined dynamic_lookup -L/Users/charles/.pyenv/versions/miniconda3-4.3.30/lib -arch x86_64...
<p>Run</p> <pre><code>export MACOSX_DEPLOYMENT_TARGET=10.9 </code></pre> <p>before running <code>pip install python-igraph</code>. Then you should see it install successfully:</p> <pre><code>$ pip install python-igraph Collecting python-igraph Using cached https://files.pythonhosted.org/packages/0f/a0/4e7134f80373...
python|python-3.x|igraph
0
3,312
63,267,305
how to ffill and and letter in pandas?
<p>New to the pandas.</p> <p>Struggling find a way to ffill and concat a string. I imported excel sheet then like to fill the blank (NaN) with proceeding value plus some distinguisher(like-1).</p> <p>-from-</p> <pre><code>1 a 2 nan 3 b 4 nan </code></pre> <p>-to-</p> <pre><code>1 a 2 a-1 3 b 4 b-1 </code></pre> ...
<p>After you do <code>ffill</code>, you can compute the order of each rows with <code>groupby().cumcount()</code>:</p> <pre><code>df['col'] = df['col'].ffill() orders = df.groupby('col').cumcount() # concatenate the order except for the first rows df['col'] = np.where(orders==0, df['col'], df['col'] + '-' + orders.ast...
pandas
0
3,313
31,346,593
How to list all directories that do not contain a file type?
<p>I'm trying to return a unique list (<code>set</code>) of all directories if they do not contain certain file types. If that file type is NOT found, add that directory name to a list for further auditing.</p> <p>The function below will find all valid folders and add it to a set for further comparison. I'd like to ex...
<p>Does this do what you want?</p> <pre><code>import os def main(): exts = {'.pdf', '.ppt', '.txt'} for directory in get_directories_without_exts('W:\\workorder', exts): print(directory) def get_directories_without_exts(root, exts): for root, dirs, files in os.walk(root): for file in file...
python|directory|subdirectory|os.walk
2
3,314
59,627,160
ModuleNotFoundError: py3k for PyInstaller + savReaderWriter
<p>I want to use PyInstaller with module savReaderWriter. My code is very simple:</p> <pre><code>import savReaderWriter print("hello world") input("Press enter, to finish...") </code></pre> <p>I was trying to use hidden import with appropriate module:</p> <pre><code>pyinstaller --clean --win-private-assemblies --up...
<p>I solved the issue by including the path of the savReaderWriter to the parameter. </p> <pre><code>pyinstaller -p "C:\PyProjects\test\venv\Lib\site-packages\savReaderWriter"; test.py </code></pre> <p>Also, the real pain is when you trying to delete the module, an Error will occur because it is finding a non "UTF-8"...
python|python-3.x|pyinstaller|spss
-1
3,315
60,216,039
Isolation Forest Length of values does not match length of index
<p>I was running isolation forest trying to apply it on a 10049972 rows x 19 columns database, but after 2 hours of running I got the following error. I really don't understand why did I get it, nor how do I resolve it?</p> <p>Code:</p> <pre><code> import numpy as np import pandas as pd import matplotlib.pyplot as ...
<p>I think the problem might be with</p> <p><code>df.values.reshape(-1,1)</code></p> <p>Look at this example</p> <pre><code>df = pd.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)], columns=['dogs', 'cats']) df dogs cats 0 0.2 0.3 1 0.0 0.6 2 0.6 0.0 3 0.2 0.1 df.values.reshape(-1,1) array([[...
python|pandas|csv|machine-learning|jupyter-notebook
1
3,316
42,699,564
Python Fabric on FreeBSD cannot execute Binary
<p>My simple Fab file cannot be run on my FreeBSD system:</p> <pre><code>from fabric.api import run, env env.shell = '/usr/local/bin/bash' #Fabric doesn't know where to get bash on BSD correctly def host_type(): run('uname') </code></pre> <p>First I get an error about the shell, which I can fix by specifying the...
<p>It seems like according to the man pages of bash(1):</p> <blockquote> <p>Bash is an <strong>sh</strong>-compatible command language interpreter that executes commands read from the start input or from a file.</p> </blockquote> <p>Meaning the only input we can give bash is a script or input via a stdin pipe. But ...
python|bash|unix|fabric|bsd
2
3,317
50,605,101
Using Python to update labels Tkinter
<p>I am in the process of making a Hangman type game. So far, I have written the CLI version which works well, i'm just porting it over to create a GUI.</p> <p>I have become stuck :-(. The program is not complete, and there's still more to do but I have two issues. The first is the label update.</p> <p>When a letter ...
<p>The reason you cant update your label is because you haven't stored it in any variable. The grid, pack and place functions of the Label object and of all other widgets returns None, therefore when you call:</p> <pre><code>letter = Label(play, text = dashes, font = ("Arial",20)).grid(row = 2, column = i+1,padx = 10,...
python|tkinter|label
1
3,318
35,197,059
Scrapy : inspect network resources in a web page
<p>I am just beginning to explore scrappy framework.</p> <p>I have been reading scrapy to be used to extract urls/images etc <strong>from the page content</strong> and crawl.</p> <p>My question is, is there a way to extract/print all the network resources loading in the webpage like how <a href="http://phantomjs.org/ne...
<p>Scrapy don't render the webpage.</p> <p>Scrapy just fetch the webpage's html code from the web server. </p> <p>So when Scrapy fetched a webpage, the spider just visited the server <strong>once</strong>, and would not request the resources, like images and javascript files.</p>
python|scrapy|scrapy-spider
0
3,319
61,541,571
DRF user creation with one-to-one relation
<p>I have made a model and serializers for User and additional ones for their profile (additional info).</p> <p>Model</p> <pre><code>class Profile(models.Model): users = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, ) nickname = models.CharField(max_length...
<p>You just need to override the create function of your serializer. Also, you dont really need two serializers for this purpose. Something like this will do the job for you, (change according to your fields):</p> <pre><code>class UserSerializer(serializers.Serializer): """ Serializer for user details """ ...
python|django|django-rest-framework
2
3,320
55,373,134
Web scraping: How can I extract links from html that correspond to keywords being matched with other tags without the keyword in the url?
<p>Im trying to extract job descriptions from a Webpage if it matches with certain Keywords and this works, however I also want to extract the link that corresponds to the description found in the HTML. The issue is that the link occurs before the described keywords and the URL does not include a keyword to search for....
<p>Looking through the web I have seen that the link is always two levels higher than the description. Then you cold use <code>find_parent()</code> function to obtain the <code>a</code> tag of the jobs found.</p> <p>You have in your code:</p> <pre><code>jobs = soup.find_all('p',text=re.compile(r'\b(?:%s)\b' % '|'.joi...
python|html|web-scraping|beautifulsoup
0
3,321
57,576,429
Training the model with experimental data
<p>I want to train my SVR (support vector regression) model using experimental data. The experimental data is as follows:-</p> <ol> <li><p>Each experiment results in a similar to sinusoidal wave output with X axis being time, sampling interval being 0.1 sec and total 200 sec so each experiment gives 2000 points.</p></...
<p><a href="https://stackoverflow.com/questions/20906474/import-multiple-csv-files-into-pandas-and-concatenate-into-one-dataframe">Import multiple csv files into pandas and concatenate into one DataFrame</a></p> <p>You could use this link to read multiple csv files at once in a folder and combine them into 1 csv file ...
python|machine-learning|regression|svm
0
3,322
42,264,817
Joining Keywords in a list NYT
<p>For each article that a keyword list is returned for. We want to join all the words using the key --> values into a list, as shown below. I would like to strip out the ‘u’ from the list, before I do the append. Then we want to compare how many common words in both list and return the result. </p> <p>Example lists r...
<p>You can use list comprehension to build lists from the given dict.</p> <pre><code>d = [{u'value': u'Dunford, Joseph F Jr', u'name': u'persons', u'rank': u'1'}, {u'value': u'Afghanistan', u'name': u'glocations', u'rank': u'1'}, {u'value': u'Afghan National Police', u'name': u'organizations', u'rank': u'1'}, {u'value...
python
0
3,323
45,364,619
Move back to running instance of browser
<p>I'm working on Robot Framework (Selenium2Library). In my Test case, I've to perform some functionality on browser instance ( Web application) and some functionality on a desktop application (Here I'm using UFT). I'm executing VBS script to execute UFT (Automation Tool). I'm doing this successfully and handling the f...
<p>inject javascript alert and handle it, then browser will be active on desktop.</p> <p>something like this </p> <pre><code>JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("alert('OK')") </code></pre> <p>and handle it.</p>
python|selenium|robotframework|selenium2library
1
3,324
41,649,968
How to vectorize and devectorize using sklearn's CountVectorizer?
<p>I want to vectorize some text to corresponding integers and then convert those text to its mapped integers and also create new sentence using new input integers <code>[2,9,39,46,56,12,89,9]</code>.</p> <p>I have seen some custom functions which can used for this purpose but I want to know whether sklearn itself has...
<p>For vectorizing sentence into integers you can use <code>transform</code> function. Output of this function is vector with counts for each term - feature vector.</p> <pre><code>vec = CountVectorizer() vec.fit(a) print vec.vocabulary_ new_sentence = "dolor nulla enim" mapped_a = vec.transform([new_sentence]) print ...
python|scikit-learn|sklearn-pandas
5
3,325
57,126,074
Using CLI to run Python script on inputs to generate outputs
<p>I am having trouble understanding how to use a CLI command to run a Python script on input file parameters to generate output files. From what I understand, <code>analysis.py</code> is the python script and <code>-s</code> and <code>-p</code> are the variable names that will contain the csv data from <code>Sales.csv...
<p>Use <code>argparse.ArgumentParser</code> class to create a parser like so:</p> <pre class="lang-py prettyprint-override"><code>import sys from argparse import ArgumentParser def parse_args(): parser = ArgumentParser() parser.add_argument('-s', '--sales') parser.add_argument('-p', '--products') par...
python|csv|command-line-interface
0
3,326
20,379,874
Integration of normal distribution using Simpson's rule
<p>I'm trying to perform a simple integration using the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.simps.html" rel="nofollow">scipy.integrate.simps</a> function and I can't figure out the results it shows.</p> <p>Here's a MWE:</p> <pre><code>import numpy as np from scipy.integrate im...
<p>Using your sample, just sort <code>a</code> first, since it should be an array of points to sample at, and it expects them to be in order to build the approximation. Simpson's rule uses</p> <p><img src="https://i.stack.imgur.com/gfsrW.png" alt="simpsons rule"></p> <p>So it will be taking values for <code>x</code>...
python|numpy|integration
5
3,327
54,798,873
regex how to remove only a word including some particular letters
<p>I'm looking for regex to get the result below. The original sentence is:</p> <pre><code>txt="そう言え" txt="そう言う" </code></pre> <p>and expected result is:</p> <pre><code>output="そう" output="そう" </code></pre> <p>What I want to do here is to remove a word consists of two letters which includes character "言".</p> <p>I...
<p>You can use a pattern that matches <code>言</code> followed by another word (denoted by <code>\w</code>), so that <code>re.sub</code> can replace the match with an empty string:</p> <pre><code>re.sub(r"言\w", "", txt) </code></pre>
python|regex
1
3,328
54,841,911
python gnupg verify file
<p>I am not sure why this is not working (Python 2.7.5) - the files created in the temp directory I <em>can</em> validate, but python will not. Help?</p> <p>I'm not sure if I am using the gpg.verify_file function wrong, or if I am not understanding the right way to tell python I trust the key that is being imported, o...
<p>Finally figured it out. Writing the signature to file is not enough, you have to close and then reopen it in read only mode. Why I do not know, but that works.</p>
python|gnupg
1
3,329
33,357,007
Tornado On RPi not working
<p>Hello im trying to use tornado websockets on my Raspberry PI and i get this error</p> <pre><code> File "socket.py", line 1, in &lt;module&gt; import tornado.httpserver File "/usr/local/lib/python2.7/dist-packages/tornado/httpserver.py", line 31, in &lt;module&gt; import socket File "/root/socket.py", li...
<p>Don't call your file <code>socket.py</code>. It's confilicting with the python library module of the same name. </p> <p>Make sure you delete <code>socket.pyc</code> too if there is one.</p>
python|python-2.7|tornado
2
3,330
33,248,504
Capturing beautifulsoup HTMLParseError exception
<p>I am getting the exception from Beutifulsoup <code>HTMLParseError: expected name token at u'&lt;![0Y', at line 1371, column 24</code> - arising because the html I am reading in is malformed.</p> <p>How do I capture this error - I have tried</p> <pre><code> try: ... except HTMLParseError: pass </code><...
<p>BeautifulSoup is raising HTMLParseError from the HTMLParser library. Try importing the error from that library before using it in your try/except:</p> <pre><code>from HTMLParser import HTMLParseError try: # error happens except HTMLParseError: pass </code></pre> <p>More info on the HTMLParse library is <a...
python|python-2.7|beautifulsoup
2
3,331
40,983,719
How to convert 500Hz csv data file to wav audio file?
<p>I have a csv file of data, recorded on a data acquisition center with frequency of 500Hz, and I am trying to convert it to wav format. I have trie to Python and simply feed the numbers (as 16bit integers to the <code>wave</code> package), and it didn't work. How should I construct a wav file from simply a stream of ...
<p>The problem is with your sampling rate. Try re-sampling the data to something like 44100 Hz (see code below). I do not know what effects re-sampling will have on your data.</p> <pre><code>import numpy as np from scipy.io import wavfile from scipy.signal import resample data = np.random.uniform(-1, 1, 500) data_res...
python|csv|audio|wav
2
3,332
52,306,279
pytorch gradient / derivative / difference along axis like numpy.diff
<p>I have been struggling with this for quite some time. All I want is a torch.diff() function. However, many matrix operations do not appear to be easily compatible with tensor operations. </p> <p>I have tried an enormous amount of various pytorch operation combinations, yet none of them work.</p> <p>Due to the fac...
<p>A 1D convolution with a fixed filter should do the trick:</p> <pre><code>filter = torch.nn.Conv1d(in_channels=1, out_channels=1, kernel_size=2, stride=1, padding=1, groups=1, bias=False) kernel = np.array([-1.0, 1.0]) kernel = torch.from_numpy(kernel).view(1,1,2) filter.weight.data = kernel filter.weight.requires_g...
python|numpy|pytorch
4
3,333
43,603,710
renaming filenames to integer sequence in python3
<p>I need to rename filenames in a folder containing many text files. The renaming should follow the sequence of numbers for every file. It should be like as follows:</p> <pre><code>***given files*** ***renamed files*** abc.txt 1.txt def.txt 2.txt rsd.txt 3.txt ijb.txt ...
<p>Great, so what have you tried?</p> <p>As a starting point, have a look at the <a href="https://docs.python.org/3/library/os.html#module-os" rel="nofollow noreferrer"><code>os</code></a>-module, especially <a href="https://docs.python.org/3/library/os.html#os.walk" rel="nofollow noreferrer"><code>os.walk()</code></a...
python|python-3.x|file-rename
1
3,334
52,579,531
How to install CVXPY / SCS to use with GPU?
<p>All the dependencies are installed in a docker container, but when I run the example with GPU=True it returns "Status: Unbounded" and with GPU=False it works ok. The scs-python GPU tests return "Status: Unbounded". Also, nvidia-smi displays GPU usage. What might be the issue? </p> <p>Dockerfile: <a href="https://gi...
<p>I had the same problem and I was able to fix it building SCS-PYTHON like:</p> <pre><code>python3 setup.py install --scs --gpu --int </code></pre> <p>If you look at the setup.py help it says:</p> <blockquote> <p>GPU code always uses 32 bit ints</p> </blockquote> <pre><code>python3 setup.py install --help </code...
python|azure|docker|nvidia|cvxpy
2
3,335
47,678,973
Python weird behaviour List of inherited classes
<p>I am building a speech recognition system and for that I build an interface for the commands. They are made up by subjects, verbs, adjectives and wildcards. I implemented it this way:</p> <pre><code>class IWord(object): strings = [] def recognize(self, word): return word in self.strings def ad...
<p><code>self.words</code> is the <code>words</code> attribute of the <code>ICommand</code> class (it is not copied when you inherit). So when you append to that, it will append to it on <code>ICommand</code>, which will affect every class inheriting from it.</p> <p>Probably, though, a better thing to do would be some...
python|inheritance
5
3,336
37,394,673
Find first instance of non zero number in list after an index value
<p>I am new to Python and having a quick snag. I wish to find the first non-zero index in an array AFTER an indexed value. Essentially, the array looks something like this </p> <pre><code>myarray=[x,y,z,0,0,...,0,a,b,c,...] </code></pre> <p>Can I change around the filter or next commands to accomplish this? I've seen...
<p>You can try this one !</p> <pre><code>myarray=[45,45,1,0,0,0,8,6,7] def firstNon0(_list,startindex): for index in range(startindex,len(_list)): if _list[index]!=0:return index return None print myarray[firstNon0(myarray,3)] &gt;&gt;8 </code></pre>
python
1
3,337
47,254,915
pymysql - python 3.6 on AWS Lambda - handling inserting data into SQL statements
<p>I have been spending hours trying to and searching for how to insert strings and decimals into a sql insert statement. I cannot seem to find an answer that works. I am using AWS Lambda with Python 3.6 to process data. I continue to have issues getting the values of variables to inserted into my SQL statement. I am g...
<p>Try this: </p> <pre><code>timeStamp = 123456789.123456 thing = "Testing/IoT" statement = "INSERT INTO `cycles` (`timeStamp`, `thing`) VALUES ({}, {})" theData = (str(timeStamp), thing) logger.info(statement, theData) cursor = conn.cursor() cursor.execute(statement, theData) conn.commit() </code></pre>
string|amazon-web-services|aws-lambda|python-3.6
2
3,338
47,361,889
Nodejs Tensorflow Serving Client Error 3
<p>I'm serving a pre-trained inception model, and I've followed the official tutorials to serve it up until now. I'm currently getting an Error Code 3, as follows:</p> <pre><code>{ Error: contents must be scalar, got shape [305] [[Node: map/while/DecodeJpeg = DecodeJpeg[_output_shapes=[[?,?,3]], acceptable_fraction=...
<p>Okay, so I finally managed to crack this. Posting it as an answer here in case someone faces this exact same problem.</p> <p>So the inception model expects a base64 encoded image:</p> <pre><code>fs.readFile('./test/Xiang_Xiang_panda.jpg', (err, data) =&gt; { if(err) { return res.json({message: "Not fou...
node.js|tensorflow|tensorflow-serving
0
3,339
46,878,824
How to send a Unicode character with Autokey keyboard.sendkeys()?
<p>I am trying to use Autokey-py3 v0.93.10 (in Linux Mint 18.2), to generate Unicode characters using the <code>keyboard.send_keys</code> command. Unfortunately none of the following attempts work.</p> <pre><code>keyboard.sendkeys(&quot;—&quot;) keyboard.sendkeys(u&quot;\u2014&quot;) </code></pre> <p>or this attempt co...
<p>This works for me (mostly):</p> <pre><code>keyboard.send_keys("&lt;ctrl&gt;+&lt;shift&gt;+u+" + "012b") keyboard.send_keys("&lt;ctrl&gt;") </code></pre> <p>It seems to depend on the app you are writing to, the desktop environment, the distro and the version thereof...</p> <p>For example, it is working now in this...
python|unicode|keyboard|autokey
5
3,340
30,198,805
TKinter: How can I set the window icon of a child window (Toplevel)
<p>I'm trying to add a window icon to the child windows of a main window, built in TKinter. For portability (aka no missing files) I've got the main window icon set from a base64 encoded gif as a variable. I've been unable to replicate this for the child windows.</p> <pre><code>from Tkinter import * ICON = """ R0lGOD...
<p>Replace:</p> <pre><code>self.call('wm', 'iconphoto', self.parent._w, self.icon) </code></pre> <p>with:</p> <pre><code>self.tk.call('wm', 'iconphoto', self._w, self.icon) </code></pre>
python|tkinter
4
3,341
27,580,732
Django: object has no attibute 'id'
<p>When saving the object it show error like:</p> <pre><code>'feed' object has no attribute 'id' </code></pre> <p>And here is my code:</p> <p>form.py</p> <pre><code>from django import forms from .models import feed class feed_form(forms.ModelForm): class Meta: model = feed fields = ('feed_text'...
<p>You need to call the <code>__init__()</code> on the super class to let django initialize your model correctly:</p> <pre><code>class feed(models.Model): ... def __init__(self, *args, **kwargs): super(feed, self).__init__(*args, **kwargs) date = timezone.now() </code></pre>
python|mysql|django|django-models
2
3,342
48,626,810
How can I do join in django?
<p>I'm working with django, expecially with QuerySet right now and I have a very big problem. so, this is my code:</p> <pre><code>resources_rights = Resources_rights.objects.filter( group_id__in = groups ) resources = Resources.objects.filter( id__in = resources_rights__resource_id </code></pre> <p>)</p> <p><strong...
<p>Try to join instead doing <code>in</code>:</p> <pre><code>resources = Resources.objects.filter(resources_rights__group_id__in=groups) </code></pre>
django|python-2.7|django-queryset
2
3,343
19,894,222
How to remove multiple elements from a list>
<p>Question : </p> <p>Days is a list with 30 elements. Write a short snippet of code that will remove the 5th, 12th, and 23rd elements from days. </p> <p>The only way i can think of answering this question is by using splicing. Will this work x = x[0:5] + x[6:12] + x[13:23] +x[24:31]??? Or is there a better way?</p>
<p>To remove list elements by their indexes:</p> <pre><code>x = [e for i, e in enumerate(x) if i not in [5, 12, 23]] </code></pre>
python-3.x
1
3,344
48,325,859
Subclass pandas DataFrame with required argument
<p>I'm working on a new data structure that subclasses pandas DataFrame. I want to enforce my new data structure to have new_property, so that it can be processed safely later on. However, I'm running into error when using my new data structure, because the constructor gets called by some internal pandas function with...
<p>This question has been answered by a brilliant pandas developer. See <a href="https://github.com/pandas-dev/pandas/issues/19300" rel="noreferrer">this issue</a> for more details. Pasting the answer here. </p> <pre><code>class MyDataFrame(pd.DataFrame): @property def _constructor(self): return MyData...
pandas|dataframe|subclass
5
3,345
48,114,970
Send packets from one computer to another not on the same network
<p>I wanted to know how to send packets from another computer on some network to another computer at different network. I know the local IP of the computer and the public IP of the first network and I also know the local IP of the second computer and the public IP of the other computer's network. How can I send packets...
<p>by opening a socket, using the public IP of the other computer and the port on which a server is listening: <a href="http://stackoverflow.com/questions/68774/ddg#68796">http://stackoverflow.com/questions/68774/ddg#68796</a></p>
python|python-2.7|sockets|scapy
0
3,346
24,036,136
Create dictionary with different fields from different dictionaries
<p>I have such list:</p> <pre><code>two_dimension_sizelist = \ [{u'sizeOptionId': u'1542', u'sizeOptionName': u'1', u'sortOrderNumber': u'915'}, {u'sizeOptionId': u'1543', u'sizeOptionName': u'2', u'sortOrderNumber': u'975'}, ... {u'sizeOptionId': u'1602', u'sizeOptionName': u'Long', u'sortOrderNumber'...
<p>It seems to me that you will scan through the two_dimension_sizelist a lot of times and search for matching "sizeOptionId" from your product dictionaries.</p> <p>I would suggest doing this:</p> <pre><code>all_size_list = dict((str(x['sizeOptionId']), str(x['sizeOptionName'])) for x in two_dimension_sizelist) for ...
python|json|dictionary
0
3,347
71,862,754
incrementing image number python
<p>I am trying to rename those images so image_0596(2) changed to iamge_0596 After that I want to increment the file number so previous image_0596 =&gt; image_0597 and previous image_0598 =&gt; image_0599 ...... However, the block of my code doesn't replace anything.</p> <pre><code>from itertools import count import os...
<p>Well, <code>itertools.count</code> is totally the wrong tool here. And, of course, you are not calling <code>os.rename</code> at all.</p> <p>This is not a trivial problem. You cannot rename <code>image_0597</code> until <code>image_0598</code> is out of the way. You'll need to do them in reverse order. I think t...
python
2
3,348
71,956,506
how to generate uniform random complex numbers in python
<p>For my research, I need to generate uniform random complex numbers. How to do this in python because there is no such module to generate the complex numbers.</p>
<p>Your question is underspecified, you need to say from what region of the complex plane you want to draw your uniformly distributed numbers. For uniformly sampling real numbers, this is true as well. However, in the real case there is a very obvious choice, namely the interval [0, 1). You can see, for example that <c...
python|numpy|random|complex-numbers
2
3,349
36,224,090
NameError: global name 'program_stop_minutes' is not defined
<p>I need some help with my code, I am using two different functions as the one is for select the data on a database and the other one is to use for move to the right via on keyboard control. I want to reduce the code to avoid adding the same line of codes in one function.</p> <p>However, when I try this:</p> <pre><c...
<p>As the error message explicitly states, <code>program_stop_minutes</code> is not a global variable. You define it within <code>select_db</code> and therefore it is <em>only</em> accessible within that function's scope. If you want to access it from other functions (such as <code>GoRight</code>), you will need to def...
python|python-2.7
0
3,350
15,141,890
Starting out in Python Development: Coin-Tossing Loops
<p>Afternoon all,</p> <p>I cross your paths as someone looking to teachimself programming. As such, I've started with Python. As a disclaimer, I have searched the question for some examples of Python coin-tosses but I've not really understood any of the code that previous askers have come up with.</p> <p><strong>My...
<p>You're incrementing <code>cointoss</code> twice per loop.</p> <pre><code>while True: cointoss +=1 # You already incremented here, therefore... if cointoss &gt; 100: break if coinresult == 1: heads +=1 cointoss +=1 # ...get rid of this... elif coinresult == 2: ta...
python|coin-flipping
4
3,351
15,206,491
python: test whether subprocess call throws an expected exception
<p>I'm trying to test calling an external command with no arguments will throw a CalledProcessError exception using python2.7's unittest module like this:</p> <pre><code>import unittest class MyTest(unittest.TestCase) def testCommand(self): cmd = 'MyCommand' gotLog = 'UndefinedGot' with se...
<p>I can only think that the <code>CalledProcessError</code> name has been trampled, maybe explicitly stating it would help</p> <pre><code>with self.assertRaises(subprocess.CalledProcessError) as context: </code></pre>
python|unit-testing|exception|subprocess
2
3,352
15,261,793
Python: efficient method to replace accents (é to e), remove [^a-zA-Z\d\s], and lower()
<p>Using Python 3.3. I want to do the following:</p> <ul> <li>replace special alphabetical characters such as e acute (é) and o circumflex (ô) with the base character (ô to o, for example)</li> <li>remove all characters except alphanumeric and spaces in between alphanumeric characters</li> <li>convert to lowercase</li...
<pre><code>&gt;&gt;&gt; import unicodedata &gt;&gt;&gt; s='éô' &gt;&gt;&gt; ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')) 'eo' </code></pre> <p>Also check out <a href="https://pypi.python.org/pypi/Unidecode" rel="noreferrer">unidecode</a></p> <blockquote> <p>What Unidecode...
python|regex
34
3,353
46,285,510
Filter strings in a for loop by list of words for reddit bot
<p>So I'm trying to write a reddit bot to find articles with certain words in the title. Here's what I have so far: </p> <pre><code>top_posts = page.hot(limit=20) for post in top_posts: title = post.title if title.lower() in ['word1', 'word2', 'word3']: print(title) </code></pre> <p>If I replace the...
<p>You have the order of the operands wrongly placed and you're not doing it right.</p> <p>Use <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow noreferrer"><code>any</code></a> to check if <em>any</em> of words in the list is contained in the title:</p> <pre><code>if any(wd in title.lower(...
python|for-loop|praw
3
3,354
62,576,760
Python & Discord.py, if Server ID = 'ServerID' Leave
<p>So i have a Discord Bot that is written in Python &amp; Discord.py, now my question is, is it possible to do something like that:</p> <pre><code>Server_ID = 'TheServerID' if ServerID = Server_ID: leave </code></pre>
<p>The most efficient way is to only check this <em>if you're joining a guild right now</em>, this is done with the <code>discord.on_guild_join(guild)</code> <a href="https://discordpy.readthedocs.io/en/latest/api.html#discord.on_guild_join" rel="nofollow noreferrer">Reference</a>. Then it's just checking the id and le...
python|discord|discord.py
0
3,355
70,101,224
Merge 2 txt files with different length
<p>I have 2 datasets, both <code>.txt</code> files. Initialized as:</p> <pre><code>df_a = pd.read_csv(&quot;path_a.txt&quot;) # df_a.shape = (50000, 8) df_b = pd.read_csv(&quot;path_b.txt&quot;) # df_b.shape = (8000, 8) </code></pre> <p>Their <code>8</code> columns has same names. I want to merge both by <code>col_1</c...
<p>JOIN should be the way, but more specifically, an outer JOIN.</p> <p>To make it simpler, you may need to assign some distinct names, and suppose the shared key is <code>ts</code>:</p> <pre><code>df_a = pd.read_csv(&quot;a.txt&quot;, names=['ts', 'a', 'b', 'c', 'd', 'e', 'f', 'g']) # df_a.shape = (50000, 8) df_b = pd...
python|python-3.x|pandas
1
3,356
53,543,181
How to perform a fast cut zero edge in python?
<p>I have a binary image size of <code>256x256x256</code>, where the foreground region is located in a small region, and I have a lot of zero margins. I want to cut zero edges by finding the minimum and maximum coordinate of points that has pixel non-zero in images. It worked but it spends time-consuming. I post my cod...
<p>Your function can be improved significantly using numpy's built-in functions:</p> <pre><code>def cut_edge(image, keep_margin): ''' function that cuts zero edge ''' #Calculate sum along each axis D_sum = np.sum(image, axis=(1,2)) #0 H_sum = np.sum(image, axis=(0,2)) #1 W_sum = np.sum(ima...
arrays|python-3.x|numpy|image-processing
3
3,357
53,385,173
Creating a list of strings when input is not separated python
<p>I have this name list that i got online,the list is 200 names long,here is a sample of it that i have saved in a text file.</p> <pre><code>John Noah William James Logan Benjamin ... </code></pre> <p>I want them to be a <em>list of strings</em> i.e </p> <pre><code>x=['John','Noah','William',...] </code></pre> <p>...
<p>If the input is a file you can do...</p> <pre><code>x = [] with open('file_name', 'r') as f: for line in f: x.append(line.strip()) </code></pre>
python|python-3.x|list
2
3,358
33,314,082
Passing argument to pdf2txt function
<p>I'm trying to use PDFMiner to extract texts from PDF file. I wanted to use script pdf2txt.py to run the sample example in </p> <p><a href="http://www.unixuser.org/~euske/python/pdfminer/index.html" rel="nofollow">http://www.unixuser.org/~euske/python/pdfminer/index.html</a></p> <p>with this single line</p> <pre><...
<p>You should call it as:</p> <pre><code>pdf2txt.py samples/simple1.txt samples/simple1.pdf </code></pre> <p>If you want, let's say, samples/simple1.txt to be the output.</p>
python|python-2.7|command-line-arguments|python-idle|pdfminer
1
3,359
33,406,687
Python - Getting around Beautifulsoup's "object has no attribute" error in empty page
<p>To extract the texts that I need, I am able to scrape most webpages using Beautifulsoup's <strong>find_next_sibling</strong> in my conditional execution.</p> <pre><code>if len(str(h4.find_next_sibling)) &lt; 90: ... else: ... </code></pre> <p>For one particular page, however, the webpage is empty so Python...
<p>Huge thanks to the commenters, this issue is successfully solved using <strong>try: except</strong>: </p> <pre><code>try: if len(str(h4.find_next_sibling)) &lt; 90: coverage = h4.find_next_sibling(text=True) else: if len(str(h4.find_next_sibling)[1]) &lt; 90: coverage = h4.find_...
python|web-scraping|beautifulsoup
2
3,360
73,653,039
What are query modules in Memgraph?
<p>I keep coming across the term &quot;query module&quot; in blog posts related to Memgraph. What are query modules and when should I use one?</p>
<p>Memgraph supports extending the query language with user-written procedures in C, C++, Python, and Rust. These procedures are grouped into modules - query modules files (either <code>*.so</code> or <code>*.py</code> files).</p> <p>Some query modules are built-in, and others, like those that can help you solve comple...
python|c|graph-databases|memgraphdb
1
3,361
73,808,102
Cannot make Virtual Envoirment
<p>I have been following all the steps VSC's tutorial ia giving me but i keep running into this error</p> <pre><code>py : The term 'py' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and t...
<p>Take a look at this <a href="https://stackoverflow.com/a/68489809/13642249">post</a>. With windows, running <code>py</code> or <code>python</code> in a terminal (command prompt, PowerShell, git bash) should work in making a virtual environment. From your post, you are attempting to run this virtual environment in Po...
python|powershell|python-venv
-1
3,362
28,869,585
Read_Table with multiple comment characters
<p>I have data that is in 4 columns with a # separating comments at the end of the row. That's easy to read just the 4 columns and ignore the comment using the comment='#' in read_table.</p> <p>However, there is a line separating years of data. It is 8 '-' with nothing else on the line. I want skip the whole line t...
<p>Ii would just say to let them in and then to drop rows that have <code>--</code> in the first column. Something like this:</p> <pre><code>In [1]: import pandas as pd In [2]: df = pd.read_csv('in.txt',sep=',',header=0,names=['A','B','C','D']) In [3]: print df A B C D 0 q 88 4...
pandas
0
3,363
29,098,311
How to import re and formatting code
<p>I am trying to import re and have a format for a license plate in my original code, however I have the code but just do not know where to put it. I hope this is clear in my coding.</p> <pre><code>import re number_plate = re.match('\d{2}[A-Z]{2}\d{3}','12MNB36'): </code></pre> <p>The above code is what i am try...
<p>Here's how I might write what it looks like you're trying to do:</p> <pre><code>import re PLATE_PATTERN = r'\d{2}[A-Z]{2}\d{3}' with open("newfile.txt", "w") as f: over_limit = [] while True: distance = 10 print time = raw_input('Enter time: ') if time.lower() == 'x': ...
python|import
0
3,364
58,924,320
Django Listview Displays 0 results
<p>I have a weird situation (translation: I'm missing something obvious) where I have a ListView that renders fine when I iterate over each object in my queryset and yield, but returns 0 results when I just return the queryset. </p> <pre><code>class TestListView(ListView): model = Result context_object_name = ...
<p>Removing the for loop after the return solved my problem:</p> <pre><code>class TestListView(ListView): model = Result context_object_name = 'results' template_name = 'cases/test_list2.html' def get_queryset(self): # Get latest results results = Result.objects.filter(canonical=True, ...
python|django|listview|templates
0
3,365
52,096,764
How to add and remove single-index dataframe rows to and from a MultiIndex dataframe?
<p>I have a df, <code>Stock_to_buy</code>, that tells which stock to buy on a given date. Index column is <code>Date</code>.</p> <pre><code> Symbol Shares Date 2018-01-01 AAOI 20 2018-01-03 FB 34 2018-01-05 AMZN 5 2018-01-07 SQ 25 2018-01-08 TPL 31 </code></pre...
<p>I'm not sure that it is exactly what you want, but I think it can be helpful. <strong>Data:</strong></p> <pre><code>Stock_to_buy = pd.DataFrame(data=[ ['2018-01-01','AAOI','20'], ['2018-01-03', 'FB', 34], ['2018-01...
python|pandas|multi-index
0
3,366
51,735,082
Downloading a large file from colab fails
<p>I'm trying to download a directory which I've compressed as a .tar file, using the code below. The .tar file seems to have downloaded but is much smaller than it is shown on colab. Also I get the error message below. Can someone please let me know what the error message below means and is there a better way to do...
<p>This post seemed to solve my issue. Instead of downloading locally I saved it to my google drive using the code in the post:</p> <p><a href="https://stackoverflow.com/questions/49428332/how-to-download-large-files-like-weights-of-a-model-from-colaboratory">How to download large files (like weights of a model) from...
python-3.x|tar|google-colaboratory
0
3,367
51,818,271
Pycharm: Run Django from virtual env
<p>I have a Django project in Pycharm with a virtualenv named venv</p> <p>My Terminal path is:</p> <pre><code>(venv) C:\projects\Django\deya&gt; </code></pre> <p>I install my packages inside this virtualenv.</p> <p>The problem is that when I run project from Pycharm run icon, I am getting errors like:</p> <pre><co...
<p>This is complaining about not finding <code>django-tables2</code> module.</p> <p>Did you install <code>django-tables2</code> module in your virutalenv</p> <pre><code>pip install django-tables2 </code></pre> <p>The installation instruction for the module can be found <a href="http://django-tables2.readthedocs.io/e...
python|django|pycharm
2
3,368
51,967,409
input must be 4-dimensional[1,30,144,192,3], error in tensorflow training
<p>I'm trying to train a gif dataset but am getting this error. It says the error is probably because of the ResizeBilinear</p> <p>This is the code for the resize bilinear</p> <pre><code>input_height, input_width = hub.get_expected_image_size(module_spec) input_depth = hub.get_num_image_channels(module_spec) gif_dat...
<p>I am assuming that the list in your title corresponds to <code>[?,batch_size,height,width,channels]</code>. If so, and assuming that you do not need the first dimension (<code>[1]</code>), you can replace </p> <p><code>resized_image = tf.image.resize_bilinear(decoded_image_4d,resize_shape_as_int)</code> </p> <p>wi...
tensorflow|conv-neural-network|gif
0
3,369
51,585,164
Concatenating 3 df with the same index in pandas
<p>I am having issues concatenating 3 dataframes with the same index (in this case the index are dates). I am trying to plot three differnet dataframes onto one plotly graph and figured combining the dataframes would be the easiest. Currently I am using code such as below.</p> <pre><code>pd.concat([df1,df2,df3], axis ...
<p>You should ensure your indices are <strong>precisely</strong> the same. Here's a minimal example showing that you <em>can</em> concatenate with duplicate indices, provided they are identical:</p> <pre><code>idx = ['7/28/2018', '7/28/2018', '7/29/2018'] df_A = pd.DataFrame({'A': [1, 2, 3]}, index=idx) df_B = pd.Dat...
python|pandas|plotly
0
3,370
59,687,507
Pandas read_csv: Columns are being imported as rows
<p><strong>Edit</strong>: I believe this was all user error. I have been typing <code>df.T</code> by default, and it just occurred to me that this is very likely the TRANSPOSE output. By typing <code>df</code>, the data frame is output normally (headers as columns). Thank you for those who stepped up to try and help. I...
<p>A simple workaround here is to just to take the transpose of the dataframe. <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.transpose.html#pandas.DataFrame.transpose" rel="nofollow noreferrer">Link to Pandas Documentation</a></p> <pre><code>df = pd.DataFrame.transpose(df) </cod...
python|python-3.x|pandas|csv|import
1
3,371
19,111,921
Unwanted template code attached to response.out.write
<p>I'm stuck with trying to create a downloadable content. I'm using <code>webapp2.RequestHandler</code> and I've got the following scenario:</p> <ol> <li>I'm using Jinja 2 to create a page with a 'download this as csv' link.</li> <li>When you click the link, the file is downloaded correctly, starts with the correct c...
<p>Hard to say, but intuitively, deciding by the code you showed us, I would guess it's either...</p> <ul> <li>got to do with the <code>self.response.out.clear()</code> in the first <code>if</code> block—the second one doesn't have it;</li> <li>or with automatic template rendering by the webapp2 framework; but this do...
python|attachment|webapp2
0
3,372
18,954,889
How to process images of a video, frame by frame, in video streaming using OpenCV and Python
<p>I am a beginner in OpenCV. I want to do some image processing on the frames of a video which is being uploaded to my server. I just want to read the available frames and write them in a directory. Then, wait for the other part of the video to be uploaded and write the frames to the directory. And , I should wait for...
<p>After reading the documentation of <a href="http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture"><code>VideoCapture</code></a>. I figured out that you can tell <code>VideoCapture</code>, which frame to process next time we call <a href="http://docs.opencv.org/modules/hig...
python|opencv|video|video-streaming
59
3,373
69,231,042
Can a function work without defined parameters?
<p>I started learning python. I learned that a function cannot use values if they are not defined as parameters, but I was practicing and made a little program calling a function without parameters and it works. I don't understand why does it works, can someone please explain why does the program works?</p> <p>Here is ...
<p>When the names <code>x</code> and <code>y</code> aren't found in the local scope of <code>sum</code>, Python looks in the containing namespace, which is the global scope, where it finds them.</p> <p>Further reading: <a href="https://stackoverflow.com/q/291978/4518341">Short description of the scoping rules?</a></p> ...
python
1
3,374
68,875,577
why python says Expected ")" when i am creating variable in python?
<p>all of the code is on my github link is here: <a href="https://github.com/xPuszek/xPuszek/tree/main" rel="nofollow noreferrer">https://github.com/xPuszek/xPuszek/tree/main</a> and the error is here:</p> <pre><code> 'bezczynny' : engine.Animation([ pygame.image.load(&quot;ogurek/player_00.png&quot;), ...
<p>it looks like player animations should be a dictionary as such you should be defining it with curly braces not round ones</p> <pre class="lang-py prettyprint-override"><code>player_animations = { 'bezczynny': engine.Animation([ pygame.image.load(&quot;ogurek/player_00.png&quot;), pygame.image.loa...
python
3
3,375
67,456,569
Python Pandas: Concatenating dataframes misses columns
<p>I am reading multiple csv files from a folder and concatenates them inside a dataframe before loading them into SQL server database. But the problem that I am facing is that some of csv files have additional columns and have different order. The concatenation method simply ignores them and adds empty values in most ...
<p>given your described input and output you just need to use <code>pd.concat</code></p> <pre><code># input: df_A = pd.DataFrame({'A': ['1', '4'], 'B': ['3', '6']}) df_B = pd.DataFrame({'A': ['3', '9'], 'B': ['4', '5'], 'C': ['8', '1']}) df = pd.con...
python|dataframe|csv|concatenation
0
3,376
63,513,596
python get same day last year
<p>how to get same day last year in python</p> <p>I tried <code>datetime.datetime.now() - relativedelta(years=1)</code> but this doesn't produce the result I'm looking.</p> <p>Can anyone help. Thanks</p> <p>example:</p> <p>20/08/2020 (Thursday) last year will be 22/08/2019 (Thursday)</p>
<p>The answer from Pranav Hosangadi here is very nice, but please note that not every year has 52 weeks! It may be also 53, if you follow the <a href="http://en.wikipedia.org/wiki/ISO_week_date" rel="nofollow noreferrer">ISO8601 week numbering standard</a>.</p> <p>Number of ISO weeks in a year may be get <a href="https...
python|datetime
4
3,377
36,610,063
How to not store password in .pypirc?
<p>I'm trying to set up a private Pypi cloud using CloudPypi. And I really don't want store my password in .pypirc. I want to be prompt to type in my password every time I upload a package.</p> <p>In <a href="https://docs.python.org/2/distutils/packageindex.html#the-pypirc-file" rel="noreferrer">Python document about ...
<p>You omit the entire line completely:</p> <pre><code>[distutils] index-servers = pypi [pypi] repository: &lt;repository-url&gt; username: &lt;username&gt; </code></pre> <p>This has been tested on Python 3.6.2 and pip 9.0.1</p>
python|pypi
3
3,378
19,697,448
Python: Why is pygame.event.key.get_pressed() not working?
<p>I have been trying to make it where if i press space when the program has already been launched it will play my song. It opens up, then i get the loading animation on my cursor(when cursor is over the program.).The programs crashed.</p> <pre><code>`import pygame, sys from pygame.locals import * bf = 'bg.jpg' pygame...
<p>Your program is stuck here:</p> <pre><code>while True: if keys[pygame.K_SPACE]: pygame.mixer.music.load('ht.mp3') pygame.mixer.music.play(loops=-1, start=0) </code></pre> <p>The loop never ends. Once you obtain the condition you needed, you should break the loop:</p> <pre><code>while True: ...
python|pygame
1
3,379
22,342,533
How to read a text file into a 9x9 matrix?
<p>I'm having difficulty with this issue, so I'll describe my problem.</p> <p>I have a text file that contains 81 elements, but 1 column, i.e. it's a 81x1 matrix file.</p> <p>The actual elements are irrelevant.</p> <p>The file contains:</p> <pre><code>0 0 0 0 -1 . . . </code></pre> <p>How do I read it into a 9x9 m...
<p>Using <code>with</code> clause to open the file and <em>list comprehension</em> to reshape:</p> <pre><code>with open('a.x') as f: vals=list(map(int, f)) res=[vals[i: i+9] for i in range(0, 81, 9)] print res </code></pre> <p>If you're using <code>numpy</code>, <a href="http://docs.scipy.org/doc/numpy...
python
2
3,380
16,649,608
How to find bounding-layer for a threshold number in numpy stacked arrays?
<p>Lets assume I have 3 (or 100) ndarrays with dim=2 and shape=(x, y), that are stacked on top of each other. </p> <p>For each index in an array below another array, the values are smaller for the one below compared to the values of the one above, like so:</p> <pre><code>A = [ 0 0 1 1 0 0 0 1 0 0 0 0 0 0 0 0...
<p>It appears you want to use a combination of NumPy's <code>max</code>, <code>min</code>, and <code>where</code> functions.</p> <p>Using <code>numpy.where</code> allows us to find the index of matrix entries based of a criteria. In this case we can ask what the index is of the value which is the maximum/minimum of a ...
python|numpy|multidimensional-array
1
3,381
54,392,362
SQL insert query through python loop
<p>I'm trying to insert multiple rows into a table using a for-loop in python using the following code:</p> <pre><code>ID = 0 values = ['a', 'b', 'c'] for x in values: database.execute("INSERT INTO table (ID, value) VALUES (:ID, :value)", ID = ID, value = x) ID += 1 </code></pre> <p>What I'...
<p>The <a href="https://docs.python.org/3/library/sqlite3.html#cursor-objects" rel="nofollow noreferrer">execute method</a> takes an array as the second parameter.</p> <blockquote> <p><strong>execute</strong>(sql[, parameters])</p> <p>Executes an SQL statement. The SQL statement may be parameterized (i. e. plac...
python|sqlite|loops
0
3,382
55,365,482
Pandas: How to combine two dataframes by closest index match?
<p>I've got two dataframes <code>df1, df2</code> with indexes of the same type, but with few, if any, identical matches. Indexes may also have duplicaes. Columns A and B will consist of internally unique values. All indexes and columns are ordered, but not in the same direction. <code>df1.index</code> is descdending an...
<h3>Not "Pythonic" but a <code>O(n)</code> solution</h3> <pre><code>df2_index.sort() df1_index.sort() a = 0 b = 0 mapping = [[],[]] while b &lt; len(df2_index) and a &lt; len(df1_index): if df1_index[a] == df2_index[b]: mapping[0].append(df2_index[b]) mapping[1].append(df1.loc[df1_index[a], "A"]) ...
python|pandas
3
3,383
37,209,864
Interrupt all asyncio.sleep currently executing
<h3>where</h3> <p>This is on Linux, Python 3.5.1.</p> <h3>what</h3> <p>I'm developing a monitor process with <code>asyncio</code>, whose tasks at various places <code>await</code> on <code>asyncio.sleep</code> calls of various durations.</p> <p>There are points in time when I would like to be able to interrupt all ...
<p>Interrupting all running calls of <code>asyncio.sleep</code> seems a bit dangerous since it can be used in other parts of the code, for other purposes. Instead I would make a dedicated <code>sleep</code> coroutine that keeps track of its running calls. It is then possible to interrupt them all by canceling the corre...
python|linux|async-await|python-asyncio
8
3,384
39,447,513
Where is the Folder for shared library in a django project
<p>I am working on a python/django project which calls a C++ shared library. I am using boost_python C++ library. It works fine: I can call C++ methods from python interpreter. I can also call this methods from my django project. But i am wondering something: Where is the best folder for my C++ shared library ? I actua...
<p>put them to <code>$PROJECT_HOME/lib</code> just like a normal package</p>
django|boost-python
0
3,385
39,619,973
Python regex freezes with small input string
<p>I am using regular expressions on a bunch of wikipedia pages. Actually working really good for the first like 20 pages, but then it suddenly freezes without me seeing a reason. Interrupting the script delivers this:</p> <pre><code>File "imageListFiller.py", line 30, in getImage foundImage = re.search(urlRegex, str(...
<p>The <code>$-_</code> part in your pattern created a range matching uppercase letters and digits, and even more chars. Since other alternative branches in the group could match at the same location (like <code>[a-zA-Z]</code>) that led to a time out / catastrophic backtracking issue.</p> <p>You need to just concat a...
python|regex|freeze
1
3,386
16,137,108
Python Error importing Curses - not sure why
<p>So I do have curses installed Ive checked it with dpkg. Now when I try to import it, this happens</p> <pre><code>Python 2.7.3 (default, Jan 13 2013, 11:20:46) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import curses Traceback (most recent call last): ...
<pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "curses.py", line 3, in &lt;module&gt; </code></pre> <p>It seems you named your own file curses.py, Python looks in the current directory first so you cannot have the same name as a library.</p>
python|curses
9
3,387
32,091,892
xml Parsing using python
<p>Below is the XML that I am trying to parse, but it is giving me the error:</p> <pre><code>xml.etree.ElementTree.ParseError: unbound prefix: line 2, column 0 </code></pre> <p>This is the XML:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;ns1:NWEnv&gt; &lt;name&gt;lk&lt;/name&gt; &lt;gatew...
<p>Your xml has an error. The <code>ns1:</code> prefix is not bound to a namespace. There should be a namespace declaration in your xml using the xmlns attribute.</p> <blockquote> <p>When using prefixes in XML, a so-called namespace for the prefix must be defined. The namespace is defined by the xmlns attribut...
python|xml|python-2.7
1
3,388
38,947,650
Get the Key and Value of a dictionary while using random
<p>I'm new to python and I'm trying to make a simple "Game" I'm trying to get the health of the monsters but only the names come up. I can do <code>(random.choice(list(Monster.health.keys())))</code> and <code>(random.choice(list(Monster.health.Values())))</code> to store both the name and health in a variable but I'm...
<p>If you want to store both key an value at <code>self.random_mon_name_health</code> you can change your method to something like that and it will return a tuple with the monster name and its associated health.</p> <pre><code>def basic_monster(self): import random random_key = (random.choice(list(Monster.heal...
python|dictionary|random
0
3,389
40,477,081
Merging two Python APIs without breaking compatability
<h2>Here is the scenario:</h2> <p>Storage system <code>A</code> (Java) is the default and has a Python API <code>API_A</code>. Storage system <code>B</code> (Java/C++) was recently introduced, but did not have a Python API. People "somehow" made <code>B</code> work with <code>API_A</code>, but it is extremely slow, es...
<h2>Write a wrapper library for API B that &quot;looks like&quot; API A</h2> <p>In particular, it must provide exactly the same methods with exactly the same signatures. If API B does not implement some functionality (like recursive enumeration), the wrapper must re-implement this functionality in terms of API B. For...
python|api-design
0
3,390
40,716,448
Check if all elements of ListA exists in ListB using python
<p>I have two lists</p> <pre><code>ListA = [1,9,6,3,2,4] ListB = range(min(ListA),(max(ListA)+1)) i.e ListB = [1,2,3,4,5,6,7,8,9] </code></pre> <p>I want to check if all elements of ListA exists in ListB</p>
<p>Use <code>issubset</code> to achieve that (I prefer to rename your variables to make them more pythonic):</p> <pre><code>l1 = [1, 9, 6, 3, 2, 4] l2 = [1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre> <p><strong>Output:</strong></p> <pre><code>&gt;&gt;&gt; set(l1).issubset(set(l2)) True </code></pre> <p>You may also use ...
python|list
4
3,391
40,390,966
How can I alter this for-loop to alternate between 2 different characters as it inserts values, instead of only one value?
<p>I am trying to construct the game Konane (<a href="https://people.eecs.berkeley.edu/~ddgarcia/teaching/CS3Gamesman/games/konane.pdf" rel="nofollow noreferrer">this link</a> provides the game rules if you need to refer to them to better understand my question). I have created the function that will build the empty ar...
<p>This is how I would implement the array initialization in the way that you want, and then print it to verify. There are other ways to accomplish the alternation you are looking for; taking the the sum of the indices modulo 2 is the most logical to me.</p> <pre><code>area = empty_grid() # get an empty_gri...
python|multidimensional-array|grid|iteration
1
3,392
26,199,301
python json parsing error
<p>I wrote a simple program to parse json:</p> <pre><code>#! /usr/bin/env python import urllib2 import json so = 'https://api.stackexchange.com/2.2/users/507256?order=desc&amp;sort=reputation&amp;site=stackoverflow' j = urllib2.urlopen(so) print j.read() j_obj = json.loads(j.read()) </code></pre> <p>It fails with ...
<p>You cannot read the response twice. Remove the <code>print</code> line, or store the result of the <code>j.read()</code> call in a variable.</p> <p>Next, the Stack Exchange API returns <em>gzipped data</em>, so you'll have to unzip it first:</p> <pre><code>import zlib j = urllib2.urlopen(so) json_data = j.read() ...
python|json
3
3,393
26,126,528
Cherrypy _cp_dispatch strange behaviour with url without trailing slash: POST then GET
<p>I am testing CherryPy with _cp_dispatch. However, when I send 1 single post, _cp_dispatch is called twice, not once. First for the expected post then a second time with a get: Why?</p> <p>The code:</p> <pre><code>import os import cherrypy class WebServerApp: def __init__(self): self.index_count = 0 ...
<p>In cherrypy, an internal redirection occurs when the url does not end with a slash. <a href="https://cherrypy.readthedocs.org/en/3.3.0/refman/_cprequest.html#cherrypy._cprequest.Request.is_index" rel="nofollow">https://cherrypy.readthedocs.org/en/3.3.0/refman/_cprequest.html#cherrypy._cprequest.Request.is_index</a><...
rest|python-3.x|cherrypy
1
3,394
32,422,939
How to make specific parts of a text line indented properly?
<p>I use python print() function to print component name, its current version and latest version as follows:</p> <pre><code>for component in component_list: print("%s \t current ver: %s \t latest ver: %s" % (name, current_version, latest_version)) </code></pre> <p>The component name can differ in its length, which m...
<p>If <code>maxLength</code> is the maximum length of the name in your list, e.g.:</p> <pre><code># I don't know how you extract name from component so this might be incorrect maxLength = max(len(component.name) for component in component_list) </code></pre> <p>Then you can use the following to correctly format your ...
python|python-2.7
2
3,395
28,275,082
Setting session timeout in Odoo 8
<p>I need to set a session timeout in Odoo 8. This could be done in Odoo 7 by modifying the time in session_gc method in http.py. But I tried the same in Odoo 7 and it doesn't seem to be working. I would like to know if anyone has a solution to this. The following is the code that I modified in openerp 7 to get this do...
<p>the same function is available in odoo 8. The only difference is that the http.py file is located at the root of odoo directory and not in addons/web . One more thing. If you server doesnt have a heavy request, it could be better for you to increase the top limit of the random value : for example </p> <p>if random....
python|openerp|odoo
0
3,396
28,246,107
Type error Iter - Python3
<p>Can someone please explain why the following code is giving </p> <pre><code>TypeError: iter() returned non-iterator of type 'counter' in python 3 </code></pre> <p>This is working in python 2.7.3 without any error.</p> <pre><code>#!/usr/bin/python3 class counter(object): def __init__(self,size): sel...
<p>In python3.x you need to use <a href="https://docs.python.org/3/library/stdtypes.html#iterator.__next__" rel="noreferrer"><code>__next__()</code></a> instead of <code>next()</code> .</p> <p>from <a href="https://docs.python.org/3.0/whatsnew/3.0.html" rel="noreferrer">What’s New In Python 3.0</a>:</p> <blockquote>...
python|python-2.7|python-3.x
20
3,397
28,187,195
how to match two pattern into one in regex
<p>I am using python regex to do some regex match. </p> <pre><code>pattern1 = re.compile('&lt;a&gt;(.*?)&lt;/a&gt;[\s\S]*?&lt;b&gt;(.*?)&lt;/b&gt;') pattern2 = re.compile('&lt;b&gt;(.*?)&lt;/b&gt;[\s\S]*?&lt;a&gt;(.*?)&lt;/a&gt;') items = re.findall(pattern1, line) if items: print items[0] else: items = re.fi...
<p>Please don't use regular expressions to parse HTML. Regular expressions can't deal with HMTL<sup>(*)</sup>. There is more than one nice HTML parser for Python, use one of them.</p> <p>The following example uses <a href="https://pypi.python.org/pypi/pyquery" rel="nofollow">pyquery</a>, a jQuery API implementation on...
python|regex
3
3,398
28,323,764
Django custom user model with unique_together on the email
<p>I'm trying to create a custom User model in my Django app, the problem is I get an error saying email must be unique (fair enough!), however, I need <code>email</code> and <code>company</code> together to be unique, as I may have the same email but registered to a different company.</p> <p>I get the following error...
<p>You're missing the <code>unique=True</code> in your email field definition. The filed that is used in the <code>USERNAME_FIELD</code> should have this argument as explained in the <a href="https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#django.contrib.auth.models.CustomUser.USERNAME_FIELD" rel="norefe...
python|django
10
3,399
44,002,960
Python 2.7 - remove special characters from a string and camelCasing it
<p><strong>Input:</strong></p> <pre><code>to-camel-case to_camel_case </code></pre> <p><strong>Desired output:</strong></p> <pre><code>toCamelCase </code></pre> <p><strong>My code:</strong></p> <pre><code>def to_camel_case(text): lst =['_', '-'] if text is None: return '' else: for char...
<p>A better way to do this would be using a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer">list comprehension</a>. The problem with a for loop is that when you remove characters from text, the loop changes (since you're supposed to iterate over every item ...
string|python-2.7|camelcasing
1