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
1,906,700
60,199,906
use agg in python for pd.dataframe wiht customized function whose inputs are multiple dataframe columns
<p>I have a data frame like this.</p> <pre><code>mydf = pd.DataFrame({'a':[1,1,3,3],'b':[np.nan,2,3,6],'c':[1,3,3,9]}) a b c 0 1 NaN 1 1 1 2.0 3 2 3 3.0 3 3 3 6.0 9 </code></pre> <p>I would like to have a resulting dataframe like this.</p> <pre><code>myResults = pd.concat([mydf.groupby('a').apply(lambda x: (x.b/x.c).max()), mydf.groupby('a').apply(lambda x: (x.c/x.b).max())], axis =1) myResults.columns = ['b_c','c_b'] b_c c_b a 1 0.666667 1.5 3 1.000000 1.5 </code></pre> <p>Basically i would like to have max and min of ratio of <code>column b</code> and <code>column c</code> for each group (grouped by <code>column a</code>)</p> <p>If it possible to achieve this by <code>agg</code>? I tried <code>mydf.groupby('a').agg([lambda x: (x.b/x.c).max(), lambda x: (x.c/x.b).max()])</code>. It will not work, and seems column name <code>b</code> and <code>c</code> will not be recognized.</p> <p>Is there a better way to achieve this (prefer in one line) through agg or other function? In summary, I would like to apply customized function to grouped DataFrame, and the customized function needs to read multiple columns (may more than b and c columns mentioned above) from original DataFrame.</p>
<p>One way of doing it</p> <pre><code>def func(x): C= (x['b']/x['c']).max() D= (x['c']/x['b']).max() return pd.Series([C, D], index=['b_c','c_b']) mydf.groupby('a').apply(func).reset_index() </code></pre> <p><strong>Output</strong></p> <pre><code> a b_c c_b 0 1 0.666667 1.5 1 3 1.000000 1.5 </code></pre>
python|pandas
1
1,906,701
63,772,433
Determine if Django REST Framework serializer is used in context of many=True
<p>I have a Django REST Framework serializer that is used in several places. One of the fields is a SerializerMethodField that I only wanted to include if the serializer is used to serialize only a single object. Basically, I want to not include one of the SerializerMethodField (or change it's behavior) when I have that <code>MySerializer(objects, many=True)</code>. Any ideas how to do this?</p>
<p>Hi here is my solution to determine if we are in context of many=True: I override the <strong>new</strong> class method and add a &quot;has_many&quot; key to the context kwargs object:</p> <pre class="lang-py prettyprint-override"><code> class MySerializer(serializer.ModelSerializer): def __new__(cls, *args, **kwargs): if kwargs.get('many', False) is True: context = kwargs.get('context', {}) context.update({'has_many': True}) kwargs.update({'context': context}) return super().__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.context.get('has_many', False): # Do something </code></pre>
python|django|django-rest-framework
2
1,906,702
63,955,581
Building object models around external data
<p>I want to integrate external data into a Django app. Let's say, for example, I want to work with GitHub issues as if they were formulated as normal models within Django. So underneath these objects, I use the GitHub API to retrieve and store data.</p> <p>In particular, I also want to be able to reference the GitHub issues from models but not the other way around. I.e., I don't intend to modify or extend the external data directly.</p> <p>The views would use this abstraction to fetch data, but also to follow the references from &quot;normal objects&quot; to properties of the external data. Simple joins would also be nice to have, but clearly there would be limitations.</p> <p>Are there any examples of how to achieve this in an idiomatic way?</p> <p>Ideally, this would be would also be split in a general part that describes the API in general, and a descriptive part of the classes similar to how normal ORM classes are described.</p>
<p>If you want to use <strong>Django Model-like</strong> interface for your Github Issues, why don't use real <strong>Django models</strong>? You can, for example, create a method <code>fetch</code> in your model, that will load data from the remote api and save it to your model. That way you won't need to make external requests everywhere in your code, but only when you need it. A minimal example will look like these:</p> <pre><code>import requests from django.db import models from .exceptions import GithubAPIError class GithubRepo(models.Model): api_url = models.URLField() # e.g. https://api.github.com/repos/octocat/Hello-World class GithubIssue(models.Model): issue_id = models.IntegerField() repo = models.ForeignKey(GithubRepo, on_delete=models.CASCADE) node_id = models.CharField(max_length=100) title = models.CharField(max_length=255, null=True, blank=True) body = models.TextField(null=True, blank=True) &quot;&quot;&quot; Other fields &quot;&quot;&quot; class Meta: unique_together = [[&quot;issue_id&quot;, &quot;repo&quot;]] @property def url(self): return f&quot;{self.repo.api_url}/issues/{self.issue_id}&quot; def fetch_data(self): response = requests.get(self.url) if response.status != 200: raise GithubAPIError(&quot;Something went wrong&quot;) data = response.json() # populate fields from repsonse self.title = data['title'] self.body = data['body'] def save( self, force_insert=False, force_update=False, using=None, update_fields=None ): if self.pk is None: # fetch on first created self.fetch_data() super(GithubIssue, self).save( force_insert, force_update, using, update_fields ) </code></pre> <p>You can also write a custom <a href="https://docs.djangoproject.com/en/dev/topics/db/managers/" rel="nofollow noreferrer">Manager</a> for your model that will fetch data every time you call a <code>create</code> method - <code>GithubIssue.objects.create()</code></p>
python|django
4
1,906,703
42,696,635
Unable to import owlready in Python
<p>I am trying to use the owlready library in Python. I downloaded the file from link(<a href="https://pypi.python.org/pypi/Owlready" rel="nofollow noreferrer">https://pypi.python.org/pypi/Owlready</a>) but when I am importing owlready I am getting following error:</p> <pre><code>&gt;&gt;&gt; from owlready import * Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named 'owlready' </code></pre> <p>I tried running:</p> <pre><code>pip install owlready </code></pre> <p>I am get the error:</p> <pre><code>error: could not create '/usr/local/lib/python3.4/dist-packages/owlready': Permission denied </code></pre>
<p>Try installing it using <code>pip</code> instead.</p> <p>Run the command <code>pip install &lt;module name here&gt;</code> to do so. If you are using python3, run <code>pip3 install &lt;module name here&gt;</code>.</p> <p>If neither of these work you may also try:</p> <p><code>python -m pip install &lt;module name here&gt;</code></p> <p>or </p> <p><code>python3 -m pip install &lt;module name here&gt;</code></p> <p>If you don't yet have <code>pip</code>, you should probably get it. Very commonly used python package manager. <a href="https://stackoverflow.com/questions/4750806/how-do-i-install-pip-on-windows">Here</a> are some details on how to set the tool up.</p>
python|owl|owlready
2
1,906,704
50,675,219
Google Colab: "Unable to connect to the runtime" after uploading Pytorch model from local
<p>I am using a simple (not necessarily efficient) method for Pytorch model saving.</p> <pre class="lang-python prettyprint-override"><code>import torch from google.colab import files torch.save(model, filename) # save a trained model on the VM files.download(filename) # download the model to local best_model = files.upload() # select the model just downloaded best_model[filename] # access the model </code></pre> <p>Colab disconnects during execution of the last line, and hitting <code>RECONNECT</code> tab always shows <code>ALLOCATING</code> -> <code>CONNECTING</code> (fails, with "unable to connect to the runtime" message in the left bottom corner) -> <code>RECONNECT</code>. At the same time, executing any one of the cells gives Error message "Failed to execute cell, Could not send execute message to runtime: [object CloseEvent]"</p> <p>I know it is related to the last line, because I can successfully connect with my other google accounts which doesn't execute that.</p> <p>Why does it happen? It seems the google accounts which have executed the last line can no longer connect to the runtime.</p> <p><strong>Edit:</strong></p> <p>One night later, I can reconnect with the google account after session expiration. I just attempted the approach in the comment, and found that just <code>files.upload()</code> the Pytorch model would lead to the problem. Once the upload completes, Colab disconnects. </p>
<p>Try disabling your ad-blocker. Worked for me</p>
pytorch|google-colaboratory|data-persistence
9
1,906,705
35,287,085
Import data to database and retrieve
<p>I have a raspberrypi giving data for every 5 minutes running in python. I need to store the data to a data base using wamp server and plot it in a graph (time vs data). I have no idea how to connect to wamp server to store and retrieve data.</p>
<p>Taken from <a href="https://github.com/PyMySQL/PyMySQL" rel="nofollow">https://github.com/PyMySQL/PyMySQL</a></p> <pre><code>import pymysql.cursors # Connect to the database connection = pymysql.connect(host='localhost', user='user', password='passwd', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: # Create a new record sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, ('webmaster@python.org', 'very-secret')) # connection is not autocommit by default. So you must commit to save # your changes. connection.commit() with connection.cursor() as cursor: # Read a single record sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s" cursor.execute(sql, ('webmaster@python.org',)) result = cursor.fetchone() print(result) finally: connection.close() </code></pre>
python|database
0
1,906,706
35,055,496
Find timestamps of notes played in wav file
<p>Let's say we have a wav file with some guitar music recorded. The sound is very clean, no extra sounds only guitar itself and possibly metronome ticks.</p> <p>What would be the best approach to find a timestamp of each note (or a chord) played in Python? I don't need to identify the note itself, only the timestamp when it occurred.</p> <p>I never did this kind of stuff before so I'm a bit confused. I was reading on Wikipedia about Short-time Fourier transform and it looks kind of promising but I couldn't find any relevant examples. Would really appreciate any help/hints on how to start.</p>
<p>The general problem is called <a href="https://en.wikipedia.org/wiki/Onset_%28audio%29" rel="nofollow">onset detection</a> and there are many methods you can try out. I'll provide a super-naive solution, probably not working for your use case:</p> <pre><code>from scipy.io import wavfile from scipy.signal import argrelmax from matplotlib.mlab import specgram sr, x = wavfile.read(path) # read in a mono wav file spec, freqs, time = specgram(x, NFFT=4096, Fs=sr, mode='psd') # compute power spectral density spectogram spec2 = np.diff(spec, axis=1) # discrete difference in each frequency bin spec2[spec2&lt;0] = 0 # half-wave rectification diff = np.sum(spec2, axis=0) # sum positive difference in each time bin for peak in argrelmax(diff)[0]: # find peaks print("onset between %f and %f." % (time[peak], time[peak+1])) </code></pre>
python|audio|onset-detection
2
1,906,707
26,560,726
Python Binomial Coefficient
<p></p> <pre><code>import math x = int(input("Enter a value for x: ")) y = int(input("Enter a value for y: ")) if y == 1 or y == x: print(1) if y &gt; x: print(0) else: a = math.factorial(x) b = math.factorial(y) div = a // (b*(x-y)) print(div) </code></pre> <p>This binomial coefficient program works but when I input two of the same number which is supposed to equal to 1 or when y is greater than x it is supposed to equal to 0.</p>
<p>This question is old but as it comes up high on search results I will point out that <code>scipy</code> has two functions for computing the binomial coefficients:</p> <ol> <li><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.binom.html#scipy.special.binom" rel="noreferrer"><code>scipy.special.binom()</code></a></li> <li><p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.comb.html#scipy.special.comb" rel="noreferrer"><code>scipy.special.comb()</code></a></p> <pre><code>import scipy.special # the two give the same results scipy.special.binom(10, 5) # 252.0 scipy.special.comb(10, 5) # 252.0 scipy.special.binom(300, 150) # 9.375970277281882e+88 scipy.special.comb(300, 150) # 9.375970277281882e+88 # ...but with `exact == True` scipy.special.comb(10, 5, exact=True) # 252 scipy.special.comb(300, 150, exact=True) # 393759702772827452793193754439064084879232655700081358920472352712975170021839591675861424 </code></pre></li> </ol> <p>Note that <code>scipy.special.comb(exact=True)</code> uses Python integers, and therefore it can handle arbitrarily large results!</p> <p>Speed-wise, the three versions give somewhat different results:</p> <pre><code>num = 300 %timeit [[scipy.special.binom(n, k) for k in range(n + 1)] for n in range(num)] # 52.9 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit [[scipy.special.comb(n, k) for k in range(n + 1)] for n in range(num)] # 183 ms ± 814 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)each) %timeit [[scipy.special.comb(n, k, exact=True) for k in range(n + 1)] for n in range(num)] # 180 ms ± 649 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) </code></pre> <p>(and for <code>n = 300</code>, the binomial coefficients are too large to be represented correctly using <code>float64</code> numbers, as shown above).</p>
python|python-3.x
151
1,906,708
26,451,807
Python's 'site.py' gone after Yosemite upgrade. Is that okay?
<p>The Yosemite (OS X 10.10) upgrade includes Python 2.7.6, and the process, as usual with Apple system updates, seems to completely replace the system packages directory, in </p> <pre><code>/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python </code></pre> <p>This time, the process appears to have entirely omitted <a href="https://docs.python.org/2/library/site.html" rel="nofollow noreferrer"><code>site.py</code></a>. My understanding was that <a href="https://stackoverflow.com/a/11410874/656912">this file was essential to the functioning of Python</a>, in particular, the proper construction of package search paths; but my Python (which uses nothing more than the Apple system Python and additional packages in <code>site-packages</code>) works fine, and <a href="https://stackoverflow.com/q/21236384/656912">my paths</a> remain as they were before the upgrade.</p> <p>Is <code>site.py</code> no longer needed for proper functioning of Python? Has it been moved to another location?</p>
<p><code>site.py</code> is <em>still used</em>. You are just not looking in the right location:</p> <pre><code>&gt;&gt;&gt; import site &gt;&gt;&gt; print site.__file__ /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.pyc </code></pre> <p>The <code>/Extras</code> structure appears to consist entirely of <em>non-standard-library packages</em>, e.g. packages that Apple installs for their own uses that are not included with standard Python.</p> <p>If there <em>was</em> a <code>site.py</code> file there in previous OS X versions it was in all likelihood <a href="https://stackoverflow.com/a/26035458">one installed by <code>setuptools</code></a>; with 10.10 comes <code>setuptools</code> 1.1.6, which has long since got rid of the hack embodied in that file.</p>
python|import|pythonpath|osx-yosemite
2
1,906,709
61,197,372
How to fix Python 2.7 and Numpy syntax error in tmp directory
<p>I am installing my setup.py dependency file on a Ubuntu 16 instance. When I run the setup.py file below is the error I am getting.</p> <pre><code>File "/tmp/easy_install-z7cdA1/pandas-1.0.3/setup.py", line 42 f"numpy &gt;= {min_numpy_ver}" </code></pre> <p>The problem happening is that file is in a tmp directory which I am not able to debug. From the error I am guessing it is some numpy version issue with Python 2.7. Any help fixing this issue will be helpful.</p>
<p><code>pandas</code> <a href="https://pandas.pydata.org/pandas-docs/version/0.24/install.html#plan-for-dropping-python-2-7" rel="nofollow noreferrer">removed support for Python 2.7</a> starting from version 0.25.0. </p> <p>The most up-to-date version you can install for 2.7 is</p> <pre><code>pip install pandas==0.24.2 </code></pre> <hr> <p>You can see the error is because there's an f-string, which is a python 3.6 feature. <code>pd.__version__ == '1.0.3'</code> officially supports Python 3.6.1 and above, 3.7, and 3.8.</p>
pandas|python-2.7|numpy
1
1,906,710
61,604,175
Save data from TWS API to csv file
<p>I have a python script that reads data from the TWS API (Interactive Brokers) and want to dump the data in a csv file.</p> <p>Right now it just overwrites the data and prints the last line along with a bunch of other values I don't want. </p> <p>It prints out the values fine with print(df).</p> <p>Code:</p> <pre><code>from ibapi.client import EClient from ibapi.wrapper import EWrapper from ibapi.common import * from ibapi.contract import * from threading import Timer from ibapi.ticktype import * import pandas as pd import numpy as np class TestApp(EWrapper, EClient): def __init__(self): EWrapper.__init__(self) EClient.__init__(self, self) def error(self, reqId, errorCode, errorString): print("Error: ", reqId, " ", errorCode, " ", errorString) def nextValidId(self, orderId): self.start() def contractDetails(self, reqId, contractDetails): self.data = [contractDetails] df = pd.DataFrame(self.data) df.to_csv('options_test.csv') print(df) def contractDetailsEnd(self, reqId): print("\ncontractDetails End\n") def start(self): #self.reqSecDefOptParams(1, "AAPL", "", "STK", 265598) contract = Contract() contract.symbol = 'AAPL' contract.secType = 'OPT' contract.exchange = 'SMART' contract.currency = 'USD' #contract.primaryExchange = 'NASDAQ' contract.lastTradeDateOrContractMonth = '202010' #contract.strike = 175 #contract.right = "C" #contract.multiplier = "100" global underlying underlying = contract.symbol self.reqMktData(1, contract, '106', False, False, []) self.reqContractDetails(1, contract) def stop(self): self.done = True self.disconnect() def main(): app = TestApp() app.nextOrderId = 0 app.connect('127.0.0.1', 7497, 123) app.data = [] Timer(4, app.stop).start() app.run() if __name__ == "__main__": main() </code></pre> <p>I tried using append() and it spit out an error.</p> <pre><code> def contractDetails(self, reqId, contractDetails): self.data = [contractDetails] df = pd.append(self.data) df.to_csv('options_test.csv') print(df) ..raise AttributeError(f"module 'pandas' has no attribute '{name}'") AttributeError: module 'pandas' has no attribute 'append' </code></pre> <p>I just want to save the data received in "contractDetails" to a csv.</p>
<p>contractDetails is a ContractDetails details object and I'm not sure how pandas would make a dataframe. The most used field is the contract object which has the conId that you can use for requesting data or placing orders. It also has the symbol so you know what you're trading. The contractDetails has other info like trading times and exchanges. Check the source code for Contract. I modified the way a dataframe gets made a little bit for efficiency. I also modified the code a bit and removed the unneeded Timer.</p> <pre><code>from ibapi.client import EClient from ibapi.wrapper import EWrapper from ibapi.common import * from ibapi.contract import * from threading import Timer from ibapi.ticktype import * import collections import pandas as pd class TestApp(EWrapper, EClient): def __init__(self): EWrapper.__init__(self) EClient.__init__(self, self) self.data=collections.defaultdict(list) def error(self, reqId, errorCode, errorString): print("Error: ", reqId, " ", errorCode, " ", errorString) def nextValidId(self, orderId): self.nextOrderId=orderId self.start() def contractDetails(self, reqId, contractDetails): self.data["conid"].append(contractDetails.contract.conId) self.data["symbol"].append(contractDetails.contract.localSymbol) def contractDetailsEnd(self, reqId): print("\ncontractDetails End\n") self.df=pd.DataFrame.from_dict(app.data) self.stop() def start(self): #self.reqSecDefOptParams(1, "AAPL", "", "STK", 265598) contract = Contract() contract.symbol = 'AAPL' contract.secType = 'OPT' contract.exchange = 'SMART' contract.currency = 'USD' #contract.primaryExchange = 'NASDAQ' contract.lastTradeDateOrContractMonth = '202010' #contract.strike = 175 #contract.right = "C" #contract.multiplier = "100" self.reqContractDetails(1, contract) def stop(self): self.disconnect() print(self.df) #self.df.to_csv('options_test.csv') def main(): app = TestApp() app.connect('127.0.0.1', 7496, 123) app.run() </code></pre>
python|pandas|interactive-brokers|tws
1
1,906,711
60,378,598
Pythonic Nested for - loops in Python
<p>I am working on this code where I have nested for loops. <code>a_list</code> and <code>b_list</code> are list of tuples, where each tuple is made up of two tensors <code>[(tens1, tens2), ...]</code>. I am trying to compute the similarity of every <code>tens1</code> in <code>a_list</code> to every <code>tens1</code> in <code>b_list</code>. Below is the code I have. And the nested loop appears to be a bottleneck. Is there a better way(pythonic) that I can re-write the loops?</p> <pre><code>a2b= defaultdict(dict) b2a= defaultdict(dict) ab_sim = [] for a, vec_a in a_list: for b, vec_b in b_list: # Ignore combination if the first element in both a and b are same if a[0] == b[0]: continue # Calculate cosine similarity of combination sim = self.calculate_similarity(vec_a, vec_b ) a2b[a][b] = sim b2a[b][a] = sim ab_sim.append(sim) </code></pre> <p>The <code>calculate_similarity</code> is just a method computing cosine similarity. <code>a_list</code> and <code>b_list</code> could be of any size. I have <code>b2a</code> and <code>a2b</code> because I need them for other computations.</p>
<p>You could use a dictionary comprehension:</p> <pre><code>a2b = {a: {b: self.calculate_similarity(vec_a, vec_b ) for (b, vec_b) in b_list if a[0] != b[0]} for (a, vec_a) in a_list} </code></pre>
python|python-3.x|oop|for-loop|pytorch
2
1,906,712
56,364,843
How to generate all possible permutations of two numbers with value n in python?
<p>I want to get permutations for two numbers upto n repetitions in python code.</p> <p>Example:</p> <p><code>a = 10, b = 100 and given n = 3</code></p> <p>Now I want output like:</p> <pre><code>(10, 10, 10), (10, 10, 100), (10, 100, 10), (10, 100, 100), (100, 10, 10), (100, 10, 100), (100, 100, 10), (100, 100, 100) </code></pre> <p>I tried itertools permutations but wont helpful. Anyone please give me a solution.</p>
<p>You can use <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow noreferrer"><code>itertools.product</code></a> and set a <code>repeat</code> of 3:</p> <pre><code>from itertools import product a, b = 10, 100 n = 3 list(product([a,b], repeat=n)) [(10, 10, 10), (10, 10, 100), (10, 100, 10), (10, 100, 100), (100, 10, 10), (100, 10, 100), (100, 100, 10), (100, 100, 100)] </code></pre>
python|list|permutation
1
1,906,713
18,392,998
Mapping a few numerical columns into a new columns of tuples in Pandas
<p>For <code>object</code> data I can map two columns into a third, (<code>object</code>) column of tuples</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame([["A","b"], ["A", "a"],["B","b"]]) &gt;&gt;&gt; df 0 1 0 A b 1 A a 2 B b &gt;&gt;&gt; df.apply(lambda row: (row[0], row[1]), axis=1) 0 (A, b) 1 (A, a) 2 (B, b) dtype: object </code></pre> <p>(see also <a href="https://stackoverflow.com/questions/16353729/pandas-how-to-use-apply-function-to-multiple-columns">Pandas: How to use apply function to multiple columns</a>).</p> <p>However, when I try to do the same thing with numerical columns</p> <pre><code>&gt;&gt;&gt; df2 = pd.DataFrame([[10,2], [10, 1],[20,2]]) df2.apply(lambda row: (row[0], row[1]), axis=1) 0 1 0 10 2 1 10 1 2 20 2 </code></pre> <p>so instead of a series of pairs (i.e. <code>[(10,2), (10,1), (20,2)]</code>) I get a <code>DataFrame</code>.</p> <p>How can I force <code>pandas</code> to actually get a series of pairs? (Preferably, doing it nicer than converting to string and then parsing.)</p>
<p>I don't recommend this, but you <em>can</em> force it:</p> <pre><code>In [11]: df2.apply(lambda row: pd.Series([(row[0], row[1])]), axis=1) Out[11]: 0 0 (10, 2) 1 (10, 1) 2 (20, 2) </code></pre> <h2>Please don't do this.</h2> <p>Two columns will give you much better performance, flexibility and ease of later analysis.</p> <h3>Just to update with the OP's experience:</h3> <p>What was wanted was to count the occurrences of each [0, 1] pair.</p> <p>In Series they could use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a> method (with the column from the above result). However, the same result could be achieved using <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">groupby</a> and found to be 300 times faster (for OP):</p> <pre><code>df2.groupby([0, 1]).size() </code></pre> <p><em>It's worth emphasising (again) that <code>[11]</code> has to create a Series object and a tuple instance for each row, which is a <strong>huge</strong> overhead compared to that of groupby.</em></p>
python|pandas
4
1,906,714
69,393,947
Can you crop multiple areas from the same image with Wand?
<p>I have two images and would like to extract multiple areas from the first image and overlay them on the second image. Is there a way to crop multiple areas from an image without loading the first image in again with Python Wand? Something like the opposite of <code>+repage</code> in ImageMagick.</p> <pre><code>bg_img = Image(filename = 'second_image.jpg') fg_img = Image(filename = 'first_image.jpg') left = 50 top = 600 width = 30 height = 30 fg_img.crop(left, top, width=width, height=height) bg_img.composite(fg_img, left, top) fg_img = Image(filename = 'first_image.jpg') left = 500 top = 600 width = 100 height = 30 fg_img.crop(left, top, width=width, height=height) bg_img.composite(fg_img, left, top) bg_img.save(filename='second_image_plus_overlays.png') </code></pre>
<p>You can do that in Python Wand by cloning the input.</p> <p>Input:</p> <p><a href="https://i.stack.imgur.com/L2NJx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L2NJx.jpg" alt="enter image description here" /></a></p> <pre><code>from wand.image import Image from wand.display import display with Image(filename='lena.jpg') as img: with img.clone() as copy1: copy1.crop(left=50, top=100, width=100, height=50) copy1.save(filename='lena_crop1.jpg') display(copy1) with img.clone() as copy2: copy2.crop(left=100, top=50, width=50, height=100) copy2.save(filename='lena_crop2.jpg') display(copy2) </code></pre> <p>Result 1:</p> <p><a href="https://i.stack.imgur.com/1K5O2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1K5O2.jpg" alt="enter image description here" /></a></p> <p>Result 2:</p> <p><a href="https://i.stack.imgur.com/7it9X.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7it9X.jpg" alt="enter image description here" /></a></p>
python|wand
1
1,906,715
42,143,655
Storing Dynamically in an array python
<p>I am actually translating a matlab script into python an i have a problem using arrays in python (I am still a beginner) numpy. My question is this: In matlab I am computing the fourier transform of several signals and I am storing dynamically it in a 3 by 3 array say U. A simple example of what i want to do is as follows;</p> <pre><code>l = 3 ; c = 0 ; for i = 1:3 for j = 1:10 c=c+1 ; a = j + 1; U(i,c,:)=a ; end end </code></pre> <p>I want to translate this to python and I am unable to create the array U that stores dynamically the value of 'a' in U. Note : Here am computing 'a' as j+1 for simplicity but in my script 'a' is an array (the fourier transform of a signal)</p> <p>Sorry for my bad english, I am french. T</p>
<p>I believe you will ultimately want something like this. One of the things that was confusing was what your loop variable c and j were doing. It seems like you wanted c=j, so I changed that below. The one thing you need to watch out for is that python objects are indexed from 0, whereas Matlab objects are index from 1. So below, if you actually start examining the values of i and j, you will see that they start from 0. </p> <pre><code>import numpy L = 3; C = 10; N = 50; # Size of the Fourier array U = numpy.zeros((L,C,N)) for i in range(L): for j in range(C): # Create a matrix of scalars, for testing a = i*j*numpy.ones((N,)); U[i,j,:] = a; </code></pre>
arrays|matlab|python-2.7|numpy
0
1,906,716
54,122,387
Nested dict keys as variable
<p>There must be a more graceful way of doing this but I cannot figure out how to create a single function for reading/writing values to different levels of a dict, this is the 'best' that I could come up with:</p> <pre><code>table = { 'A': { 'B': '2', 'C': { 'D':'3' } } } first = 'A' second1 = 'B' second2 = 'C' third = 'D' def oneLevelDict(first): x = table[first] print(x) def twoLevelDict(first, second): x = table[first][second] print(x) def threeLevelDict(first, second, third): x = table[first][second][third] print(x) oneLevelDict(first) twoLevelDict(first, second1) threeLevelDict(first, second2, third) </code></pre>
<p>You can use *args to pass an arbitrary number of arguments to a function. You can then use a loop to traverse the levels.</p> <pre><code>get_any_level(*keys): d = table for key in keys: d = d[key] return d </code></pre> <p>Now you have one function that can replace the three you had before:</p> <pre><code>print(get_any_level(first)) print(get_any_level(first, second1)) print(get_any_level(first, second2, third)) </code></pre> <p>You can use this function to write to an arbitrary level as well:</p> <pre><code>get_any_level(first)[second1] = 17 </code></pre> <p>A better way might be to have a separate function to write though:</p> <pre><code>def put_any_level(value, *keys): get_any_level(*keys[:-1])[keys[-1]] = value put_any_level(17, first, second1) </code></pre> <p><code>value</code> has to come first in the argument list unless you want it to be keyword-only because <code>*keys</code> will consume all positional arguments. This is not necessarily a bad alternative:</p> <pre><code>def put_any_level(*keys, value): get_any_level(*keys[:-1])[keys[-1]] = value </code></pre> <p>The keyword argument adds clarity:</p> <pre><code>put_any_level(first, second1, value=17) </code></pre> <p>But it will also lead to an error if you attempt to pass it as a positional argument, e.g. <code>put_any_level(first, second1, 17)</code>.</p> <p>Couple of minor points:</p> <ol> <li>It's conventional to use CamelCase only for class names. Variables and functions are conventionally written in lowercase_with_underscores.</li> <li>A function should generally do one thing, and do it well. In this case, I've split the task of finding the nested value from the task of displaying it by giving the function a return value.</li> </ol>
python
2
1,906,717
58,421,078
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc9 in position 388: invalid continuation byte
<p>I am really beginning at python, but I am hours in this line, can't go anywhere without fixing it. </p> <pre><code>cadastro_2019_10= pd.read_csv("inf_cadastral_fi_20191015.csv",delimiter=";")[["CNPJ_FUNDO","DENOM_SOCIAL","CLASSE"]] </code></pre> <blockquote> <p>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc9 in position 49: invalid continuation byte</p> </blockquote> <pre><code>cadastro_2019_10= pd.read_csv("inf_cadastral_fi_20191015.csv",delimiter=";")[["CNPJ_FUNDO","DENOM_SOCIAL","CLASSE"]] </code></pre> <p>again: </p> <blockquote> <p>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc9 in position 388: invalid continuation byte</p> </blockquote>
<p>Figure out what encoding the CSV file uses. Seems it doesn't use UTF-8. Say it's latin1, then you can try with <code>read_csv(..., encoding="latin1")</code>.</p> <p>If you are on a UNIX system, you can use the <code>file</code> command to try to detect the encoding.</p>
python|pandas
1
1,906,718
58,194,840
Trouble appending values to an array in a for loop
<p>I'm trying to create an array that has values 0, 0.01, 0.02, 0.03... all the way up to 1.0.</p> <p>Here is my input:</p> <pre><code>x=0 h=0.01 n=100 xArray=[x] for i in (0,n): x += h xArray.append(x) print, xArray </code></pre> <p>Here is my output:</p> <p>[0, 0.01, 0.02]</p> <p>I'm very confused why it's only adding two elements to the array. How do I fix this?</p>
<p>There are some syntactical errors in your program. </p> <p>The code should be like this</p> <pre><code>x=0 h=0.01 n=100 xArray=[x] for i in range(0,n): x += h xArray.append(x) print(xArray) </code></pre> <p>As you can see the for loop and print function are erroneous in your code.</p>
python|arrays|for-loop
0
1,906,719
22,878,109
Error installing scipy library through pip on python 3: "compile failed with error code 1"
<p>I'm trying to install scipy library through pip on python 3.3.5. By the end of the script, i'm getting this error:</p> <blockquote> <p>Command /usr/local/opt/python3/bin/python3.3 -c "import setuptools, tokenize;<strong>file</strong>='/private/tmp/pip_build_root/scipy/setup.py';exec(compile(getattr(tokenize, 'open', open)(<strong>file</strong>).read().replace('\r\n', '\n'), <strong>file</strong>, 'exec'))" install --record /tmp/pip-9r7808-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/tmp/pip_build_root/scipy Storing debug log for failure in /Users/dan/.pip/pip.log</p> </blockquote>
<p>I was getting the same thing when using pip, I went to the install and it pointed to the following dependencies.</p> <p><code>sudo apt-get install python python-dev libatlas-base-dev gcc gfortran g++</code></p>
python|python-3.x|scipy|pip
18
1,906,720
41,415,629
ImportError: No module named 'tensorflow.python'
<p>here i wanna run this code for try neural network with python :</p> <pre><code>from __future__ import print_function from keras.datasets import mnist from keras.models import Sequential from keras.layers import Activation, Dense from keras.utils import np_utils import tensorflow as tf batch_size = 128 nb_classes = 10 nb_epoch = 12 #input image dimensions img_row, img_cols = 28, 28 #the data, Shuffled and split between train and test sets (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = X_train.reshape(X_train.shape[0], img_rows * img_cols) X_test = X_test.reshape(X_test.shape[0], img_row * img_cols) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_text /= 255 print('X_train shape:', X_train.shape) print(X_train_shape[0], 'train samples') print(X_test_shape[0], 'test samples') #convert class vectors to binary category Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) model = Sequential() model.add(Dense(output_dim = 800, input_dim=X_train.shape[1])) model.add(Activation('sigmoid')) model.add(Dense(nb_classes)) model.add(Actiovation('softmax')) model.compile(loss = 'categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) #crossentropy fungsi galat atau fungsi error dipakai kalo class biner #model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch = nb_poch, verbose=1, validation_data=(X_test, Y_test)) score = model.evaluate(X_test, Y_test, verbose = 0) print('Test Score : ', score[0]) print('Test Accuracy : ', score[1]) </code></pre> <p>at the beginning it must install keras, and success. but when try to run the code at the first the error is :</p> <blockquote> <p>ImportError : No Moduled Name "tensorflow"</p> </blockquote> <p>then i install using pip :</p> <blockquote> <p>pip install tensorflow</p> </blockquote> <p>after installation i try to run code again, got another message like this :</p> <blockquote> <p>ImportError : No Moduled Name "tensorflow.python"</p> </blockquote> <p><a href="https://i.stack.imgur.com/tYgfR.png" rel="noreferrer">Message Error</a> i dont have any idea with the error</p>
<p>Uninstall tensorflow:</p> <pre><code>pip uninstall tensorflow </code></pre> <p>Then reinstall it:</p> <pre><code>pip install tensorflow </code></pre>
python|tensorflow|keras|neural-network
40
1,906,721
6,813,818
wxPython + pysftp won't work at the same time
<p>My code:</p> <pre><code>class ConnectingPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE, pos=(-2, -2), size=(387, 267)) self.control.SetForegroundColour((34,139,34)) self.control.SetBackgroundColour((0,0,0)) self.control.Disable() self.control.AppendText("Connecting to device") self.device = Connection(#info goes here) self.control.AppendText("Connected to device") </code></pre> <p>So, as can be seen by my code, I'm trying to generate a panel with a "status" textbox, self.control. The idea is that I'm connecting to a remote device using pysftp, and that I want it to add a line to the status textbox each time an action takes place. The first one is just connecting to the host. However, my panel only displays <em>once the code has connected to the host</em>, even though the code for making the panel, etc is before.</p> <p>What can I do? No errors, just this weird behaviour. Thanks!</p>
<p>As already mentioned, it is because you are doing this in the constructor.</p> <p>Use <a href="http://www.wxpython.org/docs/api/wx-module.html#CallAfter" rel="nofollow">wx.CallAfter</a>:</p> <pre><code>class ConnectingPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE, pos=(-2, -2), size=(387, 267)) self.control.SetForegroundColour((34,139,34)) self.control.SetBackgroundColour((0,0,0)) self.control.Disable() wx.CallAfter(self.start_connection) def start_connection(self): self.control.AppendText("Connecting to device") self.device = Connection(#info goes here) self.control.AppendText("Connected to device") </code></pre>
python|ssh|connection|wxpython|pysftp
1
1,906,722
25,708,412
Django logging with multiple handlers for commands and views, with shared functions
<p>Is it possible to log commands and views to separate log files, while using a common function called from a command and a view ? Passing the logger as a function parameter would surely not be a good design.</p> <p><strong>settings.py</strong></p> <pre><code>'loggers': { 'Web': { 'handlers': ['logfile_website'], # -&gt; views.log 'Commands': { 'handlers': ['logfile_commands'], # -&gt; commands.log } </code></pre> <p><strong>views.py</strong> -> goes to <em>views.log</em></p> <pre><code>log = logging.getLogger('Web') def index(request): log.info('In view') my_common.common_function(1) </code></pre> <p><strong>command.py</strong> -> goes to <em>commands.log</em></p> <pre><code>log = logging.getLogger('Commands') class Command(BaseCommand): def handle(self, *args, **options): log.info('In command') my_common.common_function(2) </code></pre> <p><strong>my_common.py</strong> -> goes to where needed based on caller</p> <pre><code>def common_function(param): log = How to get logger based on current call stack? log.info('In common function') </code></pre>
<p>You could use a single handler which uses a filename based on the environment. For example, on POSIX,</p> <pre><code>LOG_FILENAME = os.environ.get('LOGFILE', 'views.log') # then use the filename in your configuration </code></pre> <p>and then run commands using</p> <pre><code>LOGFILE=commands.log python manage.py syncdb </code></pre> <p>where I am using <code>syncdb</code> as just an example of a command.</p>
python|django|logging
0
1,906,723
44,649,678
Warning when run tf contrib learn linear regression example
<p>The following code raised some warnings posted after the code. What is wrong with it and how to fix them.</p> <pre><code>import tensorflow as tf import numpy as np features = [tf.contrib.layers.real_valued_column('x', dimension=1)] estimator = tf.contrib.learn.LinearRegressor(feature_columns=features) x_train = np.array([1., 2., 3., 4.]) y_train = np.array([0., -1., -2., -3.]) x_eval = np.array([2., 5., 8., 1.]) y_eval = np.array([-1.01, -4.1, -7, 0.]) input_fn = tf.contrib.learn.io.numpy_input_fn( {'x':x_train}, y_train, batch_size=4, num_epochs=1000) eval_input_fn = tf.contrib.learn.io.numpy_input_fn( {'x':x_eval}, y_eval, batch_size=4, num_epochs=1000) estimator.fit(input_fn=input_fn, steps=1000) train_loss = estimator.evaluate(input_fn=input_fn) eval_loss = estimator.evaluate(input_fn=eval_input_fn) print('train loss: %r'% train_loss) print('eval loss: %r'% eval_loss) </code></pre> <p>=======================================================================</p> <p>WARNING:tensorflow:Using temporary folder as model directory: <code>C:\Users\user\AppData\Local\Temp\tmprlxunsfy</code></p> <p><code>WARNING:tensorflow: Rank of input Tensor (1) should be the same as output_rank (2) for a column. Will attempt to expand dims. It is highly recommended that you resize your input, as this behavior may change.</code></p> <p>WARNING:tensorflow:From <code>C:\python\Python352\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\head.py:615: scalar_summary (from tensorflow.python.ops.logging_ops) is deprecated and will be removed after 2016-11-30.</code></p> <p>Instructions for updating:</p> <p>Please switch to tf.summary.scalar. Note that tf.summary.scalar uses the node name instead of the tag. This means that TensorFlow will automatically de-duplicate summary names based on the scope they are created in. Also, passing a tensor or list of tags to a scalar summary op is no longer supported.</p> <p>WARNING:tensorflow: Rank of input Tensor (1) should be the same as output_rank (2) for a column. Will attempt to expand dims. It is highly recommended that you resize your input, as this behavior may change.</p> <p>WARNING:tensorflow:From <code>C:\python\Python352\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\head.py:615: scalar_summary (from tensorflow.python.ops.logging_ops) is deprecated and will be removed after 2016-11-30.</code></p> <p>Instructions for updating:</p> <p>Please switch to tf.summary.scalar. Note that tf.summary.scalar uses the node name instead of the tag. This means that TensorFlow will automatically de-duplicate summary names based on the scope they are created in. Also, passing a tensor or list of tags to a scalar summary op is no longer supported.</p> <p><code>WARNING:tensorflow: Skipping summary for global_step, must be a float or np.float32.</code></p> <p><code>WARNING:tensorflow: Rank of input Tensor (1) should be the same as output_rank (2) for a column. Will attempt to expand dims. It is highly recommended that you resize your input, as this behavior may change.</code></p> <p>WARNING:tensorflow:From <code>C:\python\Python352\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\head.py:615: scalar_summary (from tensorflow.python.ops.logging_ops) is deprecated and will be removed after 2016-11-30.</code></p> <p>Instructions for updating:</p> <p>Please switch to tf.summary.scalar. Note that tf.summary.scalar uses the node name instead of the tag. This means that TensorFlow will automatically de-duplicate summary names based on the scope they are created in. Also, passing a tensor or list of tags to a scalar summary op is no longer supported.</p> <p><code>WARNING:tensorflow: Skipping summary for global_step, must be a float or np.float32.</code></p> <blockquote> <p>train loss: {'loss': 6.2396435e-09, 'global_step': 1000}</p> <p>eval loss: {'loss': 0.0025317217, 'global_step': 1000}</p> </blockquote>
<p>For the first one, pass model_dir= explicitly to LinearRegressor <strong>init</strong>. That way you know where it is.</p> <p>Not sure what the input-output rank warning is. But all others are internal to the Estimator, and therefore you don't have to worry about and can't fix.</p>
python|tensorflow
0
1,906,724
44,380,199
Pairwise Earth Mover Distance across all documents (word2vec representations)
<p>Is there a library that will take a list of documents and en masse compute the nxn matrix of distances - where the word2vec model is supplied? I can see that genism allows you to do this between two documents - but I need a fast comparison across all docs. like sklearns cosine_similarity.</p>
<p>The "Word Mover's Distance" (earth-mover's distance applied to groups of word-vectors) is a fairly involved optimization calculation dependent on every word in each document. </p> <p>I'm not aware of any tricks that would help it go faster when calculating many at once – even many distances to the same document. </p> <p>So the only thing needed to calculate pairwise distances are nested loops to consider each (order-ignoring unique) pairing. </p> <p>For example, assuming your list of documents (each a list-of-words) is <code>docs</code>, a gensim word-vector model in <code>model</code>, and <code>numpy</code> imported as <code>np</code>, you could calculate the array of pairwise distances D with:</p> <pre><code>D = np.zeros((len(docs), len(docs))) for i in range(len(docs)): for j in range(len(docs)): if i == j: continue # self-distance is 0.0 if i &gt; j: D[i, j] = D[j, i] # re-use earlier calc D[i, j] = model.wmdistance(docs[i], docs[j]) </code></pre> <p>It may take a while, but you'll then have all pairwise distances in array D. </p>
python|scikit-learn|distance|word2vec
3
1,906,725
44,584,924
how i can send message to my contact whit telethon API python telegram
<p>when i use this command for see contact :</p> <pre><code>result = client.invoke(GetContactsRequest("")) print(result) </code></pre> <p>i see this result :</p> <pre><code>(contacts.contacts (ID: 0x6f8b8cb2) = (contacts=['(contact (ID: 0xf911c994) = (user_id=334412783, mutual=False))'], users=['(user (ID: 0x2e13f4c3) = (is_self=None, contact=True, mutual_contact=None, deleted=None, bot=None, bot_chat_history=None, bot_nochats=None, verified=None, restricted=None, min=None, bot_inline_geo=None, id=334412783, access_hash=-8113372651091717470, first_name=khood, last_name=None, username=Mosafer575, phone=19132594548, photo=(userProfilePhoto (ID: 0xd559d8c8) = (photo_id=1436291966805583785, photo_small=(fileLocation (ID: 0x53d69076) = (dc_id=1, volume_id=803110857, local_id=86736, secret=1232685751818265379)), photo_big=(fileLocation (ID: 0x53d69076) = (dc_id=1, volume_id=803110857, local_id=86738, secret=3801220285627155105)))), status=(userStatusOffline (ID: 0x8c703f) = (was_online=2017-06-16 13:09:57)), bot_info_version=None, restriction_reason=None, bot_inline_placeholder=None, lang_code=None))'])) </code></pre> <p>now how i can send one message fore this friend with first_name my friend or user_id or phone or other details in my contact??? i see this <a href="https://github.com/LonamiWebs/Telethon/blob/master/telethon_examples/interactive_telegram_client.py" rel="nofollow noreferrer">page</a> but I din't notice. please use simple code for this</p>
<p>If it's your contacts you can use the phone number like you would use an username:</p> <pre><code>client.send_message('+xx123456789', 'hello') </code></pre> <hr> <p>Old answer:</p> <blockquote> <pre><code>users=['(user (ID: 0x2e13f4c3) ...` </code></pre> </blockquote> <p>The <code>users</code> list has the user you want to talk to. So you get that user:</p> <pre><code>user = result.users[0] </code></pre> <p>And then you can call <code>.send_message(user, 'your message')</code>.</p>
python|api|telegram
1
1,906,726
61,802,149
Sorting values in a pandas series in ascending order not working when re-assigned
<p>I am trying to sort a Pandas Series in ascending order. </p> <pre><code>Top15['HighRenew'].sort_values(ascending=True) </code></pre> <p>Gives me:</p> <pre><code>Country China 1 Russian Federation 1 Canada 1 Germany 1 Italy 1 Spain 1 Brazil 1 South Korea 2.27935 Iran 5.70772 Japan 10.2328 United Kingdom 10.6005 United States 11.571 Australia 11.8108 India 14.9691 France 17.0203 Name: HighRenew, dtype: object </code></pre> <p>The values are in <strong>ascending order</strong>. </p> <p>However, when I then modify the series in the <strong>context of the dataframe</strong>:</p> <pre><code>Top15['HighRenew'] = Top15['HighRenew'].sort_values(ascending=True) Top15['HighRenew'] </code></pre> <p>Gives me:</p> <pre><code>Country China 1 United States 11.571 Japan 10.2328 United Kingdom 10.6005 Russian Federation 1 Canada 1 Germany 1 India 14.9691 France 17.0203 South Korea 2.27935 Italy 1 Spain 1 Iran 5.70772 Australia 11.8108 Brazil 1 Name: HighRenew, dtype: object </code></pre> <p>Why this is giving me a different output to that above?</p> <p>Would be grateful for any advice?</p>
<pre><code>Top15['HighRenew'] = Top15['HighRenew'].sort_values(ascending=True).to_numpy() </code></pre> <p>or </p> <pre><code>Top15['HighRenew'] = Top15['HighRenew'].sort_values(ascending=True).reset_index(drop=True) </code></pre> <p>When you sort_values , the <strong>indexes don't change</strong> so it is aligning per the index!</p> <p>Thank you to anky for providing me with this fantastic solution!</p>
python|pandas|dataframe|sorting|series
1
1,906,727
15,000,311
Force to start python script with python exe to parse parameters
<p>I am having trouble to start a python script and get the parameters I send to the script.</p> <p><img src="https://i.stack.imgur.com/z2Pnj.jpg" alt="enter image description here"></p> <p>As you can see if I start the following test script with python comand, it works, if not, well, no arguments are passed to the script :/</p> <pre><code>import optparse import sys oOptParse = optparse.OptionParser() oOptParse.add_option("--arg", dest="arg", help="Test param") oOptParse.set_default("arg", None) if len(sys.argv) == 1: oOptParse.print_help( ) sys.exit( 1 ) aOptions = oOptParse.parse_args( ) oOptions = aOptions[0] print (oOptions.arg) </code></pre> <p>Do you have any idea what could be the problem ?</p> <p>Thanks a lot !</p>
<p>Found my answer.</p> <p>It was a problem on registry settings the following key </p> <pre><code>HKEY_CLASSES_ROOT\py_auto_file\shell\open\command </code></pre> <p>was set to </p> <pre><code>"C:\Python26\python.exe" "%1" </code></pre> <p>but should be </p> <pre><code>"C:\Python26\python.exe" "%1" %* </code></pre>
python
0
1,906,728
14,933,771
Python regular expression re.match, why this code does not work?
<p>This is written in Python,</p> <pre><code>import re s='1 89059809102/30589533 IronMan 30 Santa Ana Massage table / IronMan 30 Santa Ana Massage table' pattern='\s(\d{11})/(\d{8})' re.match(pattern,s) </code></pre> <p>it returns none.</p> <p>I tried taking the brackets off,</p> <pre><code>pattern='\s\d{11}/\d{8}' </code></pre> <p>It still returns <code>none</code>. </p> <p>My questions are:</p> <ol> <li>Why the re.match does not find anything? </li> <li>What is the difference with or without bracket in pattern?</li> </ol>
<p><code>re.match</code> "matches" since the beginning of the string, but there is an extra <code>1</code>.</p> <p>Use <code>re.search</code> instead, which will "search" anywhere within the string. And, in your case, also find something:</p> <pre><code>&gt;&gt;&gt; re.search(pattern,s).groups() ('89059809102', '30589533') </code></pre> <p>If you remove the brackets in pattern, it will still return a valid <code>_sre.SRE_Match</code>, object, but with empty <code>groups</code>:</p> <pre><code>&gt;&gt;&gt; re.search('\s\d{11}/\d{8}',s).groups() () </code></pre>
python|regex
38
1,906,729
15,465,997
Python tools for out-of-core computation/data mining
<p>I am interested in <code>python mining</code> data sets too big to sit in RAM but sitting within a single HD. </p> <p>I understand that I can export the data as <code>hdf5</code> files, using <code>pytables</code>. Also the <code>numexpr</code> allows for some basic out-of-core computation.</p> <p>What would come next? Mini-batching when possible, and relying on linear algebra results to decompose the computation when mini-batching cannot be used?</p> <p>Or are there some higher level tools I have missed?</p> <p>Thanks for insights,</p>
<p>What exactly do you want to do &mdash; can you give an example or two please ?</p> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html" rel="nofollow noreferrer">numpy.memmap</a> is easy &mdash;</p> <blockquote> <p>Create a memory-map to an array stored in a <em>binary</em> file on disk.<br> Memory-mapped files are used for accessing small segments of large files on disk, without reading the entire file into memory. Numpy's memmap's are array-like objects ...</p> </blockquote> <p>see also <a href="https://stackoverflow.com/search?q=[numpy]+memmap">numpy+memmap</a> on SO. </p> <p>The <a href="http://scikit-learn.org" rel="nofollow noreferrer">scikit-learn</a> people are very knowledgeable, but prefer specific questions.</p>
python|numpy|data-mining|large-data|database
4
1,906,730
29,621,527
Can't connect to MongoDB after upgrading?
<p>I'm building a website using Flask in which I use MongoDB with the <a href="http://mongoengine.org/" rel="nofollow">MongoEngine</a> ORM. To go for a fresh start again I now upgraded all apt and pip packages on my ubuntu 14.04 development machine. Unfortunately this broke my connection to MongoDB:</p> <pre><code>Traceback (most recent call last): File "./run.py", line 4, in &lt;module&gt; from app import app, socketio File "/home/kr65/beta/app/__init__.py", line 21, in &lt;module&gt; mongoDb = MongoEngine(app) File "/usr/local/lib/python2.7/dist-packages/flask_mongoengine/__init__.py", line 33, in __init__ self.init_app(app) File "/usr/local/lib/python2.7/dist-packages/flask_mongoengine/__init__.py", line 66, in init_app self.connection = mongoengine.connect(**conn_settings) File "/usr/local/lib/python2.7/dist-packages/mongoengine/connection.py", line 164, in connect return get_connection(alias) File "/usr/local/lib/python2.7/dist-packages/mongoengine/connection.py", line 126, in get_connection raise ConnectionError("Cannot connect to database %s :\n%s" % (alias, e)) mongoengine.connection.ConnectionError: Cannot connect to database default : False is not a read preference. </code></pre> <p>I checked if MongoDB is up:</p> <pre><code>$ sudo service mongodb status mongodb start/running, process 781 </code></pre> <p>and if I could get into the interactive command line:</p> <pre><code>$ mongo MongoDB shell version: 2.4.9 connecting to: test Welcome to the MongoDB shell. For interactive help, type "help". For more comprehensive documentation, see http://docs.mongodb.org/ Questions? Try the support group http://groups.google.com/group/mongodb-user Server has startup warnings: Tue Apr 14 09:14:10.267 [initandlisten] Tue Apr 14 09:14:10.267 [initandlisten] ** WARNING: You are running in OpenVZ. This is known to be broken!!! Tue Apr 14 09:14:10.267 [initandlisten] &gt; </code></pre> <p>I didn't change anything to the code or passwords or anything like that. I did a reboot and restarted mongoDB, but nothing works. My settings are like this:</p> <pre><code>MONGODB_SETTINGS = { 'db': 'mydatabasename' } </code></pre> <p>and I instantiate the connection like this (which worked before):</p> <pre><code>app = Flask(__name__) app.config.from_object('config') mongoDb = MongoEngine(app) </code></pre> <p>Since I didn't really change anything, I'm kind of unsure where to search for a solution. Does anybody have any tips how I could solve this?</p> <p>[EDIT] With the tip of @lapinkoira my MongoDB now starts up correctly, but I now get the error below while querying. Any ideas how to solve this one?</p> <pre><code>File "/home/kr65/beta/app/views/webviews.py", line 476, in getDoc userDoc = UserDocument.objects(id=docId).first() File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/base.py", line 309, in first result = queryset[0] File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/base.py", line 160, in __getitem__ return queryset._document._from_son(queryset._cursor[key], File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/base.py", line 1410, in _cursor **self._cursor_args) File "/usr/local/lib/python2.7/dist-packages/pymongo/collection.py", line 924, in find return Cursor(self, *args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'snapshot' </code></pre>
<p>looks like you have pymongo 3.0 installed. </p> <p>Mongoengine is not yet compatible with it. </p> <p>You can try fix this by </p> <pre><code>pip uninstall pymongo pip install pymongo==2.8 </code></pre>
python|mongodb|flask|mongoengine|flask-mongoengine
6
1,906,731
29,521,801
Why Tkinter can be procedural and PyQt can only be used just with the OO paradigm?
<p>I have been programming in Python3 and use Tkinter to create GUIs. I have recently been introduced to PyQT and realise how much better the GUI toolkit is in terms of its style and range of widgets.</p> <p>I have used Tkinter mostly in a procedural way and it works fine in terms of GUI building. I realise that PyQT uses the OOP paradigm to create GUIs.</p> <p>Am I correct in thinking that the following correctly describes how tkinter and PyQT differ in the way in which they work...?</p> <ul> <li>With Tkinter, you produce a window object and then you create widget objects (buttons, labels etc) (all these widgets being separate objects) and each time you place them on your window like sticking different pictures on a piece of paper, <strong>which is why you can create tkinter GUIs in a procedural way</strong>.</li> <li>With PyQT however, you can produce a window object in the same way, but if you want widgets to appear on the window object you don't create them separately and 'stick them on' like with Tkinter. Instead, you have to create a new class (blueprint) for your window object, inherit the various widgets from the PyQT parent classes, create these widgets (objects) and build them into your new class (as attributes) so that when you instantiate your window object, it comes with all the widgets that was set up in the customised class for the window. And this is <strong>why with PyQt it only works using the Object Orientated paradigm</strong>.</li> </ul> <p>Is this correct? If not, where is my understanding going wrong? Thanks.</p>
<p>I can only speak about tkinter, but <em>both</em> modes are useful. Procedural code is useful for exploring with minimal boilerplate. For instance, after running the following from an Idle editor (intentionally without a <code>mainloop()</code> call)</p> <pre><code>from tkinter import * from tkinter.font import Font root = Tk() spin = Spinbox(root, from_=0, to=9, width=3, font=Font(family='Helvetica', size=36, weight='bold')) spin.pack() </code></pre> <p>I can interactively experiment with changing the attributes of <code>spin</code>, such as by entering</p> <pre><code>&gt;&gt;&gt; spin['fg'] = 'red' &gt;&gt;&gt; spin['fg'] = 'blue' &gt;&gt;&gt; spin['justify'] = 'right' </code></pre> <p>However, for a finished app of any complexity, I think it better to put gui setup code in a one or more methods of one or more classes. For instance, Idle, a tkinter app, is composed of numerous classes that either subclass a widget or contain a widget. </p>
python|tkinter|pyqt
3
1,906,732
46,536,579
How to sum same countries in a csv file using pandas
<p>I have a csv file and there are Count and Country columns. There are many Count and Country columns but this is the example I will write below.</p> <pre><code>Country Count Country Count Japan 654 Japan 566 US 90 US 90 </code></pre> <p>And I want the result :</p> <pre><code>Country Total Count Japan 1220 US 180 </code></pre> <p>How do I add the code in pandas :</p> <pre><code>import pandas as pd df = pd.read_csv('/Users/giyan/Desktop/monthly report/geoip/finalsumgeoip.csv') df['Total Count'] = df.filter(like='Count').sum(axis=1).astype(int) df = df[['Country','Total Count']] df.to_csv('podapoda.txt', sep='\t', encoding='utf-8') </code></pre>
<p>You can use the loc method for this. You can replace your your filter line with this:</p> <pre class="lang-python prettyprint-override"><code>df['Total count'] = df.loc[df['A'] =df['C'],['B','D']].sum(axis=1) </code></pre>
python|pandas|csv|log-analysis
0
1,906,733
49,396,727
Specify compression type in Confluent Python Avro Producer
<p>Is there a way to specify the <code>compression.type</code> in producer configs while using the AvroProducer in Confluent's Kafka (python)?</p> <p>I tried the following:</p> <pre><code>from confluent_kafka import avro from confluent_kafka.avro import AvroProducer from myconfigs import BOOTSTRAP_SERVER, SCHEMA_REGISTRY_URL, KEY_SCHEMA, VALUE_SCHEMA avroProducer = AvroProducer({'bootstrap.servers': BOOTSTRAP_SERVER, 'schema.registry.url': SCHEMA_REGISTRY_URL, 'compression.type': 'gzip'}, default_key_schema=KEY_SCHEMA, default_value_schema=VALUE_SCHEMA) </code></pre> <p>Got the following error when running this:</p> <pre><code>Traceback (most recent call last): File "confluent_click.py", line 47, in &lt;module&gt; default_key_schema=KEY_SCHEMA, default_value_schema=VALUE_SCHEMA) File "/usr/local/lib/python3.6/site-packages/confluent_kafka/avro/__init__.py", line 38, in __init__ super(AvroProducer, self).__init__(config) cimpl.KafkaException: KafkaError{code=_INVALID_ARG,val=-186,str="No such configuration property: "compression.type""} </code></pre> <p>Also tried specifying <code>compression_type = 'gzip'</code> as a param to <code>AvroProducer()</code> as</p> <pre><code>avroProducer = AvroProducer({'bootstrap.servers': BOOTSTRAP_SERVER, 'schema.registry.url': SCHEMA_REGISTRY_URL}, default_key_schema=KEY_SCHEMA, default_value_schema=VALUE_SCHEMA, compression_type='gzip') </code></pre> <p>I didn't expect this to succeed and it didn't.</p> <pre><code>Traceback (most recent call last): File "confluent_click.py", line 47, in &lt;module&gt; default_key_schema=KEY_SCHEMA, default_value_schema=VALUE_SCHEMA, compression_type='gzip') TypeError: __init__() got an unexpected keyword argument 'compression_type' </code></pre> <p>How can I specify <code>compression.type</code> in the producer? I have not been able to find <code>AvroProducer</code>'s documentation.</p>
<p>confluent-kafka-python's configuration property for setting the compression type is called <code>compression.codec</code> for historical reasons (librdkafka, which predates the current Java client, based its initial configuration properties on the original Scala client which used <code>compression.codec</code>).</p> <pre><code>avroProducer = AvroProducer({'bootstrap.servers': BOOTSTRAP_SERVER, 'schema.registry.url': SCHEMA_REGISTRY_URL, 'compression.codec': 'gzip'}, default_key_schema=KEY_SCHEMA, default_value_schema=VALUE_SCHEMA) </code></pre> <p>Note: the v0.11.4 release of confluent-kafka-python adds a <code>compression.type</code> alias.</p> <p>Full list of configuration settings here: <a href="https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md" rel="nofollow noreferrer">https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md</a></p>
python|compression|avro|kafka-producer-api|confluent-platform
1
1,906,734
49,727,668
remapping multiple column values with multiple dictionary in dataframe using python pandas
<p>i have following dataframe format</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>name,state,country a,1,67 b,2,52</code></pre> </div> </div> </p> <p>i have following state code and country code mapping dictionary</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>state_map = { 1:'tn', 2:'kerala' } country_map = { 67: 'usa', 52: 'india'</code></pre> </div> </div> i have used data.replace({'state':state_map,'country':'country_map'}) its working if we give one column mapping but not working for multiple mapping dictionary</p>
<p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow noreferrer">From the documentation</a> if giving a dict to replace:</p> <ul> <li>Nested dictionaries, e.g., {‘a’: {‘b’: nan}}, are read as follows: look in column ‘a’ for the value ‘b’ and replace it with nan. You can nest regular expressions as well. Note that column names (the top-level dictionary keys in a nested dictionary) cannot be regular expressions.</li> </ul> <p>So for your case your dict looks like:</p> <pre><code>r_map = {'state':{'1':'tn', '2':'kerala'},'country':{'67':'usa', '52':'india'}} </code></pre> <p>Use it like this:</p> <pre><code>df.replace(r_map) </code></pre>
python|python-2.7|pandas
2
1,906,735
49,642,542
converting coordinates given in list of tuples to complex number
<p>I have written the following code for calculating the closest pair in a plane. The code works fine but I have two questions. First, is there a shorter/better way to convert the representation of points from tuples to complex in the first function? and second, is the way I have passed the first function to the second function correct?</p> <pre><code>import sys x = [1, 4] y = [1, 5] def to_complex(hor, ver): list_of_points = list(zip(hor, ver)) list_of_points.sort(key=lambda el: (el[0], el[1])) complex_points = [complex(item[0], item[1]) for item in list_of_points] return complex_points # Brute force algorithm. def brute_force(points=to_complex(x, y)): n = len(points) if n &lt; 2: return sys.maxsize else: min_distance = sys.maxsize for i in range(n): for j in range(i + 1, n): if abs(points[i] - points[j]) &lt; min_distance: min_distance = abs(points[i] - points[j]) closest_pair = (points[i], points[j]) return min_distance, closest_pair print(brute_force()) </code></pre>
<p>A shorter version of <code>complex(item[0], item[1])</code> is <code>complex(*item)</code>, which splats a sequence into separate arguments. And I think this is a little better because it will explicitly fail on tuples longer than 2 items.</p> <p>But it might be even clearer to just write <code>item[0] + item[1] * 1j</code>. Besides looking like the way you write a complex number, this also avoids the implicit conversion to <code>float</code> that allows <code>complex(…)</code> to silently work on things like <code>Decimal</code> objects or <code>sympy</code> constant-valued expressions—you'll get an error in the first case, and a <code>sympy</code> complex constant-valued expression in the second. (Of course if you <em>want</em> to coerce things to <code>complex</code> values, that's a negative rather than a positive.)</p>
python
1
1,906,736
49,668,053
Python / opencv getting ret, frame from .read() when using self
<p>I hope you understand what I am asking for her. I have just started learning python and opencv, so If my question seems strange then that's probably the cause :-)</p> <p>I am trying to create a class in python to activate my camera. But I am struggling to get two values from the read() function when using <em>self</em>. </p> <pre><code>Normally you would just use: ret, frame = cap.read() </code></pre> <p>I just want to get the boolean return value from ret as well as frame from the class as well.</p> <pre><code>class Camera: def __init__(self): self.video_capture = cv2.VideoCapture(device) # if capture failed to open, try to open again if not self.video_capture.isOpened(): self.video_capture.open(device) self.ret ,self.current_frame = self.video_capture.read()[1] self.current_height = int(self.video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) # create thread for capturing images def start(self) -&gt; object: Thread(target=self._update_frame, args=()).start() def _update_frame(self): while (True): self.current_frame = self.video_capture.read()[1] # get the current frame def get_current_frame(self): return self.current_frame # get return 0 or 1 from cap.read() def get_ret(self): return self.retd() </code></pre> <p>How can i get both ret and frame from self.video_capture.read()?</p> <p>I have tried to search for my answer. But when you don't really know what to exactly search for, It gets difficult finding anything.</p>
<p>The error is in this line:</p> <pre><code>self.ret ,self.current_frame = self.video_capture.read()[1] </code></pre> <p>Basically you are accessing one value using <code>[1]</code> of the two values returned by <code>read()</code>. To obtain both values just remove it.</p> <pre><code>self.ret ,self.current_frame = self.video_capture.read() </code></pre> <p>If you are only interested in one value it is ok to use the <code>[1]</code></p>
python|opencv
0
1,906,737
70,289,115
filtering from list as query string postgresql flask sqlalchemy
<p>I am passing list as a query string and i want to retrieve data from database with the value of all the list value.The list value represents the value of a column.My code look something like this:</p> <pre><code>companylist=['a','b','c'] sql = text(&quot;&quot;&quot;select * from company_data cd where cd.company_id=:companyId&quot;&quot;&quot;) priceItem = connection.execute(sql, id=id, companyId=companylist).fetchAll() </code></pre> <p>This is how table looks like:</p> <pre><code>create table company_data ( id varchar(255) primary key, company_id text, price text, volume text ); </code></pre> <p>All i want is filter all the value based on value from the list from database and also the list cannot be greater than 20.How can i resolve this?</p>
<p>I am not understand about that <code>text()</code> and insert the value inside an <code>execute()</code>, here I make it to a sql command in string format.</p> <pre><code>companylist=['a','b','c'] sql = (&quot;&quot;&quot;select * from company_data cd where cd.company_id = ANY(ARRAY{})&quot;&quot;&quot;.format(companylist)) priceItem = connection.execute(sql).fetchAll() </code></pre> <p>This is refer to</p> <p><code>WHERE column = ANY(ARRAY([a, r, r, a, y]))</code></p>
python|postgresql|flask|sqlalchemy
0
1,906,738
53,525,787
How to find missing number from a list?
<p>I am breaking on the missing value in the list as subjected. And as well as attached in this question <a href="https://stackoverflow.com/questions/20718315/how-to-find-a-missing-number-from-a-list">How to find a missing number from a list?</a> </p> <p>How is it including missing value in the sum of range of list as mentioned below?</p> <pre><code>a=[1,2,3,4,5,7,8,9,10] sum(xrange(a[0],a[-1]+1)) - sum(a) </code></pre> <p>Result: <code>6</code></p>
<p>It's as simple as it could be.</p> <p>Try to break it down and it will be easier to understand:</p> <ul> <li><strong><em>xrange</em></strong> provides you with a generator that will eventually give you integers between the two numbers provides as the arguments to this function. So xrange(4,9) will give you (4,5,6,7,8). So the main takeaway is that xrange here gives integers from 4 till 9(including 4 and while excluding 9)</li> <li>Now the <strong><em>sum</em></strong> function just adds up the values inside a given object(here list);nothing more to explain here I believe</li> <li>So in your case, xrange(a[0],a[-1]+1) resulted into a generator which gives out values from a[0] i.e. 1 till and not including a[-1]+1 i.e. 11. Remember, in Python, negative indexing is referencing from backward. So a[-1] means last term in the list a. Similarly a[-2]=9.</li> <li>So now as we got a list of all the numbers b/w 1 to 10 and sum gives out 55 and sum of a itself is equal to 49(since it doesn't include 6), so the difference is your missing value.</li> </ul> <p>Note- One issue with this code is that let's say if there are more than 1 number missing, it will result into the sum of those missing values and not the missing value rather. So if a=[1,2,3,5,8,9,10], then this code will result into:</p> <pre><code>sum(1,2,3,4,5,6,7,8,9,10)-sum(1,2,3,5,8,9,10) and that will be equal to 17 </code></pre> <p><strong><em>On a sidenote</em></strong>- xrange is deprecated from Python 3 and I am like 90% sure this question will be marked as a bad one.</p>
python
1
1,906,739
53,489,897
Simpler method for performing replacement on multiple columns at a time?
<pre><code>import pandas as pd w=pd.read_csv('w.csv') </code></pre> <p>Takes sections of a CSV to add them up. Two columns require numerical conversion</p> <pre><code>w["Social Media Use Score"]=w.iloc[:,[6,7,8,9,10,11,12,13,14,15,16]].sum(axis=1) </code></pre> <p>Switches Yes or No in this section to 1 o 0 and adds them up, other section switches ABCD to 1234 and sums</p> <pre><code> w['Q1'],w['Q3'],w['Q6'] = w['Q1'].map({'No': 1, 'Yes': 0}),\ w['Q3'].map({'No': 1, 'Yes': 0}),\ w['Q6'].map({'No': 1, 'Yes': 0}) w['Q2'],w['Q4'],w['Q5'],w['Q7'],w['Q8'],w['Q9'],w['Q10']=\ w['Q2'].map({'Yes': 1, 'No': 0}),\ w['Q4'].map({'Yes': 1, 'No': 0}),\ w['Q5'].map({'Yes': 1, 'No': 0}),\ w['Q7'].map({'Yes': 1, 'No': 0}),\ w['Q8'].map({'Yes': 1, 'No': 0}),\ w['Q9'].map({'Yes': 1, 'No': 0}),\ w['Q10'].map({'Yes': 1, 'No': 0}) w["Anxiety Score"]=w.iloc[:,[17,18,19,20,21,22,23,24,25,26]].sum(axis=1) w['d1'],w['d2'],w['d3'],w['d4'],w['d5'],w['d6'],w['d7'],w['d8'],w['d9'],w['d10']=\ w['d1'].map({'A': 1, 'B': 2,'C':3,'D':4}),\ w['d2'].map({'A': 1, 'B': 2,'C':3,'D':4}),\ w['d3'].map({'A': 1, 'B': 2,'C':3,'D':4}),\ w['d4'].map({'A': 1, 'B': 2,'C':3,'D':4}),\ w['d5'].map({'A': 1, 'B': 2,'C':3,'D':4}),\ w['d6'].map({'A': 1, 'B': 2,'C':3,'D':4}),\ w['d7'].map({'A': 1, 'B': 2,'C':3,'D':4}),\ w['d8'].map({'A': 1, 'B': 2,'C':3,'D':4}),\ w['d9'].map({'A': 1, 'B': 2,'C':3,'D':4}),\ w['d10'].map({'A': 1, 'B': 2,'C':3,'D':4}) w['Depression Score']=w.iloc[:,[27,28,29,30,31,32,33,34,35,36]].sum(axis=1) w.to_csv("foranal.csv") </code></pre>
<p>If you want to perform replacement on multiple columns simultaneously, you should use <code>df.replace</code> (it is slower than <code>map</code>, so use it only if you can afford to). </p> <pre><code># Mapping for replacement. repl_dict = {'A':1, 'B':2,'C':3, 'D':4} repl_dict.update({'Yes':1, 'No':0}) # Generate the list of columns to perform replace on. cols = [f'{x}{y}' for x in ('Q','d') for y in range(1, 11)] w[cols] = w[cols].replace(repl_dict) # Fix values for special columns. w.loc[:, ['Q1', 'Q3', 'Q6']] = 1 - w.loc[:, ['Q1', 'Q3', 'Q6']] </code></pre> <p>"Social Media Use Score" and "Anxiety Score" are fine.</p>
python|pandas|csv
2
1,906,740
45,828,219
New to python: why does random.choice() produce correctly when alone but when placed in a name expression it doesnt
<p>If I do <code>random.choice</code> by itself, I get the desired result, but if I place it in a name expression, I don't. The reason I ask is because I'm making a rock paper scissor game and I need the computer to randomly choose between the three, and from what I've read it's not practical to use <code>random.choice</code> all on its lonesome. What would be the ideal solution? Thanks.</p> <p>Ex:</p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; l = [1,2,3] &gt;&gt;&gt; comprandom = random.choice(l) &gt;&gt;&gt; comprandom 1 &gt;&gt;&gt; comprandom 1 &gt;&gt;&gt; comprandom 1 &gt;&gt;&gt; comprandom 1 &gt;&gt;&gt; comprandom 1 &gt;&gt;&gt; comprandom 1 &gt;&gt;&gt; random.choice(l) 3 &gt;&gt;&gt; comprandom 1 &gt;&gt;&gt; </code></pre>
<p>When you type <code>comprandom</code> in an interactive prompt, you aren't repeatedly calling <code>random.choice(l)</code>. You're simply requesting that python return you the current value of the variable <code>comprandom</code>.</p> <p>You should call <code>random.choice(l)</code> every time you need a new random number.</p>
python|random
8
1,906,741
45,753,986
COPY data from S3 to RedShift in python (sqlalchemy)
<p>I'm trying to push (with COPY) a big file from s3 to Redshift. Im using sqlalchemy in python to execute the sql command but it looks that the copy works only if I preliminary TRUNCATE the table. </p> <p>the connection works ok:</p> <pre><code>from sqlalchemy import create_engine engine = create_engine('postgresql://XXXX:XXXX@XXXX:XXXX/XXXX') </code></pre> <p>with this command string (if I truncate the table before the COPY command)</p> <pre><code>toRedshift = "TRUNCATE TABLE public.my_table; COPY public.my_table from 's3://XXXX/part-p.csv' CREDENTIALS 'aws_access_key_id=AAAAAAA;aws_secret_access_key=BBBBBBB' gzip removequotes IGNOREHEADER 0 delimiter '|';" engine.execute(toRedshift) </code></pre> <p>If I remove the "TRUNCATE TABLE public.my_table;" bit </p> <pre><code>toRedshift = "COPY public.my_table from 's3://XXXX/part-p.csv' CREDENTIALS 'aws_access_key_id=AAAAAAA;aws_secret_access_key=BBBBBBB' gzip removequotes IGNOREHEADER 0 delimiter '|';" engine.execute(toRedshift) </code></pre> <p>But the command works perfectly in with any other SQL client (like DBeaver for example) </p>
<p>Thank you Ilja. With this command it works:</p> <pre><code>engine.execute(text(toRedshift).execution_options(autocommit=True)) </code></pre> <p>I don't know why I was able to push the data with the TRUNCATE bit at the front of the string. </p> <p>Ivan</p>
python|sql|amazon-s3|sqlalchemy|amazon-redshift
0
1,906,742
45,909,019
Reading from file each line to list in Python
<p>Here is my code:</p> <pre><code>with open(path) as file: lines = file.readlines() print lines[0:5] </code></pre> <p>However I get many extra characters, for example:</p> <pre><code>['cat2\xc2\xa0\xc2\xa0 2\xc2\xa0 0', 'cat1\xc2\xa00.5\xc2\xa0 0', 'cat2\xc2\xa0\xc2\xa0 1\xc2\xa0 0', 'cat1\xc2\xa0\xc2\xa0 0\xc2\xa0 0', 'cat2\xc2\xa0\xc2\xa0 0\xc2\xa0 3'] </code></pre> <p>Why do I get them?</p> <p>The original text file was this:</p> <pre><code>cat2   2  0 cat1 0.5  0 cat2   1  0 cat1   0  0 cat2   0  3 </code></pre>
<p><code>\xc2\xa0</code> is a <code>non-breaking space</code>. Replace it with regular spaces in the file.</p> <p>This sequence appears in many encodings including <code>UTF-8</code>.</p> <p>See more on <a href="https://en.wikipedia.org/wiki/Non-breaking_space" rel="nofollow noreferrer">Wikipedia</a></p>
python|file|encoding|character-encoding|special-characters
2
1,906,743
45,766,740
Typeerror when using CFFI to test C code using struct
<p>I'm working on a cffi testing demo, and when I try to run the python tester file, it returns the following error: TypeError: initializer for ctype 'Car *' appears indeed to be 'Car *', but the types are different (check that you are not e.g. mixing up different ffi instances)</p> <p>The car.h file defines the C structure Car and is shown here:</p> <pre><code>/*Class definition for car*/ typedef struct { char make[32]; char model[32]; char year[32]; char color[32]; } Car; </code></pre> <p>Here is the python file using cffi that I'm trying to use to test the C code.</p> <pre><code>import unittest import cffi import importlib ffi=cffi.FFI() def load(filename): #load source code source = open('../src/' + filename + '.c').read() includes = open('../include/' + filename + '.h').read() #pass source code to CFFI ffi.cdef(includes) ffi.set_source(filename + '_', source) ffi.compile() #import and return resulting module module = importlib.import_module(filename + '_') return module.lib class carTest(unittest.TestCase): def test_setMake(self): module = load('car') myCar = ffi.new('Car *', ["Honda", "Civic", "1996", "Black"]) make = ("char []", "Honda") self.assertEqual(module.setMake(myCar, make), car) if __name__ == '__main__': unittest.main() </code></pre> <p>Any advice on this issue would be very welcome. I feel like I've gone over it a hundred times.</p> <p>Thanks in advance</p>
<p>It's because you are mixing two unrelated <code>ffi</code> instance. There is the one you explicitly create and use inside the <code>load()</code> function to make the C extension module; in this kind of usage we recommend to call it <code>ffibuilder</code> instead of <code>ffi</code>. But then you import the compiled module, and you get a different <code>ffi</code> instance as <code>module.ffi</code>; that one comes from the C extension module. Ideally, you should no longer use the <code>ffibuilder</code> after compilation.</p> <p>I would recommend to change <code>load()</code> to return both <code>module.ffi</code> and <code>module.lib</code> (or maybe just <code>module</code>), kill the global <code>ffi</code> declaration, and make locally a <code>ffibuilder = cffi.FFI()</code> inside the <code>load()</code> function.</p>
c|python-cffi
0
1,906,744
38,462,641
selenium webdriver not working
<p>Selenium version: 2.53.6 Firefox version: 47.0.1 Chrome version: 51.0.2704.106 m</p> <p>Now if I want to use them like that:</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() driver2 = webdriver.Chrome() </code></pre> <p>i get an error: FileNotFoundError: [WinError 2]</p> <p>i even checked the manual twice that its the correct way to code it.</p> <p>So why cant it find the browsers even though everything is updated to latest version? Firefox and chrome work fine if I use them as person.</p> <p>edit: can provide error code in comment so here it is, (srry some parts are in german, as it is the main language istalled on my pc):</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; driver = webdriver.Firefox() File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 80, in __init__ self.binary, timeout) File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\firefox\extension_connection.py", line 52, in __init__ self.binary.launch_browser(self.profile, timeout=timeout) File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py", line 67, in launch_browser self._start_from_profile_path(self.profile.path) File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py", line 90, in _start_from_profile_path env=self._firefox_env) File "C:\Program Files (x86)\Python35-32\lib\subprocess.py", line 947, in __init__ restore_signals, start_new_session) File "C:\Program Files (x86)\Python35-32\lib\subprocess.py", line 1224, in _execute_child startupinfo) FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden </code></pre> <p>and for Chrome its:</p> <pre><code>Traceback (most recent call last): File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\common\service.py", line 64, in start stdout=self.log_file, stderr=self.log_file) File "C:\Program Files (x86)\Python35-32\lib\subprocess.py", line 947, in __init__ restore_signals, start_new_session) File "C:\Program Files (x86)\Python35-32\lib\subprocess.py", line 1224, in _execute_child startupinfo) FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;pyshell#2&gt;", line 1, in &lt;module&gt; driver2 = webdriver.Chrome() File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 62, in __init__ self.service.start() File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\common\service.py", line 71, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home </code></pre> <p>the wierd thing is i did include it in path enivornment variables. I can type in 'chromedriver' in the cmd and it finds it.... so python should too. 1 more mistake: doing last thing says some wierd stuff about: only local connetctions are allowed.</p>
<p>I'm not sure about running two drivers at the same time, but for the chrome part at least you may need to point it to a chrome driver (which you can download from <a href="https://sites.google.com/a/chromium.org/chromedriver/downloads" rel="nofollow">https://sites.google.com/a/chromium.org/chromedriver/downloads</a></p> <pre><code>import time from selenium import webdriver #driver = webdriver.Chrome('..\..\..\chromedriver.exe') # Optional argument, if not specified will search path that script is running in. driver = webdriver.Chrome('E:\AutomatedTesting\PyTestFramework\Automation\selenium\AdditionalDrivers\chromedriver.exe') #this is my path, I haven't worked out how to make the path relative to the script yet driver.get('http://www.google.com/xhtml'); time.sleep(5) # Let the user actually see something! search_box = driver.find_element_by_name('q') search_box.send_keys('ChromeDriver') search_box.submit() time.sleep(5) # Let the user actually see something! driver.quit() </code></pre>
python|python-3.x|selenium|selenium-webdriver
0
1,906,745
31,032,464
How to open Interactive Brokers' TWS from within Python
<p>A link to the latest version of TWS is <a href="https://www.interactivebrokers.com/java/classes/latest.jnlp?counter=0.9639924327729598" rel="nofollow">here</a>.</p> <p>When I opened the link in Firefox while watching the 'network' traffic (Ctrl+Shift+Q) it seemed to show a GET request to </p> <pre><code>https://www.interactivebrokers.com/java/classes/latest.jnlp?counter=0.9639924327729598 </code></pre> <p>(the counter is set to a random number). Yet, the following code returns a HTML web page; and not the 'latest.jnlp' file:</p> <pre><code>import requests import random url = 'https://www.interactivebrokers.com/java/classes/latest.jnlp?counter=' + str(random.random()) r = requests.get(url, stream=True) print r.content </code></pre> <p>How do I download the actual latest.jnlp file and save it?</p>
<p>The two functions below illustrate two different ways to download the file:</p> <pre><code>import random import urllib import urllib2 url = 'https://www.interactivebrokers.com/java/classes/latest.jnlp?counter=' + str(random.random()) def download_file_1(url): urllib.urlretrieve(url + ".jnlp", "latest.jnlp") def download_file_2(url): jnlpfile = urllib2.urlopen(url + ".jnlp") output = open('test.jnlp','wb') output.write(jnlpfile.read()) output.close() </code></pre> <p>Calling both these functions produces the same result: the file is simply downloaded and saved to the current working directory, with the names for the file specified as "latest.jnlp" and "test.jnlp". Since you didn't specify that it was necessary to use the requests library, I decided to use urllib and urllib2. </p> <p>Hope this is what you were looking for!</p>
python-2.7|web-scraping
1
1,906,746
30,773,189
I can't figure out this sequence - 11110000111000110010
<p>NOTE: This is for a homework assignment, but the portion I have a question on is ok to ask help for.</p> <p>I have to script out a sequence 11110000111000110010 (i am using python) without using switches or if statements and only a maximum of 5 for and whiles.</p> <p>I already have my script laid out to iterate, I just can't figure out the algorithm as recursive or explicit let alone whether the element's are 1's 2's or 4's =/</p> <p>As much as we have learned so far there is no equation or algorithm to use to figure OUT the algorithm for sequence. Just a set of instructions for defining one once we figure it out. Does anyone see a pattern here I am missing?</p> <p>EDIT: What I am looking for is the algorithm to determine the sequence. IE the sequence 1,3,6,10,15 would come out to be a[n]=(a[n-1]+n) where n is the index of the sequence. This would be a recursive sequence because it relies on a previous element's value or index. In this case a[n-1] refers to the previous index's value. Another sequence would be 2, 4, 6, 8 would come out to be a[n] = (n*2) which is an explicit sequence because you only require the current index or value.</p> <p>EDIT: Figured it out thanks to all the helpful people that replied.... I can't believe I didn't see it =/</p>
<p>There are many possible solutions to this problem. Here's a reusable solution that simply decrements from 4 to 1 and adds the expected number of 1's and 0's. </p> <p><strong>Loops used : 1</strong></p> <pre><code>def sequence(n): string = "" for i in range(n): string+='1'*(n-i) string+='0'*(n-i) return string print sequence(4) </code></pre> <p>There's another single-line elegant and more pythonic way to do this:</p> <pre><code>print ''.join(['1'*x+'0'*x for x in range(4,0,-1)]) </code></pre> <p><strong>Loops used : 1, Lines of code : 1</strong> </p> <p>;)</p>
python|algorithm|math|sequence|discrete-mathematics
3
1,906,747
28,976,484
Only allowing one instance of a pyqt4 application
<p>I have created a <code>pyqt4</code> app and I want to make it so only one instance (of QApplication) is allowed to run. </p> <p>The program reads and writes audio files, and if more than 1 instance is running, Windows (linux is fine) throws errors that 2 programs are trying to access the same files. I see a lot of java and C apps that will display a simple dialog if the program is already running, I just want to know how to do this in pyqt4. </p> <p>A little help?</p>
<p>This kind of programming pattern is called a "singleton" instance or a "singleton application".</p> <p>Usually it is done with a global mutex or by locking a file early in the life of the program. And when you program launches, if the file handle is already locked, then you exit.</p> <p>Qt Solutions has it here: <a href="http://doc.qt.digia.com/solutions/4/qtsingleapplication/qtsingleapplication.html" rel="nofollow noreferrer">http://doc.qt.digia.com/solutions/4/qtsingleapplication/qtsingleapplication.html</a></p> <p><a href="https://qt.gitorious.org/qt-solutions/qt-solutions/source/841982ceec9d30a7ab7324979a0fd5c9c36fd121:qtsingleapplication" rel="nofollow noreferrer">https://qt.gitorious.org/qt-solutions/qt-solutions/source/841982ceec9d30a7ab7324979a0fd5c9c36fd121:qtsingleapplication</a></p> <p>It would probably take a bit of work to get those global mutexes/locks to work in pyqt, since pyqt doesn't have the qt-solutions part in it yet as far as I could tell.</p> <p>Here is an alternative that uses a cross platform python script:</p> <p><a href="https://stackoverflow.com/questions/380870/python-single-instance-of-program">Python: single instance of program</a></p> <p>Hope that helps.</p>
python|qt|python-3.x|qt4|instance
2
1,906,748
28,986,156
Python movement of hands on analogue clock
<p>I am trying to draw a clock face in which the second hand moves as the time changes. I am using the following to calculate the points on my circle:</p> <pre><code>def points_on_circle(): global time, radius, centre, x, y theta = time% math.pi * 2 c = math.cos(theta) s = math.sin(theta) x= centre[0] + radius * c y =centre[1] + radius * s return x,y </code></pre> <p>my timer 'ticks' every tenth second, the radius of my circle is 50, the centre is at (150,150) which is also the origin of my hand, the other end of the hand being (x,y) as calculated above. How do I calculate , I assume by multiplying time by some constant, how fast the x,y should change for this circle ( but for any circle) . I am using CodeSkulptor from Coursera to try to do this ( the original assignment created a digital timer which I am done. This is not part of the homework ( yet??)</p>
<p>The hand rotates 2 Pi radians every 60 seconds. Assuming you're syncing with real time, time.time() will return the current time in seconds (and milliseconds which I suggest you ignore). If you take the time and first do <code>numseconds = int(time.time()) % 60</code>, you now need to translate that, which is a simple as numseconds * 2 * pi / 60. (Example: numseconds = 0, theta = 0, numseconds = 15, theta = pi /2 (90 degrees).</p> <p>You will also need to play with your equations as normally theta=0 implies the line is horizontal pointing right (which would be numseconds = 15) and theta=Pi implies the line is vertical pointing up (which would be numseconds = 0)</p>
python-2.7
2
1,906,749
52,155,265
My uptime function isn't able to go beyond 24 hours on Heroku
<p>I have the following uptime function for a Python Discord bot:</p> <pre><code>import datetime start_time = datetime.datetime.utcnow() # Timestamp of when it came online @client.command(pass_context=True) async def uptime(ctx: commands.Context): now = datetime.datetime.utcnow() # Timestamp of when uptime function is run delta = now - start_time hours, remainder = divmod(int(delta.total_seconds()), 3600) minutes, seconds = divmod(remainder, 60) days, hours = divmod(hours, 24) if days: time_format = "**{d}** days, **{h}** hours, **{m}** minutes, and **{s}** seconds." else: time_format = "**{h}** hours, **{m}** minutes, and **{s}** seconds." uptime_stamp = time_format.format(d=days, h=hours, m=minutes, s=seconds) await client.say("{} has been up for {}".format(client.user.name, uptime_stamp)) </code></pre> <p>I deployed this bot to Heroku (free tier) and over several days observed that I was never able to get an uptime of 24 hours or more (i.e. the uptime didn't report days, seemingly resetting midway somewhere, even though the bot was online throughout). I figured something might be wrong with my function, so I added print statements to debug, with a sample start time, <a href="https://pastebin.com/UnT3Ki87" rel="nofollow noreferrer">like so.</a></p> <p>My output showed that the function is capable of handling differences > 1 day:</p> <pre><code>The start time is: 2018-09-02 00:00:00 The time now is: 2018-09-03 18:58:03.458852 The delta is 1 day, 18:58:03.458852 The time difference in seconds is: 154683 Hours: 42, remainder: 3483 seconds Minutes: 58, remainder: 3 seconds Days: 1, remainder: 18 hours The time difference is over one day. **1** days, **18** hours, **58** minutes, and **3** seconds &gt;&gt;&gt; </code></pre> <p>Two questions:</p> <p>1) Is my uptime function sound? and 2) I'm reading now that Heroku may be resetting their free dynos every 24 hours - if this is the case, how can I get an uptime function that actually works over several days?</p> <p>Thanks!</p>
<p>Heroku restarts your dyno every 24 hours so you will never see more than 24 hours uptime. You would have to persist data in a store like Redis so it spans restarts.</p>
python|python-3.x|heroku|discord.py
3
1,906,750
59,576,792
What will be the correct angle to get the correct shape in clockwise direction
<p><img src="https://i.stack.imgur.com/EKkYU.png" alt=""> </p> <p><img src="https://i.stack.imgur.com/GS2wI.png" alt=""></p> <pre><code>from PyQt5.QtCore import (QByteArray,QDataStream, QIODevice,pyqtSlot, QMimeData, QPointF, QPoint, Qt, QRect,QTimer,QLineF, QEvent,QRectF) from PyQt5.QtGui import QColor,QDrag, QPainter, QPixmap,QFont,QFontMetrics,QBrush, QLinearGradient, QIcon, QPen, QPainterPath, QTransform,QCursor,QMouseEvent,QClipboard from PyQt5.QtWidgets import QApplication,QGraphicsTextItem,QStyleOptionGraphicsItem,QStyle,QGraphicsItemGroup,QErrorMessage, QSizePolicy,QShortcut, QScrollArea, QPushButton,QLineEdit, QMainWindow,QInputDialog, QGraphicsPathItem,QDialog, QVBoxLayout,QGraphicsItem,QStatusBar,QTextEdit, QAction,QMenu, qApp,QSplitter, QButtonGroup, QToolButton, QFrame, QHBoxLayout, QGraphicsView, QGraphicsItem, QGraphicsPixmapItem, QLabel, QGraphicsScene, QWidget import importlib class GraphicsSceneClass(QGraphicsScene): global selectedObjType def __init__(self, parent=None): super(GraphicsSceneClass, self).__init__(parent) self.gridOn = 0 self.setSceneRect(0, 0, 1920, 1080) self.setItemIndexMethod(QGraphicsScene.NoIndex) self.setBackgroundBrush(QBrush(Qt.black)) def mousePressEvent(self, event): sampleTransform = QTransform() objectAtMouse = self.itemAt(event.scenePos(), sampleTransform) if objectAtMouse and event.button()== Qt.LeftButton: objectAtMouse.setSelected(True) pass elif objectAtMouse==None and event.button()==Qt.RightButton: # pass self.grid = self.TargPosForLine(event.scenePos(), "ForLine") self.grid = self.TargPosForLine(event.scenePos(), "ForLine") opt=QStyleOptionGraphicsItem() opt.State=QStyle.State_None painter=QPainter() painter.setPen(Qt.NoPen) painter.setBrush(Qt.green) painter.drawRect(self.grid.x(),self.grid.y(),16,16) def TargPosForLine(self, position, mode): clicked_column = int((position.y() // 16)) * 16 clicked_row = int((position.x() // 16)) * 16 if clicked_column &lt; 0: clicked_column = 0 if clicked_row &lt; 0: clicked_row = 0 if(mode == "ForRect"): return QRect(clicked_row, clicked_column,16,16) elif(mode == "ForLine"): return QPointF(clicked_row,clicked_column) def mouseReleaseEvent(self, event): # self.DeselectItems() pass class MainWindow(QMainWindow): global selectedObjType # global item def __init__(self,): super(MainWindow, self).__init__() self.createToolbars() self.scene = GraphicsSceneClass() MainWindow.obj = self.scene self.view = QGraphicsView(self.scene) # self.view.setDragMode(QGraphicsView.RubberBandDrag) self.view.setMouseTracking(True) self.view.setRenderHint(QPainter.HighQualityAntialiasing) self.widg = QWidget() self.horizontalLayout = QHBoxLayout() self.horizontalLayout.addWidget(self.view) self.widg.setMouseTracking(True) self.widget = QWidget() self.widget.setLayout(self.horizontalLayout) self.setCentralWidget(self.widget) self.obj=None # def contextMenuEvent(self, event): contextMenu = QMenu(self) Cutaction = contextMenu.addAction("Cut") Coaction = contextMenu.addAction("Copy") Paaction = contextMenu.addAction("Paste") Propaction = contextMenu.addAction("draw1") Propaction1=contextMenu.addAction("draw2") quitAct = contextMenu.addAction("quit") action = contextMenu.exec_(self.mapToGlobal(event.pos())) if action == quitAct: self.close() elif action == Propaction: objectDrop = QGraphicsPathItem() painterPath = QPainterPath() painterPath.moveTo(10, 6) painterPath.lineTo(10 + 44.3479, 6) painterPath.arcTo(10 + 44.3479 - 6, 6 - 4, 4, 4, 270, 90) painterPath.lineTo(10 + 44.3479 - 2, 6 - 4) painterPath.arcTo(10 + 44.3479 - 6, 6 - 6, 4, 4, 0, 90) painterPath.lineTo(10, 0) gradient = QLinearGradient(1, 1, 1, 5) gradient.setColorAt(0, QColor(Qt.gray)) gradient.setColorAt(0.5, QColor(192, 192, 192, 255)) gradient.setColorAt(1, QColor(Qt.darkGray)) painterPath.closeSubpath() objectDrop.setPos(self.scene.grid) objectDrop.setPen(QPen(Qt.NoPen)) objectDrop.setPath(painterPath) objectDrop.setBrush(QBrush(gradient)) objectDrop._position = QPointF(self.scene.grid) print("line", self.scene.grid) objectDrop.setFlag(QGraphicsItem.ItemIsSelectable) objectDrop.setFlag(QGraphicsItem.ItemIsMovable) objectDrop._type1 = "line" self.scene.addItem(objectDrop) print(objectDrop) elif action==Propaction1: objectDrop = QGraphicsPathItem() painterPath = QPainterPath() painterPath.moveTo(10, 0) painterPath.lineTo(10 + 44.3479, 0) painterPath.arcTo(10 + 44.3479 - 6, 0 - 4, 4, 4, 270, 90) painterPath.lineTo(10 + 44.3479 - 2, 0 - 4) painterPath.arcTo(10 + 44.3479 - 6, 0 - 6, 4, 4, 0, 90) painterPath.lineTo(10, 6) gradient = QLinearGradient(1, 1, 1, 5) gradient.setColorAt(0, QColor(Qt.gray)) gradient.setColorAt(0.5, QColor(192, 192, 192, 255)) gradient.setColorAt(1, QColor(Qt.darkGray)) painterPath.closeSubpath() objectDrop.setPos(self.scene.grid) objectDrop.setPen(QPen(Qt.NoPen)) objectDrop.setPath(painterPath) objectDrop.setBrush(QBrush(gradient)) objectDrop._position=QPointF(self.scene.grid) print("line",self.scene.grid) objectDrop.setFlag(QGraphicsItem.ItemIsSelectable) objectDrop.setFlag(QGraphicsItem.ItemIsMovable) objectDrop._type1 = "line" self.scene.addItem(objectDrop) print(objectDrop) if __name__=="__main__": import sys app=QApplication(sys.argv) mainWindow = MainWindow() mainWindow.show() sys.exit(app.exec_()) </code></pre> <p>I need help in arcTo function of Qpainterpath.I have added the images of the painterpath code which i have mentioned here.</p> <p>In first image i have drawn the pathitem in counter clockwise direction. In second image I have drawn the pathitem in clockwise direction and it looks like twisted one.</p> <p>I have tried by changing the angle mentioned in arcTo with negative sign.But it is not giving the perfect item like in first image.</p> <p>What will be the correct angle to get the correct shape in clockwise direction</p>
<p>You could try something like this. I've added comments to indicate how the elements in item 2 relate to those in item 1. </p> <p>Item 1:</p> <pre><code>painterPath.moveTo(10, 6) # line 1 painterPath.lineTo(10 + 44.3479, 6) # arc 1 counter clockwise painterPath.arcTo(10 + 44.3479 - 6, 6 - 4, 4, 4, 270, 90) # line 2 painterPath.lineTo(10 + 44.3479 - 2, 6 - 4) # arc 2 counter clockwise painterPath.arcTo(10 + 44.3479 - 6, 6 - 6, 4, 4, 0, 90) # line 3 painterPath.lineTo(10, 0) </code></pre> <p>Item 2:</p> <pre><code>painterPath.moveTo(10, 0) # line 3 painterPath.lineTo(10 + 44.3479, 0) # arc 2 clockwise painterPath.arcTo(10 + 44.3479 - 6, 6 - 6, 4, 4, 90, -90) # line 2 painterPath.lineTo(10 + 44.3479 - 2, 6 - 4) # arc 1 clockwise painterPath.arcTo(10 + 44.3479 - 6, 6 - 4, 4, 4, 360, -90) # line 1 painterPath.lineTo(10, 6) </code></pre>
python|pyqt5
0
1,906,751
18,832,169
Numpy analog for Jython
<p>I am considering porting scientific code from Python to Jython and I am interested, whether there exist math libraries for Jython, which are:</p> <ol> <li>free for commercial use</li> <li>have convenient matrix syntax designed for Jython - i.e. permit slicing, binary and integer indexing, +-*/ operations like matlab and numpy.</li> </ol> <p>Additional availability of machine learning and statistical routes would be a plus (or easy convertibility of data to some common data format, understood by major Java machine learning libraries).</p> <p>Thanks in advance for any information about such libraries.</p>
<p>I took on the role of maintaining such a package a while back. It's called jnumeric (available on <a href="https://github.com/tbekolay/jnumeric" rel="noreferrer">github</a> and installable via <a href="http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.github.tbekolay.jnumeric%22" rel="noreferrer">maven</a>).</p> <p>JNumeric kind of has a weird history though, dating back to the early 2000s. It's never really been functionally equivalent to NumPy (or even numeric, which is what it's actually trying to emulate), and while it was "good enough" for what we were using it for, to use it as the primary number-cruncher in a Java program is probably not a good idea. It was a bad enough idea that we rewrote our application from scratch in Python so that we could use NumPy instead of trying to do vector math in Java. For that reason, jnumeric is undermaintained, and should probably silently fade into non-existence.</p> <p>I recently noticed a new project pop up on Github, <a href="https://github.com/JosephCottam/Numpy4J" rel="noreferrer">Numpy4J</a>, which may have a brighter future.</p> <p>While I know it doesn't quite address your question, I am curious why you would want to move to Jython for scientific code. Java does not have the nice number crunching and plotting libraries that Python has. ML libraries like Weka have Python equivalents in scikit-learn. Imaging stuff like ImageJ has an equivalent in scikit-image. Statistical packages exist in pandas and statsmodels. What is your scientific itch that Python does not scratch?</p> <p>If you want to move to Jython in order to interface with an existing Java library that cannot be easily ported to Python, I would consider <a href="http://jpype.sourceforge.net/" rel="noreferrer">JPype</a> rather than Jython.</p>
python|numpy|matrix|jython|slice
5
1,906,752
62,146,075
Django : no such table
<p>I am using a ManyToMany relationship using an intermediate table (keyword <code>through</code>) in django and I get a <code>OperationalError at /admin/workoutJournal/workout/add/ no such table: workoutJournal_workoutexercise</code></p> <p>My code is the following : </p> <pre><code>class Exercise(models.Model): name = models.CharField(max_length=120, default='') def __repr__ (self): return 'self.name' def __str__ (self): return self.name class planesOfMovement(models.TextChoices): SAGITTAL = 'SA', _('Sagittal') FRONTAL = 'FR', _('Frontal') TRANSVERSAL = 'TR', _('Transversal') planesOfMovement = models.CharField( max_length=2, choices=planesOfMovement.choices, default=planesOfMovement.FRONTAL, ) class typeOfMovement(models.TextChoices): PUSH = 'PS', _('Push') PULL = 'PL', _('Pull') CARRY = 'CA', _('Carry') LOAD = 'LO', _('Load') typeOfMovement = models.CharField( max_length=2, choices=typeOfMovement.choices, default=typeOfMovement.LOAD, ) class Workout(models.Model): date = models.DateField(default=datetime.date.today) exercises = models.ManyToManyField(Exercise, through='WorkoutExercise') def __str__(self): # __unicode__ on Python 2 return self.name # class Meta: # db_table = "workoutJournal_Workout_exercises" # necessary to update migrations when modifying the through # # argument of an existing relation class WorkoutExercise(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.DO_NOTHING) workout = models.ForeignKey(Workout, on_delete = models.PROTECT) sets = models.PositiveIntegerField() reps = models.PositiveIntegerField() tempo = models.CharField(max_length = 11, validators=[ RegexValidator(r'[0-9]{1,3}-[0-9]{1,3}-[0-9]{1,3}', message='Please format your tempo as [0-9]{1,3}-[0-9]{1,3}-[0-9]{1,3}') ]) </code></pre> <p>Any idea what I am doing wrong ? </p>
<p>Step 1: Delete all files in the <code>migrations</code> folder except <code>__init__.py</code>.<br> Step 2: Comment out all the fields in models.py, and add some random field, like:<br></p> <pre><code>class Exercise(models.Model): randomfield = models.CharField(max_length=10) #name = models.CharField(max_length=120, default='') #def __repr__ (self): # return 'self.name' #def __str__ (self): # return self.name </code></pre> <p>Step 3: Run <code>python manage.py makemigrations</code> and <code>python manage.py migrate</code> in your terminal or CMD.</p> <p>Step 4: Now remove the random field and uncomment the fields, like:</p> <pre><code>class Exercise(models.Model): name = models.CharField(max_length=120, default='') def __repr__ (self): return 'self.name' def __str__ (self): return self.name </code></pre> <p>Step 5: Run <code>python manage.py makemigrations</code> and <code>python manage.py migrate</code> again. <br> I hope that this should work for you.<br> Note: Be sure to do this with all models!</p>
python|django|django-models
1
1,906,753
64,485,588
BeautifulSoup can't find my table because of some weird string
<p>Hi I have been trying to get a table from wunderground using BeautifulSoup but it just doesn't work.</p> <p>I think it could be for the starnge string next to the table header but i can´t fix it.</p> <p>Here is my code:</p> <pre><code>from bs4 import BeautifulSoup import requests url='https://www.wunderground.com/history/daily/LEMD/date/2020-10-21' html_content = requests.get(url).text soup = BeautifulSoup(html_content, &quot;html.parser&quot;) table = soup.find(&quot;table&quot;, {&quot;class&quot;: &quot;mat-table cdk-table mat-sort ng-star-inserted&quot;}) table_data = table.tbody.find_all(&quot;tr&quot;) </code></pre> <p>and the error:</p> <pre><code>Traceback (most recent call last): File &quot;weather_poc.py&quot;, line 12, in &lt;module&gt; table_data = table.tbody.find_all(&quot;tr&quot;) AttributeError: 'NoneType' object has no attribute 'tbody' </code></pre>
<p>The data you see is loaded from external URL via JavaScript. You can use <code>requests</code>/<code>json</code> module to load it. For example:</p> <pre><code>import json import requests import pandas as pd url = 'https://api.weather.com/v1/location/LEMD:9:ES/observations/historical.json?apiKey=6532d6454b8aa370768e63d6ba5a832e&amp;units=e&amp;startDate=20201021&amp;endDate=20201021' data = requests.get(url).json() # uncomment this line to print all data: # print(json.dumps(data, indent=4)) df = pd.json_normalize(data['observations']) df.to_csv('data.csv', index=False) </code></pre> <p>Creates <code>data.csv</code> (screenshot from LibreOffice):</p> <p><a href="https://i.stack.imgur.com/aymlH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aymlH.png" alt="enter image description here" /></a></p>
python|python-3.x|web-scraping|beautifulsoup|wunderground
1
1,906,754
70,416,030
Windowing with Looking back in numpy array in python
<p>following the array I have. I have added my expected result that i am not getting with attached code.</p> <pre><code>p= array([[0.26650886, 0.6108316 , 0.87093688, 0.56106049], [0.27189878, 0.60786972, 0.87653939, 0.54244087], [0.27508257, 0.60678571, 0.87979568, 0.5297218 ], [0.27582241, 0.60754711, 0.88034473, 0.51667662], [0.27606467, 0.60711087, 0.8800212 , 0.51716336], [0.27705633, 0.60654571, 0.88044624, 0.52474009], [0.27909608, 0.60545549, 0.88164035, 0.52696207], [0.28027486, 0.60447923, 0.8821804 , 0.51754806], [0.27989394, 0.6036416 , 0.88188837, 0.50952766], [0.27953247, 0.6015729 , 0.88151134, 0.51027505]]) ​ </code></pre> <p>Expected result i want, lets say window_size=4 I am not getting this using below code.</p> <pre><code>[[0.26650886, 0.6108316 , 0.87093688, 0.56106049], [0.27189878, 0.60786972, 0.87653939, 0.54244087], [0.27508257, 0.60678571, 0.87979568, 0.5297218 ], [0.27582241, 0.60754711, 0.88034473, 0.51667662] [0.27189878, 0.60786972, 0.87653939, 0.54244087], [0.27508257, 0.60678571, 0.87979568, 0.5297218 ], [0.27582241, 0.60754711, 0.88034473, 0.51667662], [0.27606467, 0.60711087, 0.8800212 , 0.51716336] [0.27508257, 0.60678571, 0.87979568, 0.5297218 ], [0.27582241, 0.60754711, 0.88034473, 0.51667662], [0.27606467, 0.60711087, 0.8800212 , 0.51716336], [0.27705633, 0.60654571, 0.88044624, 0.52474009].....] </code></pre> <p>I did the following code but it not giving me a result that I want.</p> <pre><code># df is dataframe with shape(14, 4) X = np.zeros(shape=(df.shape[0]-window_size,window_size,df.shape[1])) for i in range(window_size-1, 10): for j in range(i-window_size+1, i+1): X[i-window_size+1][window_size-1-i+j] = p[j] </code></pre> <p>Thanks in advance</p>
<p>A more efficient solution would be to use <a href="https://numpy.org/doc/stable/reference/generated/numpy.lib.stride_tricks.sliding_window_view.html" rel="nofollow noreferrer"><code>sliding_window_view</code></a> from <code>numpy.lib.stride_tricks</code>:</p> <pre><code>from numpy.lib.stride_tricks import sliding_window_view values_per_arr = 4 # or p.shape[1] window_size = 4 X = sliding_window_view(p, window_shape=(window_size,values_per_arr)).reshape(-1, values_per_arr, window_size) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; X array([[[0.26650886, 0.6108316 , 0.87093688, 0.56106049], [0.27189878, 0.60786972, 0.87653939, 0.54244087], [0.27508257, 0.60678571, 0.87979568, 0.5297218 ], [0.27582241, 0.60754711, 0.88034473, 0.51667662]], [[0.27189878, 0.60786972, 0.87653939, 0.54244087], [0.27508257, 0.60678571, 0.87979568, 0.5297218 ], [0.27582241, 0.60754711, 0.88034473, 0.51667662], [0.27606467, 0.60711087, 0.8800212 , 0.51716336]], [[0.27508257, 0.60678571, 0.87979568, 0.5297218 ], [0.27582241, 0.60754711, 0.88034473, 0.51667662], [0.27606467, 0.60711087, 0.8800212 , 0.51716336], [0.27705633, 0.60654571, 0.88044624, 0.52474009]], [[0.27582241, 0.60754711, 0.88034473, 0.51667662], [0.27606467, 0.60711087, 0.8800212 , 0.51716336], [0.27705633, 0.60654571, 0.88044624, 0.52474009], [0.27909608, 0.60545549, 0.88164035, 0.52696207]], [[0.27606467, 0.60711087, 0.8800212 , 0.51716336], [0.27705633, 0.60654571, 0.88044624, 0.52474009], [0.27909608, 0.60545549, 0.88164035, 0.52696207], [0.28027486, 0.60447923, 0.8821804 , 0.51754806]], [[0.27705633, 0.60654571, 0.88044624, 0.52474009], [0.27909608, 0.60545549, 0.88164035, 0.52696207], [0.28027486, 0.60447923, 0.8821804 , 0.51754806], [0.27989394, 0.6036416 , 0.88188837, 0.50952766]], [[0.27909608, 0.60545549, 0.88164035, 0.52696207], [0.28027486, 0.60447923, 0.8821804 , 0.51754806], [0.27989394, 0.6036416 , 0.88188837, 0.50952766], [0.27953247, 0.6015729 , 0.88151134, 0.51027505]]]) </code></pre>
python|numpy
1
1,906,755
73,028,210
How to "translate" string into an integer in python?
<p>I have the following df:</p> <pre><code>print(df) &gt;&gt;&gt; Marital Status Income Education Married 66613 PhD Married 12441 Bachelors Single 52842 Masters Degree Relationship 78238 PhD Divorced 21242 High School Single 47183 Masters Degree </code></pre> <p>I'd like to convert every &quot;String&quot; to a corresponding number (int). E.g.</p> <p>&quot;Married&quot; should be <strong>1</strong></p> <p>&quot;Single&quot; <strong>2</strong></p> <p>&quot;Relationship&quot; <strong>3</strong></p> <p>and so on.</p> <p>I still haven't tried any code yet since I haven't found any reasonable solution after googling for around 1 hour now, but I am sure that the solution is most likely incredibly simple.</p> <p>Edit: grammar</p>
<p>This may help you to get what you need.</p> <pre class="lang-py prettyprint-override"><code>df['Marital Status'] = df['Marital Status'].astype('category').cat.codes </code></pre> <p>Reference: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.astype.html" rel="noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.astype.html</a></p>
python|pandas|string|integer
6
1,906,756
55,730,536
Index in pandas.to_sql, ValueError: duplicate name in index/columns: cannot insert id, already exists
<p>I am reading and writing MySQL table with pandas and I am pretty sure that the value I am trying to set as index during writing is unique. I checked the table without an index and <code>count(distinct(id))</code> gives the same amount of rows as <code>count(id)</code>. However, I still get an error</p> <pre><code>'ValueError: duplicate name in index/columns: cannot insert product_id, already exists' </code></pre> <p>if i set <code>index=True, index_label="id"</code></p> <p>I have tried <code>reset_index</code>, but it did not help.</p> <p><code>df.to_sql(name=config.DB_TABLE, con=connection, schema=config.DB_SCHEMA, if_exists='fail', index=True, index_label="id")</code></p> <p>What am I doing wrong?</p>
<p>I had the same issue and was wondering. The problem was, that in the mean time while programming I had added a column into my DataFrame. Consequently, the columns did not match with the SQL Columns anymore. You should check the matching of your columns.</p>
python|mysql|pandas|indexing
0
1,906,757
50,040,534
pandas pivot_table returns empty dataframe
<p>I get an empty dataframe when I try to group values using the pivot_table. Let's first create some stupid data:</p> <pre><code>import pandas as pd df = pd.DataFrame({"size":['large','middle','xsmall','large','middle','small'], "color":['blue','blue','red','black','red','red']}) </code></pre> <p>When I use:</p> <pre><code>df1 = df.pivot_table(index='size', aggfunc='count') </code></pre> <p>returns me what I expect. Now I would like to have a complete pivot table with the color as column:</p> <pre><code>df2 = df.pivot_table(index='size', aggfunc='count',columns='color') </code></pre> <p>But this results in an empty dataframe. Why? How can I get a simple pivot table which counts me the number of combinations? Thank you.</p>
<p>You need to use len as the aggfunc, like so</p> <pre><code>df.pivot_table(index='size', aggfunc=len, columns='color') </code></pre> <p>If you want to use count, here are the steps:</p> <ol> <li><p>First add a frequency columns, like so:</p> <pre><code>df['freq'] = df.groupby(['color', 'size'])['color'].transform('count') </code></pre></li> <li><p>Then create the pivot table using the frequency column:</p> <pre><code>df.pivot_table(values='freq', index='size', aggfunc='count', columns='color') </code></pre></li> </ol>
python|pandas|count|pivot-table
2
1,906,758
66,506,081
Indexing a 2d array with another 2d array
<p>I have an array <code>lines = np.array[[0,0],[0,1],[1,0],[1,2],[2,0],[2,1],[2,3],[3,1],[3,3],[0,1],[1,2],[4,4]]</code> and another numpy zeros array <code>vectors = [[0. 0. 0. 0. 0.],[0. 0. 0. 0. 0.],[0. 0. 0. 0. 0.],[0. 0. 0. 0. 0.],[0. 0. 0. 0. 0.]]</code> I want to use the elements in the first array(lines) to insert &quot;1's&quot; into the second array(vectors).</p> <p>So my desired output would be:</p> <pre><code>vectors = [[1. 1. 1. 0. 0.], [1. 0. 1. 1. 0.], [0. 1. 0. 0. 0.], [0. 0. 1. 1. 0.], [0. 0. 0. 0. 1.]] </code></pre> <p>Note: Take into account in the lines array all the second numbers are used to index a particular array in the vectors array and the first number is where to place the &quot;1&quot;. e.g., lines[2] = [1,0], lines[2][1] = 0 and lines[2][0] = 1 so you will use the 0 to index into the 0th array in the vectors array and place a &quot;1&quot; in the 1st position(index 1).</p> <p>Apologies if I explained it badly I am new to python and StackOverflow.</p>
<p><strong>Use:</strong> <code>vectors[lines[:, 1], lines[:, 0]] = 1</code></p> <p><strong>Explanation:</strong> <code>lines[:, n]</code> indexes the nth column of the 2-D lines array. So according to your specifications, <code>lines[:, 1]</code> (the first column) contains the row numbers of the <code>vectors</code> array. Then we use <code>lines[:, 0]</code> (i.e. values in the zeroth column) to substitute in appropriate columns in the <code>vectors</code> array.</p>
python|arrays|numpy|multidimensional-array|indexing
1
1,906,759
64,783,520
Debugging: Right View of Binary Tree
<p>Given a Binary Tree, find the Right view of it. The right view of a Binary Tree is a set of nodes visible when the tree is viewed from the right side.</p> <p>Right view of the following tree:</p> <blockquote> <p>1 3 7 8</p> </blockquote> <pre><code> 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 </code></pre> <p><strong>Example 1:</strong></p> <p><em>Input:</em></p> <pre><code> 1 / \ 3 2 </code></pre> <p>Output:</p> <blockquote> <p>1 2</p> </blockquote> <p><strong>Example 2:</strong></p> <p><em>Input:</em></p> <pre><code> 10 / \ 20 30 / \ 40 60 </code></pre> <p><em>Output:</em></p> <blockquote> <p>10 30 60</p> </blockquote> <p><strong>Task:</strong> Just complete the function rightView() that takes node as parameter and returns the right view as a list.</p> <p><strong>My Code:</strong></p> <pre><code>''' # Node Class: class Node: def init(self,val): self.data = val self.left = None self.right = None ''' def func(list1,root,level,max_level): if not root: return if max_level&lt;level: list1.append(root.data) max_level=level func(list1,root.right,level+1,max_level) func(list1,root.left,level+1,max_level) def rightView(root): max_level = 0 list1 = [] func(list1,root,1,max_level) return list1 </code></pre> <p>Note that when I submit this code I'm getting the Wrong Answer.</p> <p>If I change <code>max_level = 0</code> to <code>max_level=[0]</code> and all the other max_level lines like <code>max_level&lt;level</code> to <code>max_level[0]&lt;level</code> and <code>max_level=level</code> to <code>max_level[0]=level</code>.</p> <p>If I make these changes, I'm getting the correct answer.</p> <p>Why is this so?</p>
<p>When you use <strong>max_level = 0</strong>, this variable is not passed in the function by reference, So it is not updated for every function call using it.</p> <pre><code>func(list1,root.right,level+1,max_level) func(list1,root.left,level+1,max_level) </code></pre> <p>Suppose you update the max_level in the first function call, although it remains the same as it is previously set for the second function call</p> <p>While <strong>max_level = [0]</strong>, this list is <em><strong>passed by reference</strong></em>, So when you make updates to it. Those changes are effective for all the function call using it.</p>
python|algorithm|recursion|data-structures|tree
1
1,906,760
64,083,255
How to make two loop print, print on 2 differents lines, without erasing what the other wrote
<p>I have two functions using two differents processes, and each have a while loop with a print(data + &quot;\r&quot;, end=&quot;&quot;)?</p> <p>EDIT: Here is an example of what I'd want:</p> <pre><code>$&gt; First line $&gt; $&gt; $&gt; 5/10 (0%) &lt; This is what function 1 print $&gt; 111/400 (0%) &lt; This is what function 2 print </code></pre> <p>And what they do right now is they overwrite what the other write. I'd like them to overwrite their own line and not what the other wrote.</p> <p>Here is the code I have right now:</p> <pre><code>def print_i(): i = 0 while (i &lt; 50000): print(i, + &quot;\r&quot;, end='') i += 1 def main(): p = multiprocessing.Pool() p.apply_async(print_i, args=(0,)) p.apply_async(print_i, args=(1,)) p.close() p.join() </code></pre>
<p>try to make a common print handler who get the data from the two function and let it scheduling</p>
python|cmd|printing
-1
1,906,761
53,283,421
Serving django app in an intended location (NGINX)
<p>I have a web server serving my Django app (using NGINX) and I need to access it in a defined "location".</p> <p>For example, I access my Django app XPTO in "ip:port/" but I need to access it like "ip:port/XPTO/". All urls specified in Django have to be resolved "after" this "base url".</p> <p>Anyway I can do this without messing with my "urls.py" in Django? I had tried some configurations on NGINX but nothing worked.</p> <p>Thanks in advance!</p>
<p>You need to use the <code>location</code> directive in your nginx config.</p> <p>You probably have something right now that looks like this:</p> <pre><code>location / { ... } </code></pre> <p>To serve under XPTO instead you want this:</p> <pre><code>location /XPTO/ { ... } </code></pre> <p>You also need to be sure that you generate all internal links via the <code>url</code> tag or the <code>reverse</code> function, so that they will automatically include the prefix. </p> <p>If this doesn't work, please show us your current nginx config (edit it into the question) and we may be able to provide more specific advice.</p>
python|django|web|nginx|webserver
1
1,906,762
53,132,093
Django - Database design
<p>I have the following database so far:</p> <pre><code>Person model Student model inherits from Person, no added functionality Lecturer model same as Student Course model leader = ForeignKey to Lecturer (1 Lecturer can have many courses) students = ManytoMany with Student (Many students can take many courses) Card model student = OneToOne with student (1 card per 1 student). Event model course = ForeignKey to Course (One course can have many events) </code></pre> <p>Now my question is; I want to mark students present in an event based on the following criteria. On creation of Event, marked students need to be empty. Later I will create a view that will register a Card ID. The Card model has a 1-1 relationship with student. Student is many-many with Course. Course is a FK to Event. </p> <ul> <li>They need to be part of the same course that the Event is connected to.</li> <li>The marked present students need to be visible inside the model later on.</li> </ul> <p>How do I go about doing this?</p>
<p>If it were me, I might use a dedicated Attendance table (something like the following):</p> <pre><code>class Attendance(Model): student = models.ForeignKey('Student') event = models.ForeignKey('Event') present = models.BooleanField(default=True) </code></pre> <p>You could swap out the student field for a Card instead, if that's what you desire (but since it's a one-to-one, it doesn't really matter). The default value for the <code>present</code> field could also be swapped, depending on how you want to treat entries in this table.</p>
python|django|database
1
1,906,763
53,339,223
COPY Postgres table to CSV output, paginated over n files using python
<p>Using psycopg2 to export Postgres data to CSV files (not all at once, 100 000 rows at a time). Currently using <code>LIMIT OFFSET</code> but obviously this is slow on a 100M row db. Any faster way to keep track of the offset each iteration?</p> <p><code> for i in (0, 100000000, 100000): "COPY (SELECT * from users LIMIT %s OFFSET %s) TO STDOUT DELIMITER ',' CSV HEADER;" % (100000, i)</code></p> <p>Is the code run in a loop, incrementing <code>i</code></p>
<p>Let me suggest you a different approach.</p> <p>Copy the whole table and split it afterward. Something like: </p> <pre><code>COPY users TO STDOUT DELIMITER ',' CSV HEADER </code></pre> <p>And finally, from bash execute the split command (btw, you could call it inside your python script):</p> <pre><code>split -l 100000 --numeric-suffixes users.csv users_chunks_ </code></pre> <p>It'll generate a couple of files called users_chunks_1, users_chunks_2, etc.</p>
python|postgresql|psycopg2
1
1,906,764
68,511,961
Why torch.nn.Conv2d has different result between '(n, n)' and 'n' arguments?
<pre><code>input = torch.randn(8, 3, 50, 100) m = nn.Conv2d(3, 3, kernel_size=(3, 3), padding=(1, 1)) m2 = nn.Conv2d(3, 3, kernel_size=3, padding=1) output = m(input) output2 = m2(input) torch.equal(output, output2) &gt;&gt; False </code></pre> <p>I suppose above m and m2 Conv2d should have exactly same output value but practically not, what is the reason?</p>
<p>You have initialized two <code>nn.Conv2d</code> with identical settings, that's true. Initialization of the weights however is done randomly! You have here two different layers <code>m</code> and <code>m2</code>. Namely <code>m.weight</code> and <code>m2.weigth</code> have different components, same goes for <code>m.bias</code> and <code>m2.bias</code>.</p> <p>One way to have get the same results, is to copy the underlying parameters of the model:</p> <pre><code>&gt;&gt;&gt; m.weight = m2.weight &gt;&gt;&gt; m.bias = m2.bias </code></pre> <p>Which, of course, results in <code>torch.equal(m(input), m2(input))</code> being <code>True</code>.</p>
machine-learning|deep-learning|pytorch|conv-neural-network
3
1,906,765
68,452,681
Parsing datetime with milliseconds
<p>stackoverflow community. I was writing a program which takes a data from optical unit and stores to the server. I am having a problem with parsing the data with pandas. In my data, the datetimes are with milliseconds. However, I dont know how to parse a date with corresponding format string. My code is only converting string into year,month,day,hour,minute, and second. My code:</p> <pre><code>data['Datetime'] = pd.to_datetime(data['Datetime'], format='%Y-%m-%d %H:%M:%S') </code></pre> <p>This is the sample datetime from the source I am using: <strong>2021-07-09 09:41:30.839000</strong> Thanks for any help)</p>
<p>try without passing the format:</p> <pre><code>pd.to_datetime(&quot;2021-07-09 09:41:30.839000&quot;) </code></pre> <blockquote> <p>Timestamp('2021-07-09 09:41:30.839000')</p> </blockquote>
python|pandas|numpy|date|datetime
0
1,906,766
71,655,623
Why is my password generator only generating one password?
<p>Im a beginner to python and wish for help with this</p> <pre><code>print('Password generator ') letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&amp;*().,?0123456789' numv = int(input('Amounts of Passwords to generate:')) leny = input('Input your password length:') leny = int(leny) print('Here are your passwords:') for pwd in range(numv):     passwords = '' for c in range(leny):     passwords += random.choice(letter) print(passwords) </code></pre> <p>I don't understand why it isn't printing out more than one password when I run it.</p>
<p>What you want to do is nest the second for-loop in the first one.</p> <pre class="lang-py prettyprint-override"><code>for pwd in range(numv): passwords = '' </code></pre> <p>This for-loop doesn't do anything as of right now it is equivalent as if you had just written:</p> <pre class="lang-py prettyprint-override"><code>passwords = '' </code></pre> <p>To achieve the desired behaviour you'd need to do something like this:</p> <pre class="lang-py prettyprint-override"><code>passwords = '' for pwd in range(numv): for c in range(leny): passwords += random.choice(letter) passwords += &quot;|&quot; # This is just a separator </code></pre> <p>You'll notice I added <code>passwords += &quot;|&quot;</code> at the end of every iteration of the outer for-loop. This is just for you to be able to distinguish the different passwords when you print the string later. Without it the output would look like <code>password1password2password3</code> but with it you'd get <code>password1|password2|password3</code></p> <p>An even better approach is to declare <code>passwords</code> as a list and append the different passwords to that list:</p> <pre class="lang-py prettyprint-override"><code>passwords = [] for pwd in range(numv): password = &quot;&quot; for c in range(leny): password += random.choice(letter) passwords.append(password) for password in passwords: print(password) </code></pre>
python
1
1,906,767
10,627,898
How to force a directory listing using SimpleHTTPServer?
<p>I have an <code>index.html</code> on the folder where SimpleHTTPServer is running, but depending on the value of a URL GET parameter I want to show a directory listing instead. Is that possible? I was trying to query the root directory using ajax, but it returns <code>index.html</code>by default. </p> <p>I guess one possible option is to rename <code>index.html</code> to something like <code>main.html</code> and never use index.html.</p>
<p>You can override do_GET() and catch the path and parameter you are interested in, and do the right thing from there.</p>
javascript|python
1
1,906,768
67,487,062
DeprecationWarning: remove_friend is deprecated. await coro(*args, **kwargs)
<p>I wanted to make self bot and command to unfriend someone but when I use it removes friends but gives me a warning:</p> <pre><code>DeprecationWarning: remove_friend is deprecated. await coro(*args, **kwargs) </code></pre> <p>Code:</p> <pre><code>for i in client.user.friends: try: await i.remove_friend() except: pass </code></pre>
<p>As of version 1.7, all user related endpoints are deprecated and awaiting their subsequent removal in version 2.0 of <code>discord.py</code>. You can currently safely ignore this warning but be aware that when 2.0 will be released, if you decide to upgrade, your code wont work anymore.</p> <p>You can add this shebang if you are running Linux to prevent warning in console</p> <p><code>#!/usr/bin/env python -W ignore::DeprecationWarning</code></p> <p>If you run Windows, the equivalent is <code>python file_name.py -W ignore::DeprecationWarning</code></p> <p>If that does not work you can use this quick and dirty hack (it will hide any warning so be careful). Put below code at the top of your files.</p> <pre><code>def warn(*args, **kwargs): pass import warnings warnings.warn = warn </code></pre>
python|discord|discord.py
1
1,906,769
70,155,440
How to do chapter analysis from books imported from nltk.corpus.gutenberg.fileids()
<p>I am a newbie using python. Now I am doing natural language processing for a novel, and I choose to load the book from nltk.corpus.gutenberg.fileids(). I just use 'Sense and Sensibility'. Then I want to analyze each chapter. How to split the whole book into parts? I notice that the books loaded this way has unique format. It's not like txt format.</p> <pre><code>import nltk nltk.download('gutenberg') nltk.corpus.gutenberg.fileids() </code></pre> <p>When I print the book out, it shows: ['[', 'Sense', 'and', 'Sensibility', 'by', 'Jane', ...]</p> <pre><code>sense = nltk.Text(nltk.corpus.gutenberg.words('austen-sense.txt')) print(sense) </code></pre> <p>Then here is another format: &lt;Text: Sense and Sensibility by Jane Austen 1811&gt; I don't know what it means.</p> <p>If I use another .txt book source, I also don't know how to split the chapters. I've uploaded the book into the folder, then:</p> <pre><code>text = 'senseText.txt' </code></pre>
<blockquote> <p>It's not like txt format.</p> </blockquote> <p>If you want something more like the whole text, try:</p> <pre><code>raw = nltk.Text(nltk.corpus.gutenberg.raw('austen-sense.txt')) </code></pre> <p>If you want individual sentences, you can use:</p> <pre><code>sentences = nltk.Text(nltk.corpus.gutenberg.sents('austen-sense.txt')) </code></pre> <p>Gutenberg doesn't break up the text by chapters for you. (Many of the original sources didn't have chapters to begin with.) If your specific text happens to include chapter breaks in the raw, you could try searching for those, but it'd be text-specific.</p>
python|nlp|format|nltk|wordpress-gutenberg
0
1,906,770
70,444,108
How to send emails with both text part and html table in python?
<p>I am using below method to send emails with a text part and a html table. For the html table, i have used pretty_html_table library.</p> <p>First I got table data using a query as below.</p> <pre><code>def get_data(): &quot;&quot;&quot;&quot; data :return: &quot;&quot;&quot; df = pd.read_sql(raw_data_query, db_connection) data=pd.DataFrame(df) return data </code></pre> <p>Then I have initated a sendmail method as below.</p> <pre><code> def send_mail(body): message=MIMEMultipart() message['From']='' message['To']='&gt;' message['Subject']=&quot;Daily Termination Data &quot; text = f&quot;&quot;&quot; Dear All,&lt;br/&gt;&lt;br/&gt; Please refer below termination data :&lt;br/&gt;&lt;br/&gt; &lt;b&gt;This is an automated email, Please do not reply ...&lt;/b&gt; &quot;&quot;&quot; body_content=body message.attach(MIMEText(text,&quot;html&quot;)) message.attach(MIMEText(body_content,&quot;html&quot;)) msg_body=message.as_string() try: smtpObj = smtplib.SMTP('XXX',25) smtpObj.sendmail(sender, receivers, msg_body) print (&quot;Successfully sent email&quot;) except smtplib.SMTPException: print (&quot;Error: unable to send email&quot;) smtpObj.quit() </code></pre> <p>Then finally I add the output as below.</p> <pre><code>data =get_data() data output=build_table(data,&quot;blue_light&quot;) send_mail(output) </code></pre> <p>This works fine and I am getting emails.But the issue is the text part is in a body and the html table in a attachment.</p> <p><a href="https://i.stack.imgur.com/pTyyR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pTyyR.png" alt="enter image description here" /></a></p> <p>Can someone show where I have messed up?</p> <p>Edit:</p> <pre><code>data =get_data() data Name Terminated_Date Calls Answered_Calls Total_Minutes 0 XXX 2021-12-21 522273 124018 408328.17 1 XXX 2021-12-20 508439 124895 407590.03 2 XXX 2021-12-19 456587 107899 384698.82 </code></pre>
<p>To do this you can use Python format and MIMEMultipart.</p> <p>Basically, you can do</p> <pre><code>message = MIMEMultipart() html = &quot;&quot;&quot;\ &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;p&gt;The text you want &lt;/p&gt; &lt;br&gt; {0} &lt;/body&gt; &lt;/html&gt; &quot;&quot;&quot;.format(df_test.to_html()) message.attach(MIMEText(html, &quot;HTML&quot;)) </code></pre> <p>Hope this is helpful. I am working on the same thing. Takes me a while to figure out.</p>
python|html
0
1,906,771
63,504,899
How to add log info in the Code in python in the loop
<ul> <li><p>Below is the dictionary</p> </li> <li><p>There are two ids, I need to generat</p> </li> <li><p>Once extract of completion of first id i need to get an info saying First id(100) is completed</p> </li> <li><p>Once extract of completion of second id i need to get an info saying second id(101) is completed</p> </li> </ul> <p><code>logger.info('extraction id' + str(id) + 'completed')</code></p> <p><code>logger.info('extraction id' + + str(id) + 'completed')</code></p> <p>Expected out</p> <pre><code> test = [{&quot;id&quot;:&quot;100&quot;,&quot;name&quot;:&quot;A&quot;, &quot;Business&quot;:[{&quot;id&quot;:&quot;7&quot;,&quot;name&quot;:&quot;Enterprise&quot;}, {&quot;id&quot;:&quot;8&quot;,&quot;name&quot;:&quot;Customer&quot;}], &quot;policies&quot;:[{&quot;id&quot;:&quot;332&quot;,&quot;name&quot;:&quot;Second division&quot;,&quot;parent&quot;:&quot;Marketing&quot;}, {&quot;id&quot;:&quot;3323&quot;,&quot;name&quot;:&quot;First division&quot;,&quot;parent&quot;:&quot;Marketing&quot;}]}, {&quot;id&quot;:&quot;101&quot;,&quot;name&quot;:&quot;B&quot;, &quot;Business&quot;:[{&quot;id&quot;:&quot;7&quot;,&quot;name&quot;:&quot;Enterprise&quot;}, {&quot;id&quot;:&quot;8&quot;,&quot;name&quot;:&quot;Customer&quot;}], &quot;policies&quot;:[{&quot;id&quot;:&quot;332&quot;,&quot;name&quot;:&quot;Second division&quot;,&quot;parent&quot;:&quot;Marketing&quot;}, {&quot;id&quot;:&quot;3323&quot;,&quot;name&quot;:&quot;First division&quot;,&quot;parent&quot;:&quot;Marketing&quot;}]}] </code></pre> <p>code</p> <pre><code> def do_the_thing(lst): resp = [] parents_mapper = { 'Marketing': 'level1', 'Advertising': 'level2' } for el in lst: d = { 'id': el['id'], 'name': el['name'], 'Business': [], 'level1': [], 'level2': [] } for business in el.get('Business', []): business_name = business.get('name') if business_name: d['Business'].append(business_name) for policy in el.get('policies', []): policy_parent = policy.get('parent') parent_found = parents_mapper.get(policy_parent) policy_name = policy.get('name') if parent_found and policy_name: d[parent_found].append(policy_name) resp.append(d) return resp #def lambda_handler(event,context): if __name__ == '__main__': import pprint pp = pprint.PrettyPrinter(4) pp.pprint(do_the_thing(test)) </code></pre> <p>output for 2 ids</p> <pre><code>[ { &quot;id&quot;: &quot;100&quot;, &quot;name&quot;: &quot;A&quot;, &quot;Business&quot;: [&quot;Enterprise&quot;, &quot;Customer&quot;], &quot;level1&quot;: ['Second division', 'First division'], &quot;level2&quot;: [None ] }, { &quot;id&quot;: &quot;101&quot;, &quot;name&quot;: &quot;B&quot;, &quot;Business&quot;: [&quot;Enterprise&quot;, &quot;Customer&quot;], &quot;level1&quot;: ['Second division', 'First division'], &quot;level2&quot;: [None ] } ] </code></pre> <p>First id completed then i will get <code>extraction id' 100 is completed'</code> second id completed then i will get <code>extraction id' 10</code> is completed'`</p> <p>** Expected out_one</p> <pre><code>extraction id' 100 is completed' extraction id' 101 is completed' </code></pre> <p>** Expected out_two</p> <pre><code>extraction Business' 100 is completed' extraction policy' 100 is completed' extraction level1' 100 is completed' extraction Business' 101 is completed' extraction policy' 101 is completed' extraction level1' 101 is completed' </code></pre>
<p>The following code:</p> <pre class="lang-py prettyprint-override"><code>import logging logging.basicConfig(format='%(message)s', filename='output.log',level=logging.INFO) test = [{&quot;id&quot;:&quot;100&quot;,&quot;name&quot;:&quot;A&quot;, &quot;Business&quot;:[{&quot;id&quot;:&quot;7&quot;,&quot;name&quot;:&quot;Enterprise&quot;}, {&quot;id&quot;:&quot;8&quot;,&quot;name&quot;:&quot;Customer&quot;}], &quot;policies&quot;:[{&quot;id&quot;:&quot;332&quot;,&quot;name&quot;:&quot;Second division&quot;,&quot;parent&quot;:&quot;Marketing&quot;}, {&quot;id&quot;:&quot;3323&quot;,&quot;name&quot;:&quot;First division&quot;,&quot;parent&quot;:&quot;Marketing&quot;}]}, {&quot;id&quot;:&quot;101&quot;,&quot;name&quot;:&quot;B&quot;, &quot;Business&quot;:[{&quot;id&quot;:&quot;7&quot;,&quot;name&quot;:&quot;Enterprise&quot;}, {&quot;id&quot;:&quot;8&quot;,&quot;name&quot;:&quot;Customer&quot;}], &quot;policies&quot;:[{&quot;id&quot;:&quot;332&quot;,&quot;name&quot;:&quot;Second division&quot;,&quot;parent&quot;:&quot;Marketing&quot;}, {&quot;id&quot;:&quot;3323&quot;,&quot;name&quot;:&quot;First division&quot;,&quot;parent&quot;:&quot;Marketing&quot;}]}] def do_the_thing(lst): resp = [] parents_mapper = { 'Marketing': 'level1', 'Advertising': 'level2' } for el in lst: d = { 'id': el['id'], 'name': el['name'], 'Business': [], 'level1': [], 'level2': [] } for business in el.get('Business', []): business_name = business.get('name') if business_name: d['Business'].append(business_name) if business: logging.info(f&quot;extraction Business' {d['id']} is completed'&quot;) parents = [] for policy in el.get('policies', []): policy_parent = policy.get('parent') parent_found = parents_mapper.get(policy_parent) policy_name = policy.get('name') if parent_found and policy_name: d[parent_found].append(policy_name) if parent_found not in parents: logging.info(f&quot;extraction {parent_found}' {d['id']} is completed'&quot;) parents.append(parent_found) if policy: logging.info(f&quot;extraction policy' {d['id']} is completed'&quot;) logging.info(f&quot;extraction id' {d['id']} is completed'&quot;) resp.append(d) return resp #def lambda_handler(event,context): if __name__ == '__main__': import pprint pp = pprint.PrettyPrinter(4) print(&quot;Behold Magic in Progress...&quot;) the_thing_result = do_the_thing(test) print(&quot;\nThe parsed dictionary:&quot;) pp.pprint(the_thing_result) </code></pre> <p>Has both outputs:</p> <p>Output:</p> <pre><code>Behold Magic in Progress... The parsed dictionary: [ { 'Business': ['Enterprise', 'Customer'], 'id': '100', 'level1': ['Second division', 'First division'], 'level2': [], 'name': 'A'}, { 'Business': ['Enterprise', 'Customer'], 'id': '101', 'level1': ['Second division', 'First division'], 'level2': [], 'name': 'B'}] </code></pre> <p>Log in 'output.log':</p> <pre><code>extraction Business' 100 is completed' extraction level1' 100 is completed' extraction policy' 100 is completed' extraction id' 100 is completed' extraction Business' 101 is completed' extraction level1' 101 is completed' extraction policy' 101 is completed' extraction id' 101 is completed' </code></pre>
python|logging
1
1,906,772
56,531,961
Python package called SignalFx, how to get _logger to print to stdout
<p>There is a Python package for <a href="https://www.signalfx.com/" rel="nofollow noreferrer">SignalFx</a>: <a href="https://github.com/signalfx/signalfx-python" rel="nofollow noreferrer">link to GitHub source</a></p> <p>In one of its files, it makes a <code>_logger</code> object that uses Python's <code>logging</code> library. The package has many <code>_logger.debug()</code> statements that make it useful in debugging connectivity problems.</p> <p>The code instantiates the <code>_logger</code> as a global variable, like so:</p> <p><code>_logger = logging.getLogger(__name__)</code></p> <p><a href="https://github.com/signalfx/signalfx-python/blob/master/signalfx/ingest.py#L25" rel="nofollow noreferrer">Source line in GitHub</a></p> <p>I have searched for a while, and can't figure out how to view the <code>_logger.debug()</code>'s output. How can I get the <code>_logger</code> to print to <code>stdout</code>? Or, where can I view the log statements?</p> <p>Thank you in advance!</p>
<p>You probably need to configure logging in your application which uses SignalFx. For example, this might work in your main program script:</p> <pre><code>if __name__ == '__main__': import logging # if not done already logging.basicConfig(level=logging.DEBUG, format='%(name)s %(message)s') # and then the rest of your script's code </code></pre> <p>If that doesn't produce results, you probably need to give more information about how your code that uses SignalFx is organised.</p>
python|logging
1
1,906,773
56,563,920
Yocto Bitbake Recipes for Nvidia Jetson Nano for Python whl files not on PyPi
<p>I am trying to create 2 simple Yocto Python Recipes for NVIDIA Specific PyTorch and Tensorflow Python whl packages. The target is an SD Card Image for the NVIDIA Jetson Nano produced by Yocto from the meta-tegra layer. I can successfully compile and boot an image from meta-tegra without these recipes. </p> <p>NVIDIA themselves have compiled and released the ".whl" Python packages and they are found here: <a href="https://devtalk.nvidia.com/default/topic/1048776/official-tensorflow-for-jetson-nano-/" rel="nofollow noreferrer">https://devtalk.nvidia.com/default/topic/1048776/official-tensorflow-for-jetson-nano-/</a> <a href="https://devtalk.nvidia.com/default/topic/1049071/jetson-nano/pytorch-for-jetson-nano/" rel="nofollow noreferrer">https://devtalk.nvidia.com/default/topic/1049071/jetson-nano/pytorch-for-jetson-nano/</a></p> <p>I have tried the following, but both recipes fail with various errors ( Not found license, missing setup.py , etc .. ) </p> <pre><code>SUMMARY = "NVIDIA's version of Python Torch" DESCRIPTION = "NVIDIA's version of Python Torch" HOMEPAGE = "https://nvidia.com" SECTION = "devel/python" LICENSE = "BSD-3-Clause" LIC_FILES_CHKSUM = "file://LICENSE;md5=79aa8b7bc4f781210d6b5c06d6424cb0" PR = "r0" SRCNAME = "Pytorch" SRC_URI = "https://nvidia.box.com/shared/static/j2dn48btaxosqp0zremqqm8pjelriyvs.whl" SRC_URI[md5sum] = "9ec85425a64ca266abbfdeddbe92fb18" SRC_URI[sha256sum] = "3b9b8f944962aaf550460409e9455d6d6b86083510b985306a8012d01d730b8b" S = "${WORKDIR}/${SRCNAME}-${PV}" inherit setuptools CLEANBROKEN = "1" </code></pre> <hr> <pre><code>SUMMARY = "NVIDIA's version of Python Tensorflow" DESCRIPTION = "NVIDIA's version of Python Tensorflow" HOMEPAGE = "https://nvidia.com" SECTION = "devel/python" LICENSE = "BSD-3-Clause" LIC_FILES_CHKSUM = "file://generic_BSD-3-Clause;md5=79aa8b7bc4f781210d6b5c06d6424cb0" PR = "r0" SRCNAME = "Tensorflow-gpu" SRC_URI = "https://developer.download.nvidia.com/compute/redist/jp/v42/tensorflow-gpu/tensorflow_gpu-1.13.1+nv19.5-cp36-cp36m-linux_aarch64.whl" SRC_URI[md5sum] = "ae649a62c274d19d1d096d97284ec2ee" SRC_URI[sha256sum] = "6639761eccf53cab550d4afb4c8a13dbfe1b1d8051c62e14f83199667ae42d1a" S = "${WORKDIR}/${SRCNAME}-${PV}" inherit setuptools CLEANBROKEN = "1" </code></pre> <p>I believe I have the dependencies installed in Yocto. How can I create Yocto recipes from these existing whl files? Thanks. </p>
<p>Probably (untested) something like needs to be added to your recipes:</p> <pre><code>DEPENDS += 'pip-native' do_install() { pip install ${S}/tensorflow_gpu-1.13.1+nv19.5-cp36-cp36m-linux_aarch64.whl } </code></pre> <p>but there could be more tweaks necessary.</p>
python|python-3.x|nvidia|yocto|bitbake
2
1,906,774
56,520,177
why can't my odering and list_view go together with fieldsets in django admin class
<p>I'm trying to organize my admin page. I tried to use <code>list_display</code> to show the columns, and <code>fieldsets</code> to organize the section.</p> <p>admin.py</p> <pre class="lang-py prettyprint-override"><code>class PencilManugacturerAdmin(admin.ModelAdmin): ordering = ['manufacturer_name'] list_display = ['manufacturer_name', 'id'] fieldsets = [("Manufacturer", {'fields': ["manufacturer_name"]})] </code></pre> <p>models.py</p> <pre><code>class PencilManufacturer(models.Model): manufacturer_for_type = models.ForeignKey(PencilType, default=1, verbose_name="Type", on_delete=models.SET_DEFAULT) manufacturer_name = models.CharField(max_length=100) manufacturer_description = models.CharField(max_length=300) manufacturer_img = models.ImageField(upload_to='images', blank=True) def __str__(self): return self.manufacturer_name class Meta: unique_together = ['manufacturer_name'] </code></pre> <p>I expect to have my admin page to have columns and the section when I add data. If I don't comment out the <code>fieldsets</code> (and leave the 2 others active), or the <code>ordering</code> and <code>list_display</code> (and leave the <code>fieldsets</code> active), it will show these errors:</p> <pre><code>Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 1006, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 983, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 967, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 677, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 724, in exec_module File "&lt;frozen importlib._bootstrap_external&gt;", line 860, in get_code File "&lt;frozen importlib._bootstrap_external&gt;", line 791, in source_to_code File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_removed File "&lt;string&gt;", line None TabError: inconsistent use of tabs and spaces in indentation (admin.py, line 18) Traceback (most recent call last): File "manage.py", line 21, in &lt;module&gt; main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 577, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 562, in start_django reloader.run(django_main_thread) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 280, in run self.run_loop() File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 286, in run_loop next(ticker) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 326, in tick for filepath, mtime in self.snapshot_files(): File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 342, in snapshot_files for file in self.watched_files(): File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 241, in watched_files yield from iter_all_python_module_files() File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 103, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 128, in iter_modules_and_files if not path.exists(): File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\pathlib.py", line 1339, in exists self.stat() File "C:\Users\QuanPham\AppData\Local\Programs\Python\Python37-32\lib\pathlib.py", line 1161, in stat return self._accessor.stat(self) OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '&lt;frozen importlib._bootstrap&gt;' </code></pre>
<p>There might be some special character on the <code>fieldsets</code> line, delete it and rewrite and it works.</p>
python|django|python-3.x|django-admin
0
1,906,775
56,745,633
Specifying x axis in matplotlib based on dates
<p>I am using monthly data provided from the federal reserve. However, I only want to plot 10 years worth of data, so I took the .tail() of 10 x 12 months = 120 for monthly data and 10 x 4 quarters for quarterly. My dilemma is when I plot the dataframes, it is plotting every single month on the x axis, when I only want to be having 1 tick per year per graph. </p> <pre class="lang-py prettyprint-override"><code># Load in data from .csv files only using the 10 most recent years of data, 120 for monthly 40 for quarterly federal_funds_df = pd.read_csv("data/FEDFUNDS.csv").tail(120) CPI_df = pd.read_csv("data/CPIAUCSL.csv").tail(120) unemployment_df = pd.read_csv("data/UNRATE.csv").tail(120) real_GDP_df = pd.read_csv("data/GDPC1.csv").tail(40) # Initialize the plot figure plt.figure(figsize=(4, 1)) plt.suptitle("U.S. Economic Indicators") # Effective Federal Funds Rate Plot plt.subplot(141) plt.plot(federal_funds_df.DATE, federal_funds_df.FEDFUNDS, label="Federal Funds Rate") plt.legend(loc='best') # Consumer Price Index Plot plt.subplot(142) plt.plot(CPI_df.DATE, CPI_df.CPIAUCSL, label="Consumer Price Index") plt.legend(loc='best') # Civilian Unemployment Rate Plot plt.subplot(143) plt.plot(unemployment_df.DATE, unemployment_df.UNRATE, label="Unemployment Rate") plt.legend(loc='best') # Real Gross Domestic Product Plot plt.subplot(144) plt.plot(real_GDP_df.DATE, real_GDP_df.GDPC1, label="Real GDP") plt.legend(loc='best') # Show plots fullscreen mng = plt.get_current_fig_manager() mng.window.state('zoomed') plt.show() </code></pre> <p>Sample .csv data:</p> <pre><code>DATE,FEDFUNDS 1954-07-01,0.80 1954-08-01,1.22 1954-09-01,1.06 1954-10-01,0.85 1954-11-01,0.83 1954-12-01,1.28 </code></pre>
<p>You should convert the dates to <code>date time</code> format. It would be easier if you posted a sample of your input data. But something like the following:</p> <pre><code>pd.to_datetime(df['Date'], format= '%d/%m/%y') </code></pre> <p>You can then do a <code>groupby</code> of whatever items you want to plot per year. For a more specific answer, please post some of you data. </p> <p>Also see this post : <a href="https://stackoverflow.com/questions/26646191/pandas-groupby-month-and-year">Groupby month and year</a></p>
python|pandas|matplotlib
1
1,906,776
69,793,806
Unable to over-ride "save" options while invoking firefox from selenium-python
<p>Below is the code, I'm using to invoke firefox to download an xlsx file from a website.</p> <pre><code>from selenium import webdriver options=webdriver.FirefoxOptions() dest_dir = &quot;myDir&quot; print (options.preferences) #options.set_preference('profile', profile_path) #options.set_preference(&quot;browser.download.useDownloadDir&quot;,True) options.set_preference(&quot;browser.download.folderList&quot;,2) options.set_preference(&quot;browser.download.dir&quot;,dest_dir) options.set_preference(&quot;browser.download.manager.showWhenStarting&quot;,False) options.set_preference(&quot;browser.helperApps.neverAsk.saveToDisk&quot;,&quot;application/xlsx/xls&quot;) print (options.preferences) driver = webdriver.Firefox(options=options) </code></pre> <p>Even with those options, every time I invoke firefox, it requests below questions.</p> <p><a href="https://i.stack.imgur.com/WwgLL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WwgLL.png" alt="enter image description here" /></a></p> <p><strong>EDIT:</strong> After changing <code>options.set_preference(&quot;browser.helperApps.neverAsk.saveToDisk&quot;,&quot;application/xlsx/xls&quot;)</code> to <code>options.set_preference(&quot;browser.helperApps.neverAsk.saveToDisk&quot;,&quot;application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&quot;)</code> issue is resolved. So, I was providing the wrong MIME type for an xlsx file. Referred to <a href="https://stackoverflow.com/questions/4212861/what-is-a-correct-mime-type-for-docx-pptx-etc">What is a correct MIME type for .docx, .pptx, etc.?</a> for getting the correct type.</p> <p>Thanks a lot @cruisepandey and @djmonki for your help</p>
<p>I generally invokes with these many preferences in my project, and they work seamlessly.</p> <p><strong>Code :</strong></p> <pre><code>options.set_preference(&quot;browser.download.panel.shown&quot;, False) options.set_preference(&quot;browser.helperApps.neverAsk.openFile&quot;,&quot;text/csv,application/vnd.ms-excel&quot;) options.set_preference(&quot;browser.helperApps.neverAsk.saveToDisk&quot;, &quot;application/msword, application/csv, application/ris, text/csv, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream&quot;); options.set_preference(&quot;browser.download.manager.showWhenStarting&quot;, False); options.set_preference(&quot;browser.download.manager.alertOnEXEOpen&quot;, False); options.set_preference(&quot;browser.download.manager.focusWhenStarting&quot;, False); options.set_preference(&quot;browser.download.folderList&quot;, 2); options.set_preference(&quot;browser.download.useDownloadDir&quot;, True); options.set_preference(&quot;browser.helperApps.alwaysAsk.force&quot;, False); options.set_preference(&quot;browser.download.manager.alertOnEXEOpen&quot;, False); options.set_preference(&quot;browser.download.manager.closeWhenDone&quot;, True); options.set_preference(&quot;browser.download.manager.showAlertOnComplete&quot;, False); options.set_preference(&quot;browser.download.manager.useWindow&quot;, False); options.set_preference(&quot;services.sync.prefs.sync.browser.download.manager.showWhenStarting&quot;, False); options.set_preference(&quot;pdfjs.disabled&quot;, True); options.set_preference(&quot;browser.download.dir&quot;, &quot;C:\\Users\\userid\\Desktop\\Automation&quot;) </code></pre>
python-3.x|selenium|selenium-webdriver|firefox
1
1,906,777
60,831,669
Code "crashing" in await ClientResponse.text()
<p>I'm trying to create an api, and when i try to convert the aiohttp.ClientResponse to text, my code never finishes (never go to the next line) and it raises TimeoutError, I tried to do this in terminal (with the same site), and it works, can someone help me?</p> <p>Here's my current code:</p> <pre class="lang-py prettyprint-override"><code>async with aiohttp.ClientSession() as session: # _base="https://frankerfacez.com" # query="monka" # sort="count-desc" r = await session.get(f'{_base}/emoticons/wall?q={query}&amp;sort={sort}') txt = await r.text() </code></pre> <p>And it raises this:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 612, in run_until_complete return future.result() File "C:\Users\Kaigo\Desktop\FFZ Api\ffz\__init__.py", line 112, in search txt = await r.text() File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client_reqrep.py", line 1009, in text await self.read() File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client_reqrep.py", line 973, in read self._body = await self.content.read() File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\streams.py", line 358, in read block = await self.readany() File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\streams.py", line 380, in readany await self._wait('readany') File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\streams.py", line 296, in _wait await waiter File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\helpers.py", line 596, in __exit__ raise asyncio.TimeoutError from None asyncio.exceptions.TimeoutError </code></pre>
<p>you're trying to read from the request after clossing the session. Move the <code>await r.text()</code> to inside the <code>async with</code> block:</p> <pre><code>async with aiohttp.ClientSession() as session: url = f'{_base}/emoticons/wall?q={query}&amp;sort={sort}' async with session.get(url) as r: txt = await r.text() </code></pre>
python|python-asyncio|aiohttp
2
1,906,778
61,177,938
Why my pygame code is crashing with "RecursionError: maximum recursion depth exceeded while calling a Python object"?
<p>I want to put a system of collide on my pygame's rpg and my code is crashing with "RecursionError: maximum recursion depth exceeded while calling a Python object". I tried many things but the error always appears.</p> <p>My code: </p> <pre><code>import pygame from pygame.locals import * from player import * class Camera: def __init__(self, widht, height): self.rect = pygame.Rect(0, 0, widht, height) self.widht = widht self.height = height self.center = list(self.rect.center) self.x = self.center[0] self.y = self.center[1] def apply(self, entity): return entity.move(self.rect.topleft) def update(self, target): y = -target.rect.y + int(769 / 2) x = -target.rect.x + int(1024 / 2) self.rect = pygame.Rect(x, y, self.widht, self.height) class Level(pygame.sprite.Sprite): def __init__(self): self.structure = 0 self.all_blocks = pygame.sprite.Group() def generer(self): with open("niveau.txt", "r") as fichier: structure_niveau = [] for ligne in fichier: ligne_niveau = [] for sprite in ligne: if sprite != '\n': ligne_niveau.append(sprite) structure_niveau.append(ligne_niveau) self.structure = structure_niveau def afficher(self, fenetre, x, y, camX, camY, playerX, playerY): tailleSprite = 64 self.all_blocks.empty() #Camera.__init__(self, x, y) cam = Camera(1024, 768) grass = pygame.image.load("assets/bloc/grass.png").convert_alpha() tree = pygame.image.load("assets/bloc/tree_grass.png").convert_alpha() no_texture = pygame.image.load("assets/bloc/no_texture.png").convert_alpha() num_ligne = 0 for ligne in self.structure: num_case = 0 for sprite in ligne: x = num_case * tailleSprite + camX y = num_ligne * tailleSprite + camY sprite_rect = pygame.Rect(x, y, 64, 64) screenRect = pygame.Rect(x, y, 1088, 836) aroundPlayer = pygame.Rect(playerX, playerY, playerX + 128, playerY + 128) if sprite == 'G': if screenRect.contains(sprite_rect): fenetre.blit(grass, (x, y)) if aroundPlayer.contains(sprite_rect): self.all_blocks.add(sprite) elif sprite == 'T': if screenRect.contains(sprite_rect): fenetre.blit(tree, (x, y)) #self.all_blocks.add(sprite) #print(self.x, self.y) else: if screenRect.contains(sprite_rect): fenetre.blit(no_texture, (x, y)) #print(x, y) num_case += 1 num_ligne += 1 </code></pre> <p>and main.py: </p> <pre><code>import pygame from game import Game from level import * pygame.init() lvl = Level() WIDHT = 768 HEIGHT = 1024 screen = pygame.display.set_mode((1024, 768)) screen_rect = pygame.Rect(0, 0, HEIGHT, WIDHT) pygame.display.set_caption("RPG") game = Game() cam = Camera(1024, 768) running = True lvl.generer() print(game.player.rect) print(screen_rect) clock = pygame.time.Clock() lvl.afficher(screen, 0, 0, 0, 0, game.player.rect.x, game.player.rect.y) camPos = 0 while running: lvl.afficher(screen, 0, 0, camPos, 0, game.player.rect.x, game.player.rect.y) cam.apply(game.player.rect) cam.update(game.player) #print(cam.rect.topleft) if game.pressed.get(pygame.K_RIGHT): game.player.move_right() #print(game.player.rect.x) if not screen_rect.contains(game.player.rect): game.player.rect.x -= HEIGHT -60 camPos += -HEIGHT elif game.pressed.get(pygame.K_LEFT): game.player.move_left() #print(game.player.rect.x) if not screen_rect.contains(game.player.rect): game.player.rect.x += HEIGHT - 60 camPos += HEIGHT elif game.pressed.get(pygame.K_DOWN): game.player.move_down() #print(game.player.rect.y) if not screen_rect.contains(game.player.rect): game.player.rect.y -= WIDHT - 80 elif game.pressed.get(pygame.K_UP): game.player.move_up() #print(game.player.rect.y) if not screen_rect.contains(game.player.rect): game.player.rect.y += WIDHT - 80 #print(cam.rect.x, cam.rect.y) #print(cam.rect) screen.blit(game.player.image, game.player.rect) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() elif event.type == pygame.KEYDOWN: game.pressed[event.key] = True elif event.type == pygame.KEYUP: game.pressed[event.key] = False </code></pre>
<p>Try one of the following option which will help you to get rid of the error</p> <ol> <li>try to change the algorithm from recursive to iterative</li> <li>you can change the recursion limit with <code>sys.setrecursionlimit(n)</code> - in python recursion is limited to 999 calls.</li> </ol>
python|pygame|sprite|rpg
0
1,906,779
69,011,922
Unique identifier of a video file
<p>Use case:<br /> I have a youtube playlist.<br /> I want to sync this playlist to my local computer.</p> <pre><code>Algorithm: for each video in playlist: if not exist an file name video[&quot;videoID&quot;].mp4 in directory &quot;C:\Users\username\Desktop&quot;: download the video name video[&quot;videoID&quot;].mp4 in directory &quot;C:\Users\username\Desktop&quot; </code></pre> <p>but it seems name is not a very good identifier. Reason 1: filename could be changed accidentally. Reason 2: some video ID have special character not accepted as file name in window10.</p> <p>Is there any identifier of a video file that is guarantee not to change once initialized or once created?</p>
<p>There is no such identifier by default.<br /> You could either use a hash of the file, which might slow down the validation by a lot if you have many large files, or you could set custom metadata for the videos(e.g. using ffmpeg) and keep a database for which uuids translate to which urls.</p>
python|file|operating-system|filesystems
1
1,906,780
72,804,181
How do i apply a xticks rotation on all my subplots?
<p>I am kind of stuck with this, I searched on google for an answer but I can not find it.</p> <p>I would like to turn my <code>xticks</code> 45 degrees of my subplot. I know how to do it for a normal plot:</p> <pre><code>plt.xticks(rotation = 45) </code></pre> <p>But when I put this in my plot script nothing happens. I would really like to know how I can apply this to all my subplots at the same time.</p> <p>This is my code:</p> <pre><code>plt.figure() fig, axs = plt.subplots(1, 3, sharey=True, tight_layout=True) axs[0].set_title(&quot;Classic&quot;) axs[1].set_title(&quot;Theta&quot;) axs[2].set_title(&quot;Vector&quot;) axs[0].plot(df.time,df.classic, label = 'Classic', color = 'blue') axs[1].plot(df.time,df.theta, label = 'Theta', color = 'green') axs[2].plot(df.time,df.vector, label = 'Vector', color = 'red') plt.xticks(rotation = 45) plt.suptitle('Core computations',fontsize=20) plt.legend() plt.show() </code></pre>
<p>Have you tried this?</p> <pre class="lang-py prettyprint-override"><code>ax = plt.gca() ax.tick_params(axis='x', labelrotation = 45) </code></pre> <p>For all subplots, you can also try:</p> <pre class="lang-py prettyprint-override"><code>for ax in fig.axes: matplotlib.pyplot.sca(ax) plt.xticks(rotation=90) </code></pre>
python|matplotlib|subplot|xticks
1
1,906,781
72,690,836
What exactly happens when i don't use "self" key while initialising a variable like m1 inside a class method. m1 is local,object or class variable?
<pre><code>class Student: def __init__(self,m1,m2): m1=m1 m2=m2 print(m1+m2) s1=Student(10,20) s2=Student(20,30) print(Student.m1) </code></pre> <p>#i have just started the oops concepts so am a little confused now. when writing &quot;print(Student.m1) or print(s1.m1)&quot; am getting compile time error as &quot;AttributeError: type object 'Student' has no attribute 'm1'&quot;.</p>
<p>If you don't set the values as properties (via <code>self</code>), the names (<code>m1</code>, <code>m2</code>..) are lost when they go out of scope (when <code>__init__(...)</code> returns)</p> <p>This is practically the same as using names inside a function - they only exist in that scope unless put somewhere else!</p>
python|oop
0
1,906,782
68,397,643
How to generate training data in XOR gate based on Neural Network
<p>how to modify it to achieve simpler logical AND and logical OR(linear)? How to generate training data in the XOR project? Why is this kind of data called toy data?</p>
<p>That means play with data like small toy/ Well, try to include in the above of your code a TOY library, and here you go you'll get a toy structure</p>
node.js|tensorflow|tensorflow-datasets|xor
0
1,906,783
59,063,417
Transform flair language model tensors for viewing in TensorBoard Projector
<p>I want to convert "vectors,"</p> <pre><code>vectors = [token.embedding for token in sentence] print(type(vectors)) &lt;class 'list'&gt; print(vectors) [tensor([ 0.0077, -0.0227, -0.0004, ..., 0.1377, -0.0003, 0.0028]), ... tensor([ 0.0003, -0.0461, 0.0043, ..., -0.0126, -0.0004, 0.0142])] </code></pre> <p>to</p> <pre><code>0.0077 -0.0227 -0.0004 ... 0.1377 -0.0003 0.0028 ... 0.0003 -0.0461 0.0043 ... -0.0126 -0.0004 0.0142 </code></pre> <p>and write that to a TSV.</p> <p>Aside: those embeddings are from <code>flair</code> (<a href="https://github.com/zalandoresearch/flair" rel="nofollow noreferrer">https://github.com/zalandoresearch/flair</a>): how can I get the full output, not the <code>-0.0004 ... 0.1377</code> abbreviated output?</p>
<p>OK, I dug around ...</p> <ol> <li><p>It turns out those are PyTorch tensors (Flair uses PyTorch). For a simple conversion to NumPy arrays (per the PyTorch docs at <a href="https://pytorch.org/docs/stable/tensors.html#torch.Tensor.tolist" rel="nofollow noreferrer">https://pytorch.org/docs/stable/tensors.html#torch.Tensor.tolist</a> and <a href="https://stackoverflow.com/questions/53903373/convert-pytorch-tensor-to-python-list">this StackOverFlow answer</a> use <code>tolist()</code>, a PyTorch method.</p> <pre><code>&gt;&gt;&gt; import torch &gt;&gt;&gt; a = torch.randn(2, 2) &gt;&gt;&gt; print(a) tensor([[-2.1693, 0.7698], [ 0.0497, 0.8462]]) &gt;&gt;&gt; a.tolist() [[-2.1692984104156494, 0.7698001265525818], [0.049718063324689865, 0.8462421298027039]] </code></pre></li> </ol> <hr> <ol start="2"> <li><p>Per my original question, here's how to convert those data to plain text and write them to TSV files.</p> <pre><code>from flair.embeddings import FlairEmbeddings, Sentence from flair.models import SequenceTagger from flair.embeddings import StackedEmbeddings embeddings_f = FlairEmbeddings('pubmed-forward') embeddings_b = FlairEmbeddings('pubmed-backward') sentence = Sentence('The RAS-MAPK signalling cascade serves as a central node in transducing signals from membrane receptors to the nucleus.') tagger = SequenceTagger.load('ner') tagger.predict(sentence) embeddings_f.embed(sentence) stacked_embeddings = StackedEmbeddings([ embeddings_f, embeddings_b, ]) stacked_embeddings.embed(sentence) # for token in sentence: # print(token) # print(token.embedding) # print(token.embedding.shape) tokens = [token for token in sentence] print(tokens) ''' [Token: 1 The, Token: 2 RAS-MAPK, Token: 3 signalling, Token: 4 cascade, Token: 5 serves, Token: 6 as, Token: 7 a, Token: 8 central, Token: 9 node, Token: 10 in, Token: 11 transducing, Token: 12 signals, Token: 13 from, Token: 14 membrane, Token: 15 receptors, Token: 16 to, Token: 17 the, Token: 18 nucleus.] ''' ## https://www.geeksforgeeks.org/python-string-split/ tokens = [str(token).split()[2] for token in sentence] print(tokens) ''' ['The', 'RAS-MAPK', 'signalling', 'cascade', 'serves', 'as', 'a', 'central', 'node', 'in', 'transducing', 'signals', 'from', 'membrane', 'receptors', 'to', 'the', 'nucleus.'] ''' tensors = [token.embedding for token in sentence] print(tensors) ''' [tensor([ 0.0077, -0.0227, -0.0004, ..., 0.1377, -0.0003, 0.0028]), tensor([-0.0007, -0.1601, -0.0274, ..., 0.1982, 0.0013, 0.0042]), tensor([ 4.2534e-03, -3.1018e-01, -3.9660e-01, ..., 5.9336e-02, -9.4445e-05, 1.0025e-02]), tensor([ 0.0026, -0.0087, -0.1398, ..., -0.0037, 0.0012, 0.0274]), tensor([-0.0005, -0.0164, -0.0233, ..., -0.0013, 0.0039, 0.0004]), tensor([ 3.8261e-03, -7.6409e-02, -1.8632e-02, ..., -2.8906e-03, -4.4556e-04, 5.6909e-05]), tensor([ 0.0035, -0.0207, 0.1700, ..., -0.0193, 0.0017, 0.0006]), tensor([ 0.0159, -0.4097, -0.0489, ..., 0.0743, 0.0005, 0.0012]), tensor([ 9.7725e-03, -3.3817e-01, -2.2848e-02, ..., -6.6284e-02, 2.3646e-04, 1.0505e-02]), tensor([ 0.0219, -0.0677, -0.0154, ..., 0.0102, 0.0066, 0.0016]), tensor([ 0.0092, -0.0431, -0.0450, ..., 0.0060, 0.0002, 0.0005]), tensor([ 0.0047, -0.2732, -0.0408, ..., 0.0136, 0.0005, 0.0072]), tensor([ 0.0072, -0.0173, -0.0149, ..., -0.0013, -0.0004, 0.0056]), tensor([ 0.0086, -0.1151, -0.0629, ..., 0.0043, 0.0050, 0.0016]), tensor([ 7.6452e-03, -2.3825e-01, -1.5683e-02, ..., -5.4974e-04, -1.4646e-04, 6.6120e-03]), tensor([ 0.0038, -0.0354, -0.1337, ..., 0.0060, -0.0004, 0.0102]), tensor([ 0.0186, -0.0151, -0.0641, ..., 0.0188, 0.0391, 0.0069]), tensor([ 0.0003, -0.0461, 0.0043, ..., -0.0126, -0.0004, 0.0142])] ''' # ---------------------------------------- ## Write those data to TSV files. ## https://stackoverflow.com/a/29896136/1904943 import csv metadata_f = 'metadata.tsv' tensors_f = 'tensors.tsv' with open(metadata_f, 'w', encoding='utf8', newline='') as tsv_file: tsv_writer = csv.writer(tsv_file, delimiter='\t', lineterminator='\n') for token in tokens: ## Assign to a dummy variable ( _ ) to suppress character counts; ## if I use (token), rather than ([token]), I get spaces between all characters: _ = tsv_writer.writerow([token]) ## metadata.tsv : ''' The RAS-MAPK signalling cascade serves as a central node in transducing signals from membrane receptors to the nucleus. ''' with open(metadata_f, 'w', encoding='utf8', newline='') as tsv_file: tsv_writer = csv.writer(tsv_file, delimiter='\t', lineterminator='\n') _ = tsv_writer.writerow(tokens) ## metadata.tsv : ''' The RAS-MAPK signalling cascade serves as a central node in transducing signals from membrane receptors to the nucleus. ''' tensors = [token.embedding for token in sentence] print(tensors) ''' [tensor([ 0.0077, -0.0227, -0.0004, ..., 0.1377, -0.0003, 0.0028]), tensor([-0.0007, -0.1601, -0.0274, ..., 0.1982, 0.0013, 0.0042]), tensor([ 4.2534e-03, -3.1018e-01, -3.9660e-01, ..., 5.9336e-02, -9.4445e-05, 1.0025e-02]), tensor([ 0.0026, -0.0087, -0.1398, ..., -0.0037, 0.0012, 0.0274]), tensor([-0.0005, -0.0164, -0.0233, ..., -0.0013, 0.0039, 0.0004]), tensor([ 3.8261e-03, -7.6409e-02, -1.8632e-02, ..., -2.8906e-03, -4.4556e-04, 5.6909e-05]), tensor([ 0.0035, -0.0207, 0.1700, ..., -0.0193, 0.0017, 0.0006]), tensor([ 0.0159, -0.4097, -0.0489, ..., 0.0743, 0.0005, 0.0012]), tensor([ 9.7725e-03, -3.3817e-01, -2.2848e-02, ..., -6.6284e-02, 2.3646e-04, 1.0505e-02]), tensor([ 0.0219, -0.0677, -0.0154, ..., 0.0102, 0.0066, 0.0016]), tensor([ 0.0092, -0.0431, -0.0450, ..., 0.0060, 0.0002, 0.0005]), tensor([ 0.0047, -0.2732, -0.0408, ..., 0.0136, 0.0005, 0.0072]), tensor([ 0.0072, -0.0173, -0.0149, ..., -0.0013, -0.0004, 0.0056]), tensor([ 0.0086, -0.1151, -0.0629, ..., 0.0043, 0.0050, 0.0016]), tensor([ 7.6452e-03, -2.3825e-01, -1.5683e-02, ..., -5.4974e-04, -1.4646e-04, 6.6120e-03]), tensor([ 0.0038, -0.0354, -0.1337, ..., 0.0060, -0.0004, 0.0102]), tensor([ 0.0186, -0.0151, -0.0641, ..., 0.0188, 0.0391, 0.0069]), tensor([ 0.0003, -0.0461, 0.0043, ..., -0.0126, -0.0004, 0.0142])] ''' with open(tensors_f, 'w', encoding='utf8', newline='') as tsv_file: tsv_writer = csv.writer(tsv_file, delimiter='\t', lineterminator='\n') for token in sentence: embedding = token.embedding _ = tsv_writer.writerow(embedding.tolist()) ## tensors.tsv (18 lines: one embedding per token in metadata.tsv): ## note: enormous output, even for this simple sentence. ''' 0.007691788021475077 -0.02268664352595806 -0.0004340760060586035 ... ''' </code></pre></li> </ol> <hr> <ol start="3"> <li><p>Last, my intention for all of that was to load contextual language embeddings (Flair, etc.) into TensorFlow's <a href="https://projector.tensorflow.org/" rel="nofollow noreferrer">Embedding Projector</a>. It turns out all I needed to to was to convert (here, Flair data) to NumPy arrays, and load them into a TensorFlow TensorBoard instance (no need for TSV files!).</p> <p>I describe that in detail in my blog post, here: <a href="https://persagen.com/2019/11/28/tensorboard_projector.html" rel="nofollow noreferrer">Visualizing Language Model Tensors (Embeddings) in TensorFlow's TensorBoard [TensorBoard Projector: PCA; t-SNE; ...]</a>.</p></li> </ol>
python|numpy|pytorch|tensorboard|flair
1
1,906,784
59,390,692
API Gateway Malformed Lambda proxy response in python
<p>I created a lambda function with serverless. I tested my lambda function with lambda console and it worked fine. But I get Endpoint response body before transformations: null and Execution failed due to configuration error: Malformed Lambda proxy response when I tried to call my API endpoint for this function. </p> <p>This is my serverless.yml</p> <pre><code>org: orgname app: appname service: report provider: name: aws runtime: python3.7 stage: ${opt:stage,'dev'} timeout: 120 role: arn:aws:iam::xxxxxxxx:role/rolexxxx plugins: - serverless-python-requirements functions: reportgen: handler: xlsx_generator.main events: - http: path: main method: get cors: true custom: pythonRequirements: dockerizePip: true package: exclude: - node_modules/** - venv/** </code></pre> <p>and this is snippet from xlsx_generator.py:</p> <pre><code>def main(event, context): log.basicConfig(level=log.DEBUG) if "queryStringParameters" in event.keys() and 'start_date' in event["queryStringParameters"].keys(): if "end_date" in event["queryStringParameters"].keys(): end_date = event["queryStringParameters"]['end_date'] else: end_date = event["queryStringParameters"]['start_date'] try: generate(event["queryStringParameters"]['start_date'], end_date, event["queryStringParameters"]['output']) except (ClientError, Exception, RuntimeError) as e: raise e else: body = json.dumps({ "message": "Missing parameter", "event": event }) return { "isBase64Encoded": False, "statusCode": 400, "headers": { "Access-Control-Allow-Origin": '*' }, "body": body } </code></pre> <p>and I called my endpoint with addition for query string parameter: <code>?start_date=2019-11-1&amp;end_date=2019-11-30&amp;output=reporthugree.xlsx</code>.</p> <p>I have no idea why I still got Malformed Lambda proxy response when my function already returned response with the format from <a href="https://aws.amazon.com/premiumsupport/knowledge-center/malformed-502-api-gateway/" rel="nofollow noreferrer">here</a>. I am new to this whole AWS matter, please explain to me if there is something wrong.</p>
<p>it turns out my handler function, the main function, does not contain a return value from the generate function so the lambda gives null value as response. This null response will cause a malform lambda proxy response when the integration proxy attempts to transform it to API Gateway response. When you activate Lambda proxy integration make sure your function <strong>always return</strong> a valid response format according to <a href="https://aws.amazon.com/premiumsupport/knowledge-center/malformed-502-api-gateway/" rel="nofollow noreferrer">this</a>. it will save your time.</p> <p>I found out that my question is kind of duplicate from <a href="https://stackoverflow.com/questions/54111754/aws-lambda-and-api-gateway-response-integration-issue">this</a></p>
amazon-web-services|aws-lambda|aws-api-gateway|python-3.7|aws-serverless
0
1,906,785
62,390,981
I can't make multiple statement to check two statement
<p>I am making a code in python to make password and save in the text file, if the user enters the same password in the file, the error code will appear. The problem is that although I made a two statement to check the password is valid and there is no same password in the text file, the statement of the one that will check text file to find same file. Can you tell me where I get mistake?</p> <pre><code>def InputString(): String = str(input("Enter your password. :")) return String def CheckPassword(Password): ##I declared "Index","Upper","Lower","Digit" and "Other" as Integer. ##In python, there is no data type for ##"char", so We use string instead. ##I use "variable" as boolean for checking password. Upper = 0 Lower = 0 Digit = 0 Other = 0 variable = False for index in range(len(Password)): NextChar = (Password[index:index+1]) if NextChar &gt;= "A" and NextChar &lt;= "Z": Upper = Upper + 1 elif NextChar &gt;= "a" and NextChar &lt;= "z": Lower = Lower + 1 elif NextChar &gt;= "0" and NextChar &lt;= "9": Digit = Digit + 1 else : Other = Other + 1 if Upper &gt; 1 and Lower &gt;= 5 and (Digit - Other) &gt; 0: variable = True else : variable = False return variable def CheckThrough (Password): FileP = open("Password.txt","r") if FileP.mode == 'r': contents = FileP.read() if contents == Password: usable = False else : usable = True FileP.close() return usable ###The main programs starts here### print("Enter the password.") print("You must add at least 1 upper character.") print("5 lower character") print("and the difference between numeric character and symbols must be more than 1.") variable = False usable = False while variable == False and usable == False: Password = InputString() variable = CheckPassword(Password) if variable == True: usable = CheckThrough(Password) if usable == True: print("You can use the password.") elif usable ==False : print("The password you entered is already used.") else : print("The error is ocuured.") else : print("You can't use this password, try again.") print("Your password is",Password) FileP = open("Password.txt","a+") FileP.write(Password) FileP.write("\n") FileP.close() </code></pre>
<p>you need to add <code>.strip()</code> so it has no spaces e.g <code>String = str(input("Enter your password. :").strip())</code>. When you enter in the password there's a space but that doesn't get saved to the file thus it always reads it as a new password.</p> <p>my input = Enter your password. :Kingdom1hearTs</p> <p>The input into the program = " Kingdom1hearTs" </p> <p>(used print to see what was being entered into the system)</p> <p>and the <code>if contents == Password:</code> needs to be <code>if Password in contents:</code>otherwise your seeing if Password is the same as the whole txt file.</p> <pre><code>NextChar = (Password[index:index+1]) if NextChar &gt;= "A" and NextChar &lt;= "Z": Upper = Upper + 1 elif NextChar &gt;= "a" and NextChar &lt;= "z": #had the wrong indentation Lower = Lower + 1 elif NextChar &gt;= "0" and NextChar &lt;= "9": Digit = Digit + 1 else : Other = Other + 1 </code></pre>
python-3.x|python-3.7
0
1,906,786
73,371,880
find if point intersect in graph without sorting?
<p>I have a list of items that represents X,Y on a graph (all starts at point (0,0). example:</p> <pre><code>1. [(0,0),(0,1),(0,2),(1,2),(2,2)] 2. [(0,0),(0,1),(0,2),(1,2),(2,2),(2,1),(1,1),(0,1)] </code></pre> <p>item 2 is invalid because it intersect at point (0,1).</p> <p>in order to find if intersection exists, I sort (nlogn) the list and iterate to find if 2 points are the same.</p> <pre><code>def is_intersect(points ): # points [(0,0)...] points.sort() for m,u in zip(points,points[1:]): if m==u: return True return False </code></pre> <p>My question: is there a better way to find an intersection than the above algorithm (with space complexity O(1) no extra set or hashset)?</p>
<p>There is an algorithm in O(n) time complexity and O(1) in memory<br><br> However it is based on the fact that the array elements are numbers, so you would need to create a function that transforms the pairs into numbers.<br> <br> If the numbers are small and you know they are in a range [0,10^n). You can define the following bijection: <code>f(x,y) = x*10^n+y</code> <br> From there use one of the approaches in <a href="https://www.geeksforgeeks.org/find-duplicates-in-on-time-and-constant-extra-space/" rel="nofollow noreferrer">this post</a> and adapt it to your needs.</p> <p>Example:</p> <pre class="lang-py prettyprint-override"><code>def duplicate(lst): return 12 #implementation of the algorithm in the post def is_intersect(points): n = 1 #if you don't know what n is you can find it using the log_10 of all the numbers in the list and round up the maximum value n = pow(10,n) for i in range(len(points)): points[i] = points[i][0]*n+points[i][1] ans = duplicate(points) if (ans is None): return None else: return (ans//n,ans%10) </code></pre>
python|algorithm|sorting|optimization
1
1,906,787
31,546,490
Convert float NumPy array to big endian
<p>I wrote a script and in the end I need to convert this array which is in type float64 to big endian int (>2i):</p> <pre><code>[[ 0.92702157 1.03092008 0.9072934 ..., 0.71617331 1.02524888 1.07284994] [ 0.99573712 0.96416766 0.9230931 ..., 0.66935196 0.64930711 0.5357821 ] [ 0.98846306 1.03608056 0.79976885 ..., 0.69383804 0.62434976 0.88219911] ..., [ 0.91196013 0.87880101 0.97145563 ..., 0.79110817 1.19651477 0.98244941] [ 1.0129829 0.81045263 0.95434107 ..., 0.99752385 1.08271169 1.12872492] [ 0.94037117 0.81365084 0.94384051 ..., 0.82754351 1.03742172 1.]] </code></pre> <p>How I can do that?</p> <p>Here is whole script</p> <pre><code>import numpy as np import pyfits from matplotlib import pyplot as plt import glob import os import re from struct import unpack,pack global numbers numbers=re.compile(r'(\d+)') def numericalSort(value): parts = numbers.split(value) parts[1::2] = map(int, parts[1::2]) return parts dark=sorted(glob.glob(' *.fits'),key=numericalSort) flat=sorted(glob.glob('/ *.fits'),key=numericalSort) img=sorted(glob.glob('/ *.fits'),key=numericalSort) #dark sumd0 = pyfits.open(dark[0]) sumdd=sumd0[0].data sumdd = sumdd.astype(float,copy=False) for i in range(1,len(dark)): sumdi=pyfits.open(dark[i]) sumdi=sumdi[0].data sumdd=sumdd+sumdi.astype(float, copy=False) dd=sumdd/len(dark) #flat sumf0 = pyfits.open(flat[0]) sumff=sumf0[0].data sumff = sumff.astype(float, copy=False) for i in range(1,len(flat)): sumfi=pyfits.open(flat[i]) sumfi=sumfi[0].data sumff=sumff+sumfi.astype(float,copy=False) ff=sumff/len(flat) df=(ff-dd) maxx=np.max(df) df=np.clip(df,1,maxx) for n in range(len(img)): im=pyfits.open(img[n]) imgg=im[0].data header=im[0].header imgg=imgg.astype(float,copy=False) x,y=im[0].shape m=np.max(imgg) imgg=np.clip((imgg-dd),1,m) imgg=imgg/df imgg=np.clip(imgg,0.5,1.5) #print imgg.dtype #imgg=imgg[200:950,150:1250] #imgg=imgg[::-1,:y] hdu = pyfits.PrimaryHDU(imgg,header) hdulist = pyfits.HDUList([hdu]) hdulist.writeto('/c'+img[n][48:]) plt.imshow(imgg,cmap=plt.cm.Greys_r) #plt.savefig('/+'.png') plt.show() </code></pre> <p>On last 9 line I need convert array imgg from float64 to >i2</p>
<pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; big_end = bytes(chr(0) + chr(1) + chr(3) + chr(2), 'utf-8') &gt;&gt;&gt; np.ndarray(shape=(2,),dtype='&gt;i2', buffer=big_end) array([ 1, 770], dtype=int16) </code></pre> <p>see also: <a href="http://docs.scipy.org/doc/numpy/user/basics.byteswapping.html" rel="nofollow">Byte-swapping</a></p>
python|python-2.7|numpy
2
1,906,788
31,539,018
Date Range List filter for foreign key Django admin
<p>I have a model like this</p> <pre><code>class BaseRequest(models.Model): created = models.DateTimeField(auto_now_add=True, editable=False) modified = models.DateTimeField(auto_now=True, editable=False) price_quoted = models.DecimalField(max_digits=10, decimal_places=2,null=True, blank=True) class RequestLeg(models.Model): created = models.DateTimeField(auto_now_add=True, editable=False) modified = models.DateTimeField(auto_now=True, editable=False) depart_date = models.DateField() num_seats = models.IntegerField() class Request(BaseRequest): owner = models.ForeignKey(User, null=True, blank=True) name = models.CharField(max_length=30, null=True, blank=True) email = models.EmailField() phone = models.CharField(max_length=30, null=True, blank=True) legs = models.ManyToManyField(RequestLeg) </code></pre> <p>and admin for above Request model is </p> <pre><code>class RequestAdmin(NoDeletionsAdmin): list_display=['id', 'created', 'name', 'depart_date'] def depart_date(self, obj): try: return min([leg.depart_date for leg in obj.legs.all()]) except ValueError, e: return None </code></pre> <p>I want Daterangelist filter for depart_date in RequestAdmin ? <img src="https://i.stack.imgur.com/lMns7.png" alt="enter image description here"></p>
<p>Filter it using <a href="https://docs.djangoproject.com/en/1.8/topics/db/queries/#field-lookups" rel="nofollow">field lookups</a>, just like any other relationship:</p> <pre><code>Request.objects.filter(legs__created__range=["2015-01-01", "2016-01-31"]) </code></pre> <hr> <p>If filtering over a field from parent model is required, I suggest reading <a href="https://docs.djangoproject.com/en/1.8/topics/db/models/#multi-table-inheritance" rel="nofollow">Multi-table inheritance</a>.</p> <p>A TL;DR would be that Django implicitly creates a <code>OneToOneField</code> on the child model and we can filter over it just like any other field, e.g:</p> <pre><code>BaseRequest.objects.filter(request__depart_date__range=[...]) </code></pre> <p>or</p> <pre><code>Request.objects.filter(baserequest_ptr__created__range=[...]) </code></pre> <p>However, the second query is usually better written like so, letting Django to handle the internals:</p> <pre><code>Request.objects.filter(created__range=[...]) </code></pre>
python|django|django-admin
2
1,906,789
31,533,199
How to produce the following images (gabor patches)
<p>I am trying to create four gabor patches, very similar to those below. I don't need them to be identical to the pictures below, but similar.</p> <p>Despite a bit of tinkering, I have been unable to reproduce these images... I believe they were created in MATLAB originally. I don't have access to the original MATLAB code.</p> <p>I have the following code in python (2.7.10):</p> <pre><code>import numpy as np from scipy.misc import toimage # One can also use matplotlib* data = gabor_fn(sigma = ???, theta = 0, Lambda = ???, psi = ???, gamma = ???) toimage(data).show() </code></pre> <p>*<a href="http://matplotlib.org/users/image_tutorial.html" rel="nofollow noreferrer">graphing a numpy array with matplotlib</a></p> <p>gabor_fn, from <a href="https://en.wikipedia.org/wiki/Gabor_filter#Example_implementation" rel="nofollow noreferrer">here</a>, is defined below:</p> <pre><code>def gabor_fn(sigma,theta,Lambda,psi,gamma): sigma_x = sigma; sigma_y = float(sigma)/gamma; # Bounding box nstds = 3; xmax = max(abs(nstds*sigma_x*numpy.cos(theta)),abs(nstds*sigma_y*numpy.sin(theta))); xmax = numpy.ceil(max(1,xmax)); ymax = max(abs(nstds*sigma_x*numpy.sin(theta)),abs(nstds*sigma_y*numpy.cos(theta))); ymax = numpy.ceil(max(1,ymax)); xmin = -xmax; ymin = -ymax; (x,y) = numpy.meshgrid(numpy.arange(xmin,xmax+1),numpy.arange(ymin,ymax+1 )); (y,x) = numpy.meshgrid(numpy.arange(ymin,ymax+1),numpy.arange(xmin,xmax+1 )); # Rotation x_theta=x*numpy.cos(theta)+y*numpy.sin(theta); y_theta=-x*numpy.sin(theta)+y*numpy.cos(theta); gb= numpy.exp(-.5*(x_theta**2/sigma_x**2+y_theta**2/sigma_y**2))*numpy.cos(2*numpy.pi/Lambda*x_theta+psi); return gb </code></pre> <p>As you may be able to tell, the only difference (I believe) between the images is contrast. So, <code>gabor_fn</code> would likely needed to be altered to do allow for this (unless I misunderstand one of the params)...I'm just not sure how.</p> <hr> <p><a href="https://i.stack.imgur.com/5F0Qc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5F0Qc.jpg" alt="enter image description here"></a></p> <hr> <p>UPDATE:</p> <pre><code>from math import pi from matplotlib import pyplot as plt data = gabor_fn(sigma=5.,theta=pi/2.,Lambda=12.5,psi=90,gamma=1.) unit = #From left to right, unit was set to 1, 3, 7 and 9. bound = 0.0009/unit fig = plt.imshow( data ,cmap = 'gray' ,interpolation='none' ,vmin = -bound ,vmax = bound ) plt.axis('off') </code></pre>
<p>It seems like <code>toimage</code> scales the input data so that the min/max values are mapped to black/white.</p> <p>I do not know what amplitudes to reasonably expect from gabor patches, but you should try something like this:</p> <pre><code>toimage(data, cmin=-1, cmax=1).show() </code></pre> <p>This tells <code>toimage</code> what range your data is in. You can try to play around with cmin and cmax, but make sure they are symmetric (i.e. <code>cmin=-x, cmax=x</code>) so that a value of 0 maps to grey. </p>
python|python-2.7|numpy|scipy
1
1,906,790
49,098,309
Convert date format: Fri, 9 Aug 2053 00:00:00 GMT
<p>I'm attempting to convert the string date <code>Fri, 9 Aug 2053 00:00:00 GMT</code> to day/month/year: <code>9/8/2053</code></p> <p>How do I exclude the <code>Fri</code> and <code>GMT</code> part from the string without using a string replace? Can this be accomplished using the datetime api ?</p> <p>Here is my attempt, but I am unsure how to achieve the above: </p> <pre><code>a = 'Fri, 9 Aug 2053 00:00:00 GMT' b = '9/8/2053' from datetime import datetime dt = datetime.strptime(a, '%d %m %Y') print(dt.strftime('%d/%m/%Y')) </code></pre>
<p>As all the above solutions, with the difference that you can use the <code>#</code> sign in order to remove any zero padding in day or month:</p> <pre><code>from datetime import datetime dt = datetime.strptime(a, "%a, %d %b %Y %H:%M:%S %Z") print(dt.strftime("%#d/%#m/%Y")) </code></pre> <p>Output:</p> <pre><code>9/8/2053 </code></pre> <p>This works for Windows. For Unix systems, consult using the <code>-</code> sign.</p>
python|datetime
4
1,906,791
70,816,135
get url link from href by beautifulsoup without redirect link
<p>I want to get just URL without redirect the link. my code is:</p> <pre><code>html = '&lt;a class=&quot;css-10y60kr&quot; href=&quot;/biz_redir?url=https%3A%2F%2Faceplumbingandrooter.com&amp;amp;cachebuster=1642876680&amp;amp;website_link_type=website&amp;amp;src_bizid=hqjCHBGnEj4nECnLJBvjQw&amp;amp;s=2caa69aa7350cca9ad00f1fd1d5a6346f341dd43e1ede874aa2eaa94d6a3458f&quot; rel=&quot;noopener nofollow&quot; role=&quot;link&quot; target=&quot;_blank&quot;&gt;https://aceplumbingandrooter.c…&lt;/a&gt;' soup=BeautifulSoup(html,'lxml') </code></pre> <p>in tag a <code>['href']</code> content :</p> <pre><code>href=&quot;/biz_redir?url=https%3A%2F%2Faceplumbingandrooter.com&amp;amp;cachebuster=1642876680&amp;amp;website_link_type=website&amp;amp;src_bizid=hqjCHBGnEj4nECnLJBvjQw&amp;amp;s=2caa69aa7350cca9ad00f1fd1d5a6346f341dd43e1ede874aa2eaa94d6a3458f&quot; </code></pre> <p>I want just the link URL: <code>aceplumbingandrooter.com</code></p>
<p>You can use <a href="https://docs.python.org/3/library/urllib.parse.html#module-urllib.parse" rel="nofollow noreferrer"><code>urllib.parse</code></a> package. The URL you are looking for is indeed one of the parameters of the <code>/biz_redir</code>, so we need to first get the <code>'url'</code> parameter out of it.</p> <pre class="lang-py prettyprint-override"><code>from urllib.parse import urlparse, parse_qs url = '/biz_redir?url=https%3A%2F%2Faceplumbingandrooter.com&amp;amp;' \ 'cachebuster=1642876680&amp;amp;website_link_type=website&amp;amp;' \ 'src_bizid=hqjCHBGnEj4nECnLJBvjQw&amp;amp;s=2caa69aa7350cca9ad00' \ 'f1fd1d5a6346f341dd43e1ede874aa2eaa94d6a3458f' parsed_url = urlparse(url) print(parse_qs(parsed_url.query)['url'][0]) </code></pre> <p>This gives you full URL <code>https://aceplumbingandrooter.com</code>. You can then parse it further and get the <code>netloc</code>, here is complete code:</p> <pre class="lang-py prettyprint-override"><code>from urllib.parse import urlparse, parse_qs url = '/biz_redir?url=https%3A%2F%2Faceplumbingandrooter.com&amp;amp;' \ 'cachebuster=1642876680&amp;amp;website_link_type=website&amp;amp;' \ 'src_bizid=hqjCHBGnEj4nECnLJBvjQw&amp;amp;s=2caa69aa7350cca9ad00' \ 'f1fd1d5a6346f341dd43e1ede874aa2eaa94d6a3458f' parsed_url = urlparse(url) new = parse_qs(parsed_url.query)['url'][0] new = urlparse(new) print(new.netloc) </code></pre> <p>output:</p> <pre class="lang-none prettyprint-override"><code>aceplumbingandrooter.com </code></pre>
python|web-scraping|beautifulsoup
3
1,906,792
60,296,050
appveyor matrix vs tox matrix
<p>I've found many references to use <a href="https://pypi.org/project/tox/" rel="nofollow noreferrer">tox</a> and a CI server, like <a href="https://www.appveyor.com/" rel="nofollow noreferrer">appveyor</a> for Python testing. However, the dependency matrices have confused me. It seems redundant for me and I don't know why to use both, like it acts in several examples. (<a href="https://www.appveyor.com/docs/lang/python/" rel="nofollow noreferrer">Appveyor's docs</a>, or an <a href="https://github.com/awslabs/pipeformer/blob/master/appveyor.yml" rel="nofollow noreferrer">example repo</a>.)</p> <p>I mean, I will list the same environment-settings under <code>environment -&gt; matrix</code> in <code>appveyor.yml</code> as in <code>envlist</code> in the <code>tox.ini</code>.</p> <p>Is it really redundant? Then why we use both matrices?</p>
<p>One matrix is for AppVeyor, another (well, it's the list of environments) is for <code>tox</code>. They are to some extend redundant but there is no way to avoid that redundancy because neither <code>tox</code> nor AppVeyor could read each other config files.</p>
python|testing|appveyor|tox
1
1,906,793
60,218,778
How do I extract numbers from a string in Python?
<p>I would like to extract numbers from an input string in Python.</p> <p>For example, If the input string is:</p> <pre><code>CS9ED389^329IP&quot;~a48# </code></pre> <p>Expected Output is:</p> <pre><code>[9, 389, 329, 48] </code></pre> <p>I did try this, but didn't work:</p> <pre><code>val = &quot;CS9ED389^329IP~a48#&quot; result = re.findall(&quot;\d+&quot;, val) </code></pre>
<p>You regexp is correct beside missing <code>r</code> also if you need exactly numbers you just need to cast them to <code>int</code>:</p> <pre><code>numbers = [int(number) for number in re.findall(r"\d+", val)] print(numbers) # list of numbers </code></pre>
python|regex
2
1,906,794
3,030,634
why does text from socket server erase previously written text?
<p>This is strange enough I'm not sure how to search for an answer. I have a program in Python that communicates via TCP/IP sockets to a telnet-based server. If I telnet in manually and type commands like this:</p> <pre><code>SET MDI G0 X0 Y0 </code></pre> <p>the server will spit back a line like this:</p> <pre><code>SET MDI ACK </code></pre> <p>Pretty standard stuff. Here's the weird part. If, in my code, I precede my printing of each of these lines with some text, the returned line erases what I'm trying to print before it. So for example, if I write the code so it should look like this:</p> <pre><code>SENT: SET MDI G0 X0 Y0 READ: SET MDI ACK </code></pre> <p>What I get instead is:</p> <pre><code>SENT: SET MDI G0 X0 Y0 SET MDI ACK </code></pre> <p>Now, if I make the "READ: " text a bit longer, I can get a better idea of what's happening. Let's say I change READ: to 12345678901234567890, so that it <em>should</em> read as:</p> <pre><code>12345678901234567890: SET MDI ACK </code></pre> <p>What I get instead is:</p> <pre><code>SET MDI ACK234567890: </code></pre> <p>So it seems like whatever text I'm getting back from the server is somehow deleting what I'm trying to precede it with. I tried saving all of my saved lines in a list, and then printing them out at the end, but it does exactly the same thing.</p> <p>Any ideas on what's going on, or even on how to debug this? Is there a way to get Python to show me any hidden chars in a string, for example?</p> <p>thx!</p>
<p>If you print <code>repr(send)</code> and <code>repr(received)</code> instead of just printing <code>sent</code> and <code>received</code>, you'll have a much clearer idea about exactly what you're sending and what you're getting back in return (so you can check if @theatrus' suggestion is correct, etc, etc, and at all times clearly see what you're doing).</p> <p>This is close to one of my favorite pragmatical principles: whenever printing or logging a string that might possibly be in error, <strong>always</strong> print its <code>repr</code> (or <code>%r</code> instead of <code>%s</code>, if that's how you're doing the formatting), <strong>never</strong> just the plain string itself (or its <code>%s</code>, which does nothing to it).</p> <p>Over and over again, if you don't use the <code>repr</code>, you'll waste substantial amounts of time debugging problems that you can't really see because the characters that snuck into the string by mistake and are therefore causing said problems aren't showing clearly in the logs (non-printing characters, control characters, and so on).</p> <p>So, always use <code>repr</code> to display or log strings unless you're 100% certain that they are perfectly correct and predictable -- get into the habit, it isn't any harder than <em>not</em> doing it once you <em>are</em> in the habit, and over the years you will have many occasions to thank this little, simple principle.</p>
python|sockets
3
1,906,795
6,267,901
Rationalising package structure in python
<p>I am developing a python library with the following structure</p> <pre><code>/application /lib __init__.py /models __init__.py model1.py model2.py model3.py </code></pre> <p>In each model%.py file there is a corresponding class named Model%. I like to keep these classes in their own files but it means that in my application I need to import classes from the models package like so</p> <pre><code>from models.model1 import Model1 from models.model2 import Model2 from models.model3 import Model3 </code></pre> <p>Is there some way to do this instead? </p> <pre><code>from models import Model1, Model2, Model3 </code></pre> <p>It feels more intuitive and more like what I am doing. I have a package called models and I want it to contain these classes but I still want each class to have its own file so I can add new models by simply adding a file.</p> <p>Previously I put this in my /application/lib/models/_<em>init</em>_py file</p> <pre><code>from model1 import Model1 from model2 import Model2 from model3 import Model3 </code></pre> <p>But I understood this was importing all the classes even when I only need one of them</p>
<p>Your final solution is correct. You should only worry about loading too many classes if it is causing serious performance issues, which I highly doubt.</p>
python|packaging
2
1,906,796
67,988,357
How to use pandas map() function, without overwriting items that do not match?
<p>In my previous question here : <a href="https://stackoverflow.com/questions/67985945/how-to-efficiently-replace-items-between-dataframes-in-pandas/67986050?noredirect=1#comment120168646_67986050">How to efficiently replace items between Dataframes in pandas?</a></p> <p>I got a solution with map() function that works, but it overrides items that do no match.</p> <p>In case I have 2 df</p> <pre><code>df = pd.DataFrame({'Ages':[20, 22, 57, 250], 'Label':[1,1,2,7]}) label_df = pd.DataFrame({'Label':[1,2,3], 'Description':['Young','Old','Very Old']}) </code></pre> <p>I want to replace the label values in df to the description in label_df, but if there is no match between the indexes, keep the original value.</p> <p>What I am getting with <code>df['Label'] = df['Label'].map(label_df.set_index('Label')['Description'])</code></p> <pre><code>{'Ages':[20, 22, 57, 250], 'Label':['Young','Young','Old', nan]} </code></pre> <p>Wanted result:</p> <pre><code>{'Ages':[20, 22, 57, 250], 'Label':['Young','Young','Old', 7]} </code></pre>
<p>You can further use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>.fillna()</code></a> with original column after <code>.map()</code> to reinstate the original values in case of no match, as follows:</p> <pre><code>df['Label'] = df['Label'].map(label_df.set_index('Label')['Description']).fillna(df['Label']) </code></pre> <p>Alternatively, you can also use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.replace.html" rel="nofollow noreferrer"><code>.replace()</code></a> which does not set non-match to <code>NaN</code> (retain non-match values), as follows:</p> <pre><code>df['Label'] = df['Label'].replace(dict(zip(label_df['Label'], label_df['Description']))) </code></pre> <p>Result:</p> <pre><code>print(df) Ages Label 0 20 Young 1 22 Young 2 57 Old 3 250 7 </code></pre>
python|pandas
1
1,906,797
67,805,036
Python app not able to access from azure app services
<p>I have deployed a Python app to Azure app service (OS: Linux, Python) from Visual Studio Code. I can able to see the files in the <code>wwwroot</code> folder as well as in the app service, but when I am trying to access the app service by URL, the login page not displayed. Please refer to the code below:</p> <pre class="lang-py prettyprint-override"><code>from flask import * app=Flask(__name__) @app.route('/') def welcome(): return render_template(&quot;login_post.html&quot;) &quot;&quot;&quot;using POST request method&quot;&quot;&quot; @app.route('/login',methods=[&quot;POST&quot;]) def login(): uname=request.form[&quot;uname&quot;] password=request.form[&quot;pass&quot;] if uname==&quot;shannu&quot; and password==&quot;guru&quot;: return &quot;Welcome %s&quot;%uname if __name__=='__main__': app.run() </code></pre> <p>Refer to the screenshot for files under <code>wwwroot</code> folder (in app service):<br /> <a href="https://i.stack.imgur.com/HCjMo.png" rel="nofollow noreferrer">Index of /wwwroot/ directory</a></p> <p>Not sure is there anything am I missing here. Thanks in advance.</p>
<p>You need add startup command.</p> <pre><code>gunicorn --bind=0.0.0.0 --timeout 600 app:app </code></pre> <p>Offical doc:</p> <p><a href="https://docs.microsoft.com/en-us/azure/app-service/configure-language-python#flask-app" rel="nofollow noreferrer">Flask app--Startup command</a></p> <h1>Suggestion</h1> <p>If this command not useful to you, it is recommand you deploy your flask app by vscode.</p> <p><a href="https://i.stack.imgur.com/0nUBN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0nUBN.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/ljrEe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ljrEe.png" alt="enter image description here" /></a></p> <p><strong>You will find azure web app will auto generate <code>gunicorn</code> command for 'app:app'.</strong></p> <p><a href="https://i.stack.imgur.com/jgd1G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jgd1G.png" alt="enter image description here" /></a></p>
python-3.x|azure-web-app-service
1
1,906,798
67,715,924
How to import text file in Data bricks
<p>I am trying to write text file with some text and loading same text file in data-bricks but i am getting error</p> <p>Code</p> <pre><code>#write a file to DBFS using Python I/O APIs with open(&quot;/dbfs/FileStore/tables/test_dbfs.txt&quot;, 'w') as f: f.write(&quot;Apache Spark is awesome!\n&quot;) f.write(&quot;End of example!&quot;) # read the file with open(&quot;/dbfs/tmp/test_dbfs.txt&quot;, &quot;r&quot;) as f_read: for line in f_read: print(line) </code></pre> <p>Error FileNotFoundError: [Errno 2] No such file or directory: '/dbfs/FileStore/tables/test_dbfs.txt'</p>
<p>The <code>/dbfs</code> mount doesn't work on Community Edition with DBR &gt;= 7.x - it's a known limitation.</p> <p>To workaround this limitation you need to work with files on the driver node and upload or download files using the <code>dbutils.fs.cp</code> command (<a href="https://docs.databricks.com/dev-tools/databricks-utils.html" rel="nofollow noreferrer">docs</a>). So your writing will look as following:</p> <pre class="lang-py prettyprint-override"><code>#write a file to local filesystem using Python I/O APIs with open(&quot;'file:/tmp/local-path'&quot;, 'w') as f: f.write(&quot;Apache Spark is awesome!\n&quot;) f.write(&quot;End of example!&quot;) # upload file to DBFS dbutils.fs.cp('file:/tmp/local-path', 'dbfs:/FileStore/tables/test_dbfs.txt') </code></pre> <p>and reading from DBFS will look as following:</p> <pre class="lang-py prettyprint-override"><code># copy file from DBFS to local file_system dbutils.fs.cp('dbfs:/tmp/test_dbfs.txt', 'file:/tmp/local-path') # read the file locally with open(&quot;/tmp/local-path&quot;, &quot;r&quot;) as f_read: for line in f_read: print(line) </code></pre>
python-3.x|databricks|aws-databricks|databricks-community-edition
0
1,906,799
67,933,443
how to unpack a struct with uint16_t type in python
<p>I'm trying to unpack ElfHeader in python. Type of <code>e_type</code> in Elf64_Edhr struct is uint16_t, How can I unpack it? I only found a way to unpack 4 bit unsigned int in python struct docs.</p>
<p>Probably every machine Python supports has 8 bits per byte, so a 16-bit integer uses 2 bytes. We want the size to be the same on every machine, so we look at the <em>standard size</em> column. The format for an unsigned integer with a standard size of 2 bytes or 16 bits is <code>H</code>.</p> <p>For the standard size to be relevant, the <code>unpack</code> pattern must start with <code>&lt;</code>, <code>&gt;</code>, <code>!</code> or <code>=</code> depending on endianness. ELF supports both little- and big-endian values depending on the byte at offset 0x05 of the file, so your pattern would start with either <code>&lt;</code> or <code>&gt;</code> depending on what the endianness of the file.</p> <ul> <li><p>If the byte at offset 0x05 is <code>1</code>, it's a little-endian file, so your pattern must start with <code>&lt;</code>.<br></p> <p>LE uint16_t 0x3456 = 13398 is <code>b'\x56\x34'</code></p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; x = b'\x56\x34' &gt;&gt;&gt; struct.unpack('&lt;H', x) (13398,) </code></pre> </li> <li><p>If the byte at offset 0x05 is <code>2</code>, it's a big-endian file, so your pattern must start with <code>&gt;</code>.<br></p> <p>BE uint16_t 0x3456 = 13398 is <code>b'\x34\x56'</code></p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; x = b'\x34\x56' &gt;&gt;&gt; struct.unpack('&gt;H', x) (13398,) </code></pre> </li> </ul>
python|c|struct|binary|elf
2