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,902,000 | 25,184,353 |
Why am I having problems with "large" matrices in sage?
|
<p>I'm trying to do some computations with a 22x22 matrix in sage. This doesn't seem like it should be that bad to do, in particular since the matrix is pretty sparse. However, when I try to do anything with the matrix I get an "IndexError: string index out of range", or nonsense computations. What gives?</p>
<p>Even very simply, if I try the following code:</p>
<blockquote>
<p>M = matrix(ZZ,20); M</p>
</blockquote>
<p>This should display a 20x20 matrix of zeros. However, it instead gives the same IndexError, where</p>
<blockquote>
<p>M = matrix(ZZ,19); M</p>
</blockquote>
<p>does not, and gives exactly what you expect.</p>
<p>The funny thing is that having inputted my matrix, any attempt to display it gives the IndexError. However, there are still a few things that I can do that give "answers", although I'm skeptical about their correctness. For example, I can do things like</p>
<blockquote>
<p>M.parent()</p>
</blockquote>
<p>which seems to make sense. However,</p>
<blockquote>
<p>M.determinant()</p>
</blockquote>
<p>spits out a number, but I'm about 99% certain that the number it gives me has little to do with the determinant of the matrix that I've put in.</p>
<p>So what's up? Is sage just incapable of dealing with matrices greater than size 19x19?</p>
<p>Edit: This is on Mac OS X 10.9.4, and my sage version is 5.10. This is after a fresh restart of sage, which gives me the same error. However, it seems that I should probably update sage and see if it keeps up with the problem....</p>
|
<p>This is a known and fixed bug, see tickets <a href="http://trac.sagemath.org/ticket/14785" rel="nofollow">#14785</a>
and <a href="http://trac.sagemath.org/ticket/14579" rel="nofollow">#14579</a> on
<a href="http://trac.sagemath.org/" rel="nofollow">Sage's trac</a>, where we learn that the bug was in Python,
see <a href="http://bugs.python.org/issue17526" rel="nofollow">issue 17526</a> on
<a href="http://bugs.python.org/" rel="nofollow">Python's bug tracker</a>,
that it was resovled upstream, and that this works well in Sage since version 5.11.beta3.</p>
<p>I agree with John Palmieri's encouragement to update. Sage gets better and better, so it's
always worth working with a recent version. Currently Sage 6.2 is out, and Sage 6.3.rc1 is
out and works well, so Sage 6.3 should be released pretty soon.</p>
<p>Regarding the determinant, I would be very surprised if it is computed incorrectly, but
why don't you check by computing it in another computer algebra system? If it is indeed
incorrect, please report the bug. Search the web for 'wims determinant' for an online
determinant calculator.</p>
<p>Edit (2014-08-10):
<a href="https://groups.google.com/d/topic/sage-release/Ilt8TZdy3H8/discussion" rel="nofollow">Sage 6.3 is out!</a></p>
<p>And while I'm editing I'll link to the
<a href="http://wims.unice.fr/~wims/en_tool~linear~matrix.html" rel="nofollow">wims matrix tool</a>,
just for completeness.
I also confess that I haven't checked who Wims and Sage call for computing such a
determinant; it might end up being the same software, so that wouldn't be much
of a check. It's good that you checked it another way.</p>
|
python|matrix|indexoutofboundsexception|sage
| 3 |
1,902,001 | 25,234,336 |
Simple Python TCP server not working on Amazon EC2 instance
|
<p>I am trying to run a simple Python TCP server on my EC2, listening on port 6666. I've created an inbound TCP firewall rule to open port 6666, and there are no restrictions on outgoing ports.</p>
<p>I cannot connect to my instance from the outside world however, testing with telnet or netcat can never make the connection. Things do work if I make a connection from localhost however.</p>
<p>Any ideas as to what could be wrong?</p>
<pre>
<code>
#!/usr/bin/env python
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 6666
BUFFER_SIZE = 20 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connection address:', addr
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
conn.send(data) # echo
conn.close()
</code>
</pre>
|
<p>Your TCP_IP is only listening locally because you set your listening IP to 127.0.0.1.<br>
Set <code>TCP_IP = "0.0.0.0"</code> and it will listen on "all" interfaces including your externally-facing IP.</p>
|
python|amazon-web-services|tcp|amazon-ec2|firewall
| 10 |
1,902,002 | 25,412,913 |
Giving attributes to an object in Python
|
<p>I need to copy the attribute of an array to another array that I'm newly creating. Here's my code snippet:</p>
<pre><code>def mutation(self,ind):
fitnessvalues = ind.fitness.values # saving the attributes
G = Graph()
G.add_vertices(nbr_noeuds)
n = int(math.floor(1 + math.sqrt(1 + 8 * len(ind))/2))
c = 0
for i in range(nbr_noeuds-1):
for j in range(i+1, n):
if ind[c] == 1:
G.add_edge(i,j)
c += 1
for i in range(10):
G.rewire(n=3, mode="simple")
bin = array.array('b')
for i in range(n-1):
for j in range(i+1,n):
bin.append(int(G.are_connected(i, j)))
bin.fitness.values = fitnessvalues # Wrongly putting the saved attribute to the new array
return (bin,)
</code></pre>
<p>"bin.fitness.values = fitnessvalues" is not the way to go. So how to add attributes to an array in Python ?</p>
|
<p>In python (and other Object Oriented languages), attributes are generally defined (the name and behavior of the attribute, not necessarily it's value) at the class level, not per instance. In python you can <em>sometimes</em> add attributes to an object which are to defined at the class level, but you cannot do this with built in types (including <code>array.array</code>). Lets take <code>defaultdict</code> as an example, all instances of <code>defaultdict</code> have the <code>default_factory</code> attribute. You can set the attribute by simply assigning to it or by using the setattr function.</p>
<pre><code>from collections import defaultdict
d = defaultdict(int)
d.default_factory = float
setattr(d, "default_factory", complex)
</code></pre>
<p>You cannot add new attributes to a defaultdict, or to instances of most (probably all) built in python types.</p>
<pre><code>d.new_attr = "some value"
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/Users/bagrata/<ipython-input-85-3fd77cc8678c> in <module>()
----> 1 d.new_attr = "blah"
AttributeError: 'collections.defaultdict' object has no attribute 'new_attr'
</code></pre>
<p>You can subclass built in types, and define new attributes:</p>
<pre><code>class MyDefaultdict(defaultdict):
new_attr = None
d = MyDefaultdict(int)
d.new_attr = "some value"
</code></pre>
<p>You can also add new attributes to instances of <code>MyDeaultdict</code> because the class does not explicitly prohibit it, but you should absolutely never do this:</p>
<pre><code>d.attribute_unique_to_this_instance = "some value"
</code></pre>
|
python
| 1 |
1,902,003 | 59,965,849 |
foreignkey assignment error python django model
|
<p><strong>models.py</strong>
i have create foreignkey in table paymentsDetails i have stripe payment method which is working when user login session is created and by using session value i get the primarykey of that user by using 'ORM' method and then assign this primary key of specific user into the paymentdetails models field named as user_account_id
but i am getting error that i cannot assign 1 to PaymentsDetail.User_account_id must be a instance of UserAccountModel</p>
<pre><code>class UserAccountModel(models.Model):
ContactEmail = models.EmailField(max_length=30)
FirstName = models.CharField(max_length=30)
LastName = models.CharField(max_length=40)
Counrty = models.CharField(max_length=50)
Phone = models.IntegerField()
ChooseUserName = models.CharField(max_length=30)
password = models.CharField(max_length=32)
EnterCaptcha = models.CharField(max_length=4)
payments = models.BooleanField(max_length=6, default=False)
showsponsor = models.CharField(max_length=30, default=False)
RegisteredDate = models.DateTimeField(auto_now_add=True, blank=True)
ActivationOn = models.DateField(auto_now_add=False,blank=True)
expiry_date = models.DateField(auto_now_add=False,blank=True)
def __str__(self):
return self.FirstName + ":" + self.ChooseUserName
class PaymentsDetail(models.Model):
refrer_name = models.CharField(max_length=32,default="", editable=False)
sponser_name = models.CharField(max_length=32)
status = models.CharField(default='comped', max_length=32)
s_id = models.CharField(max_length=32)
registered = models.DateTimeField(auto_now_add=True)
activated_date = models.DateField(auto_now_add=False)
Due_Date = models.DateField(auto_now_add=False)
payment = models.CharField(default='$',max_length=32)
User_Account_id = models.ForeignKey(UserAccountModel, on_delete=models.CASCADE, default=True, editable=True)
addprogrameReference = models.ForeignKey(AddProgramModel, on_delete=models.CASCADE, default=True, editable=True)
class Meta:
ordering = ['User_Account_id', 'addprogrameReference']
</code></pre>
<p>def <strong>str</strong>(self):
return self.refrer_name + ":" + self.user_account</p>
<blockquote>
<p>i am getting the error</p>
<p>cannot assign 1 to PaymentsDetail.User_account_id must be a instance
of UserAccountModel</p>
</blockquote>
<p><strong>views.py</strong></p>
<pre><code> print("user payment"+str(charge.amount))
pays = str(charge.amount)
user_id = random.randint(0, 999) # returns a random integer
user = User.objects.get(username=str(rerredby))
userKey = user.pk
print("this one is for user upper")
# saving record
payment_insertion = PaymentsDetail.objects.create(
User_Account_id=userKey,
refrer_name=rerredby,
sponser_name=rerredby,
s_id=str(user_id),
registered=datetime.now(),
activated_date=datetime.now(),
Due_Date=datetime.now(),
payment=str(pays + "$"),
)
payment_insertion.save()
</code></pre>
|
<p>Simply change this string:</p>
<pre><code>payment_insertion = PaymentsDetail.objects.create(
User_Account_id=user,
...)
</code></pre>
<p>You are trying to assign int object where Django expects an instance.</p>
|
python|django
| 0 |
1,902,004 | 60,014,652 |
Create relative path and being OS independent
|
<p>How can I get my script's file name as a relative path to <code>cwd</code> and it being OS independent?</p>
<p>e.g if I'm in linux it should return "./script.py" and if I'm in windows it should return ".\\script.py"</p>
<p>I tried with <code>os.path.join</code> and <code>os.path.basename(__file__)</code> but it returns absolute path. </p>
|
<pre><code>import os
import platform
path = os.path.basename(__file__)
run_on=platform.system()
if run_on=='Windows': path=f'.\\{path}'
elif run_on=='Linux': path=f'./{path}'
print(f'path is {path}')
</code></pre>
|
python|linux|windows|path|operating-system
| 2 |
1,902,005 | 2,815,847 |
Is there are standard way to store a database schema outside a python app
|
<p>I am working on a small database application in Python (currently targeting 2.5 and 2.6) using sqlite3.</p>
<p>It would be helpful to be able to provide a series of functions that could setup the database and validate that it matches the current schema. Before I reinvent the wheel, I thought I'd look around for libraries that would provide something similar. I'd love to have something akin to RoR's migrations. <a href="http://xml2ddl.berlios.de/" rel="nofollow noreferrer">xml2ddl</a> doesn't appear to be meant as a library (although it could be used that way), and more importantly doesn't support sqlite3. I'm also worried about the need to move to Python 3 one day given the lack of recent attention to xml2ddl.</p>
<p>Are there other tools around that people are using to handle this? </p>
|
<p>You can find the schema of a sqlite3 table this way:</p>
<pre><code>import sqlite3
db = sqlite3.connect(':memory:')
c = db.cursor()
c.execute('create table foo (bar integer, baz timestamp)')
c.execute("select sql from sqlite_master where type = 'table' and name = 'foo'")
r=c.fetchone()
print(r)
# (u'CREATE TABLE foo (bar integer, baz timestamp)',)
</code></pre>
|
python|sqlite
| 3 |
1,902,006 | 30,360,183 |
Finding and converting XML processing instructions using Python
|
<p>We are converting our ancient FrameMaker docs to XML. My job is to convert this:</p>
<pre><code><?FM MARKER [Index] foo, bar ?>`
</code></pre>
<p>to this:</p>
<pre><code><indexterm>
<primary>foo, bar</primary>
</indexterm>
</code></pre>
<p>I'm not worried about that part (yet); what is stumping me is that the <code>ProcessingInstruction</code>s are all over the documents and could potentially be under any element, so I need to be able to search the entire tree, find them, and then process them. I cannot figure out how to iterate over an entire XML tree using <code>minidom</code>. Am I missing some secret method/iterator? This is what I've looked at thus far:</p>
<ul>
<li><p><code>Elementtree</code> has the excellent <code>Element.iter()</code> method, which is a depth-first search, but it doesn't process <code>ProcessingInstruction</code>s.</p></li>
<li><p><code>ProcessingInstruction</code>s don't have tag names, so I cannot search for them using <code>minidom</code>'s <code>getElementsByTagName</code>.</p></li>
<li><p><code>xml.sax</code>'s <code>ContentHandler.processingInstruction</code> looks like it's only used to create <code>ProcessingInstruction</code>s.</p></li>
</ul>
<p>Short of creating my own depth-first search algorithm, is there a way to generate a list of <code>ProcessingInstruction</code>s in an XML file, or identify their parents?</p>
|
<p>Use the XPath API of the <code>lxml</code> module as such:</p>
<pre><code>from lxml import etree
foo = StringIO('<foo><bar></bar></foo>')
tree = etree.parse(foo)
result = tree.xpath('//processing-instruction()')
</code></pre>
<blockquote>
<p>The node test processing-instruction() is true for any processing instruction. The processing-instruction() test may have an argument that is Literal; in this case, it is true for any processing instruction that has a name equal to the value of the Literal.</p>
</blockquote>
<p><strong>References</strong></p>
<ul>
<li><a href="http://lxml.de/xpathxslt.html" rel="nofollow">XPath and XSLT with lxml</a></li>
<li><a href="https://www.w3.org/TR/xpath/#node-tests" rel="nofollow">XML Path Language 1.0: Node Tests</a></li>
</ul>
|
python|xml|elementtree|minidom|processing-instruction
| 2 |
1,902,007 | 67,031,427 |
Print from High to Low occurrences of Dictionary in Python
|
<p>I have a code that counts every word in a file and counts how many times they occurred.</p>
<pre><code>filename = "test.txt"
output = []
with open(filename) as f:
content = f.readlines()
content = [x.strip() for x in content]
wordlist = {}
for line in content:
for entry in line.split():
word = entry.replace('.', '')
word = word.replace(',', '')
word = word.replace('!', '')
word = word.replace('?', '')
if word not in wordlist:
wordlist[word] = 1
else:
wordlist[word] = wordlist[word] + 1
print(wordlist)
</code></pre>
<p>However, when I print this, I am not able to specify to go from high to low occurrences.</p>
<p>Here is a test file.</p>
<pre><code>hello my friend. hello sir.
</code></pre>
<p>How do I print such that it looks like
<code>hello: 2 (newline)</code>
<code>my: 1</code>
etc?</p>
|
<p>In <code>python3.7</code> and up the <code>dict</code> preserve the insertion order. So we can just sort the dictionary item by values and then insert(or create) in new <code>dict</code>.</p>
<p>Use:</p>
<pre><code>print(dict(sorted(wordlist.items(), key = lambda x: -x[1])))
</code></pre>
|
python|python-3.x
| 0 |
1,902,008 | 66,772,751 |
C++ & Python : Formating items of an array and removing duplicates from it
|
<p>I was translating a code from Python to C++ (of which i'm not a frequent user by far,
understanding only a little more than just synthax) and got stuck at a point, where i need to format
the b array and then remove the duplicates from already formatted array. At the very end, count the number
of items in the array c. I have outline the problematic part (which i left written in Python).
As you can see, i have a m_l array with 10 numbers, which will be used for 5 for loops. I have a preliminarily prepared b array where i will put all the possible sums comming out of the 5 for loop construction. Then, as it was mentioned earlier, i want to format items of b array, so each item has 4 numbers after dot (i.e. 128.7153). After formating i would move to duplications removal and then deremination of c array's items count.
Would you please help me with that part? Thank you in advance.
The code so far looks lite this:</p>
<pre><code>#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
int main()
{
double m_l[10] = {12.05132, 178.0779, 52.13106, 44.15764, 100.15764, 726.0874, 109.11398, 9.11518,
198.10388, 36.0773}
vector<double> b;
for (int d = 0; d < 10; d++){
for(int e = 0; e < 10; e++){
for(int f = 0; f < 10; f++){
for(int g = 0; g < 10; d++){
for(int h = 0; h < 10; h++){
b.push_back(m_l[d]+m_l[e]+m_l[f]+m_l[g]+m_l[h]);}}}}}
int bSize = sizeof(b)/sizeof(b[0]);
cout << "The size of the b is: " << bSize << "\n";
cout << " " << "\n";
_______________________________________________________
myformattedlist = ["%.4f" % item for item in b]
c = set(myformattedlist)
_______________________________________________________
int cSize = sizeof(c)/sizeof(c[0]);
cout << "The size of the c is: " << cSize << "\n";
cout << " " << "\n";
return 0;
}
</code></pre>
|
<p>If you just want to remove duplicates inside the vector you can do this:</p>
<pre><code>c++11:
for (auto it = b.begin(); it != b.end(); it++) // first iterate over the vector
for (auto it2 = it + 1; it2 != b.end(); it2++) // then for each value after the current, check if there is a duplicate
if (*it2 == *it) // if it is duplicate
{
auto tmp = it2; // put the value of the iterator in tmp
it2--; // decrease the iterator so we don't lose it when erasing (which can cause a segfault)
b.erase(tmp); // then remove it
}
c++98:
for (std::vector<double>::iterator it = b.begin(); it != b.end(); it++)
for (std::vector<double>::iterator it2 = it + 1; it2 != b.end(); it2++)
if (*it2 == *it)
{
std::vector<double>::iterator tmp = it2;
it2--;
b.erase(tmp);
}
c-style:
for (int i = 0; i < b.size(); i++)
for (int j = i + 1; j < b.size(); j++)
if (b[j] == b[i])
{
b.erase(b.begin() + j);
j--; // decrease the index so we don't skip one member
}
</code></pre>
<p>And for the size, just use the member method <code>std::vector::size</code> (in your case <code>b.size()</code>)</p>
|
python|c++|arrays|formatting
| -2 |
1,902,009 | 67,142,853 |
How do I calculate SHA-256 hash of a list in Python?
|
<p>I am trying to replicate JS method:</p>
<p>JS code:</p>
<pre><code>
const toHexCopy = (buffer) => {
return [...new Uint8Array (buffer)]
.map (b => b.toString (16).padStart (2, "0"))
.join ("");
};
ar = new Uint8Array([0, 1, 2]);
hash = await crypto.subtle.digest('SHA-256', ar)
console.log(toHexCopy(hash))
// returns 039058c6f2c0cb492c533b0a4d14ef77cc0f78abccced5287d84a1a2011cfb81
</code></pre>
<p>How do I replicate it in Python?</p>
|
<pre class="lang-py prettyprint-override"><code>from hashlib import sha256
print(sha256(bytes([1, 2, 3])).hexdigest())
</code></pre>
|
python-3.x|list|sha256
| 1 |
1,902,010 | 42,675,902 |
I'm trying to count non integers in double arrays in Python
|
<p>I'd like to count the number of non integers in double array.
For example</p>
<pre><code>Input: mylist=[['a',-2,'b',-3,1],['c','a',-1,1,3],['d','f'],['e',3],[-11]]
Output: num_value(mylist)=7
</code></pre>
<p>Show me how to make it. </p>
|
<p>Count instances of non-integers in the lists of lists (using double <code>for</code> in generator comprehension fed to <code>sum</code>)</p>
<pre><code>mylist=[['a',-2,'b',-3,1],['c','a',-1,1,3],['d','f'],['e',3],[-11]]
print(sum(1 for sl in mylist for x in sl if not isinstance(x,int)))
</code></pre>
<p>yields: <code>7</code></p>
|
python|arrays|count|isalpha
| 1 |
1,902,011 | 42,671,967 |
Python collection for create if missing, update if existing
|
<p>The programming pattern I want to implement is: create an object, if it is missing from the collection
add it to the collection, else update the equivalent object in the collection.</p>
<pre><code>class PersonStats(object):
def __init__(self, i):
super(PersonStats, self).__init__()
self.id = i
self.stats = 0
def update_stats(self):
self.stats += 1
def __key(self):
return self.id
def __eq__(self, y):
return self.__key() == y.__key()
def __hash__(self):
return hash(self.__key())
s = set_like_collection()
special_person = PersonStats(22222)
r = s.find(special_person)
if r is not None:
r.update_stats()
else:
s.add(r)
</code></pre>
<p>I was surprised to learn that Python's set does not have a find function. (One needs to iterate the set to find the object she desire)
I know I can use defaultdict but I hate to break the encapsulation of PersonStats, That is, in the above example, use the person's id out
side of the class PersonStats.</p>
<p>So my question is do you know of a data structure in Python that would let me have an unordered_set and let me find in it in constant time?<br>
Also would like to know if I am thinking of it all wrong.<br>
Also if you know why Python's set does not have find function.</p>
|
<p>You might want to use an ordered set: </p>
<p><a href="https://pypi.python.org/pypi/ordered-set" rel="nofollow noreferrer">https://pypi.python.org/pypi/ordered-set</a></p>
<p>The <code>.index(...)</code> function delivers the 'position' in the set.
You might want to catch exceptions, though.</p>
|
python|data-structures
| 1 |
1,902,012 | 66,540,321 |
How to create a dictionary out of random values from two lists?
|
<p>Context: I have two lists of unequal size; <code>names</code> holds family members' names and <code>chores</code> holds a much longer list of, well, chores. I am writing a program to randomly assign each chore to a family member, so that the everyone gets the same number of chores (or at least with +1/-1). I've thought of a few possible ways of going about this, at least in theory. One way would be to simply shuffle the list of <code>chores</code>, split the list evenly into <code>n</code> new lists, and assign one of these smaller lists to each family member. I could also loop through the list of chores, assigning each family member a chore on each pass through until all chores have been assigned to a family member.</p>
<p>I've had trouble finding specific operations or examples to help work through this; is there a specific workflow I should consider?.</p>
|
<p>Setup stolen from pakpe's answer:</p>
<pre><code>import random
names = ['John', 'Ashley', 'Debbie']
chores = ['cook', 'clean', 'shop', 'pay bills', 'wash car', 'mow lawn', 'walk dog', 'drive kids']
</code></pre>
<p>Solution 1, distributing the chores evenly:</p>
<pre><code>random.shuffle(names)
random.shuffle(chores)
assignments = {name: chores[i::len(names)]
for i, name in enumerate(names)}
</code></pre>
<p>Sample result:</p>
<pre><code>{'Debbie': ['wash car', 'clean', 'shop'],
'Ashley': ['walk dog', 'mow lawn', 'cook'],
'John': ['drive kids', 'pay bills']}
</code></pre>
<p>Solution 2, perhaps slightly easier but uneven (posted before they changed the question):</p>
<pre><code>assignments = {name: [] for name in names}
for chore in chores:
assignments[random.choice(names)].append(chore)
</code></pre>
<p>Sample result:</p>
<pre><code>{'Debbie': ['mow lawn', 'pay bills', 'shop', 'cook'],
'Ashley': [],
'John': ['wash car', 'walk dog', 'drive kids', 'clean']}
</code></pre>
<p>(First try, Ashley really got that lucky.)</p>
|
python|pandas|macos|dataframe
| 2 |
1,902,013 | 72,285,949 |
Python Color Dataframe cells depending on values
|
<p>I am trying to color the cells</p>
<p>I have the following Dataframe:</p>
<pre><code> pd.DataFrame({'Jugador': {1: 'M. Sanchez',
2: 'L. Ovalle',
3: 'K. Soto',
4: 'U. Kanu',
5: 'K. Abud'},
'Equipo': {1: 'Houston Dash',
2: 'Tigres UANL',
3: 'Guadalajara',
4: 'Tigres UANL',
5: 'Cruz Azul'},
'Edad': {1: 26, 2: 22, 3: 26, 4: 24, 5: 29},
'Posición específica': {1: 'RAMF, RW',
2: 'LAMF, LW',
3: 'RAMF, RW, CF',
4: 'RAMF, CF, RWF',
5: 'RW, RAMF, LW'},
'Minutos jugados': {1: 2053, 2: 3777, 3: 2287, 4: 1508, 5: 1436},
'Offence': {1: 84, 2: 90, 3: 69, 4: 80, 5: 47},
'Defense': {1: 50, 2: 36, 3: 64, 4: 42, 5: 86},
'Passing': {1: 78, 2: 81, 3: 72, 4: 73, 5: 71},
'Total': {1: 72, 2: 71, 3: 69, 4: 66, 5: 66}})
</code></pre>
<p>How can I color the Offence, Defense and Passing cells green if > 60, red < 40 and yellow the rest?</p>
|
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.applymap.html" rel="nofollow noreferrer"><code>Styler.applymap</code></a> with custom function:</p>
<pre><code>def styler(v):
if v > 60:
return 'background-color:green'
elif v < 40:
return 'background-color:red'
else:
return 'background-color:yellow'
df.style.applymap(styler, subset=['Offence','Defense','Passing'])
</code></pre>
<p>Alternative solution:</p>
<pre><code>styler = lambda v: 'background-color:green' if v > 60 else 'background-color:red' if v < 40 else 'background-color:yellow'
df.style.applymap(styler, subset=['Offence','Defense','Passing'])
</code></pre>
<p>Another approach:</p>
<pre><code>def hightlight(x):
c1 = 'background-color:green'
c2 = 'background-color:red'
c3 = 'background-color:yellow'
cols = ['Offence','Defense','Passing']
#DataFrame with same index and columns names as original filled empty strings
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
#modify values of df1 columns by boolean mask
df1[cols] = np.select([x[cols] > 60, x[cols] < 40], [c1, c2], default=c3)
return df1
df.style.apply(hightlight, axis=None)
</code></pre>
|
python|pandas
| 1 |
1,902,014 | 72,341,163 |
IntegrityError at /listing/1/ NOT NULL constraint failed: auctions_comments.user_id. I am trying to save comments and need help resolving this error
|
<p>I am trying to make an e-commerce site (CS50 Project 2) that saves comments. The comments were previously saving, but then I added ForeignKeys to my comment model to link it to the Listings and User models. Now whenever I try to save a comment this error occurs.</p>
<pre><code>IntegrityError at /listing/1/
NOT NULL constraint failed: auctions_comments.user_id
Request Method: POST
Request URL: http://127.0.0.1:8000/listing/1/
Django Version: 3.2.5
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: auctions_comments.user_id
</code></pre>
<p>And this line of code is highlighted <code>comment.save()</code>.</p>
<p><code>models.py:</code></p>
<pre><code>class User(AbstractUser):
pass
class Listings(models.Model):
CATEGORY = [
("Miscellaneous", "Miscellaneous"),
("Movies and Television", "Movies and Television"),
("Sports", "Sports"),
("Arts and Crafts", "Arts and Crafts"),
("Clothing", "Clothing"),
("Books", "Books"),
]
title = models.CharField(max_length=64)
description = models.CharField(max_length=500)
bid = models.DecimalField(max_digits=1000000000000, decimal_places=2)
image = models.URLField(null=True, blank=True)
category = models.CharField(max_length=64, choices=CATEGORY, default=None)
class Comments(models.Model):
listing = models.ForeignKey(Listings, on_delete=models.CASCADE, default="")
user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
comment = models.CharField(max_length=500)
</code></pre>
<p><code>views.py:</code></p>
<pre><code>@login_required(login_url='login')
def listing(request, id):
listing = Listings.objects.get(id=id)
comment_obj = Comments.objects.filter(listing=listing)
form = CommentForm()
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.listing = listing
comment.save()
else:
return render(request, "auctions/listing.html",{
"auction_listing": listing,
"form": form,
"comments": comment_obj
})
return render(request, "auctions/listing.html",{
"auction_listing": listing,
"form": form,
"comments": comment_obj
})
</code></pre>
<p><code>html or template file:</code></p>
<pre><code>{% block body %}
<img src ="{{ auction_listing.image }}" style = "height: 10%; width: 10%;">
<h4 class = "text">{{ auction_listing.title }}</h4>
<h6>Description: {{ auction_listing.description }}</h6>
<h6>Category: {{ auction_listing.category }}</h6>
<h6>Price: ${{ auction_listing.bid }}</h6>
<form action = "{% url 'listing' auction_listing.id %}" method = "POST">
{% csrf_token %}
{{ form }}
<input type = "submit" value = "Save">
</form>
{% for comment in comments %}
<h6> {{ comment.comment }} </h6>
{% endfor %}
<button type = "button">Add to Watchlist</button>
{% endblock %}
</code></pre>
<p>I think the problem is with the comment.save() in the views.py and the form in the html where it says "{% url 'listing' auction_listing.id %}", but I don't know how to fix it.</p>
<p><code>forms.py:</code></p>
<pre><code>class ListingsForm(forms.ModelForm):
class Meta:
model = Listings
fields = ['title', 'description', 'bid', 'image', 'category']
class CommentForm(forms.ModelForm):
class Meta:
model = Comments
fields = ['comment']
</code></pre>
|
<p>I'm assuming that the form the user is using to post a comment doesn't have them specify their <code>listing</code> ID or <code>user</code> ID. If this is the case, then both <code>listing</code> and <code>user</code> in the <code>Comments</code> would be null which is what gives the error since foreign keys aren't allowed to be null. You'd have to manually fill in this missing data in your view. It looks like you already have the listing value figured out and you add it to the form instance. You just have to do the same thing for the user. The <code>request</code> argument has a <code>user</code> field that you can use to figure out the <code>user</code> ID.</p>
<pre class="lang-py prettyprint-override"><code>if form.is_valid():
comment = form.save(commit=False)
comment.listing = listing
comment.user = request.user
comment.save()
</code></pre>
|
python|django|django-models|django-forms|django-templates
| 2 |
1,902,015 | 65,538,681 |
Don't understand "TensorFlow Object Detection" with OpenCV GitHub Wiki
|
<p>I am trying to use <a href="https://github.com/opencv/opencv/wiki/TensorFlow-Object-Detection-API" rel="nofollow noreferrer">this wiki</a> to detect objects with Python OpenCV. But I don't understand this line of code we're supposed to use:</p>
<pre><code>python tf_text_graph_faster_rcnn.py --input /path/to/model.pb --config /path/to/example.config --output /path/to/graph.pbtxt
</code></pre>
<p>I want to use MobileNet-SSD v3, so I downloaded <a href="https://gist.github.com/dkurt/54a8e8b51beb3bd3f770b79e56927bd7" rel="nofollow noreferrer">this</a>, as well as the <a href="https://github.com/opencv/opencv/blob/master/samples/dnn/tf_text_graph_ssd.py" rel="nofollow noreferrer">tf_text_graph_ssd.py file</a> and the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/samples/configs/ssdlite_mobilenet_v3_large_320x320_coco.config" rel="nofollow noreferrer">ssdlite_mobilenet_v3_large_320x320_coco.config file</a>.</p>
<p>But none of the files have the *.pb extension listed in the python command line, and <a href="https://gist.github.com/dkurt/54a8e8b51beb3bd3f770b79e56927bd7" rel="nofollow noreferrer">this file</a> already has the *.pbtxt output-extension, so I don't get what that line has to do exactly?</p>
<p>This probably is a very basic question, but I've been struggling with this for some time now so I thought I may ask.</p>
<p>Thank you!</p>
|
<p>this <a href="https://github.com/opencv/opencv/wiki/TensorFlow-Object-Detection-API" rel="nofollow noreferrer">wiki</a> asking you to download the <strong>.pb file</strong> which is a model from the <strong>Model Zoo</strong>. However the link is broken. Here is the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf1_detection_zoo.md" rel="nofollow noreferrer">the working link</a>.</p>
<p><a href="http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v3_large_coco_2020_01_14.tar.gz" rel="nofollow noreferrer">MobileNet-SSD v3</a> is here, you can find other MobileNet_SSD v3 models in the link above as well.</p>
<p>After unzip the downloaded file, you will find the file, <strong>frozen_inference_graph.pb</strong>. That is the model file you need.</p>
|
python|tensorflow|opencv|object-detection|mobilenet
| 0 |
1,902,016 | 65,486,502 |
Getting an invalid JWT token when I try to register a django user
|
<p>trying to figure out why I'm getting an invalid token error given my code below. I'm testing registration and authentication via my API.</p>
<p>I create a dummy account and then check my email for the verification link. Everything is working great until I click on the link in the email and receive a 400 bad request and due to my debugging the error is caused by an "Invalid Token".</p>
<p>Here is my code:</p>
<p><code>views.py</code></p>
<pre><code>import jwt
from django.urls import reverse
from django.contrib.sites.shortcuts import get_current_site
from django.conf import settings
#from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework import generics ,status
from rest_framework.response import Response
from rest_framework import views
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.permissions import AllowAny
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from .models import NewUser
from .serializers import RegisterSerializer, EmailVerificationSerializer, LoginSerializer
from .utils import ConfirmEmail
class CustomUserCreate(generics.GenericAPIView):
permission_classes = [AllowAny]
serializer_class = RegisterSerializer
def post(self, request):
user = request.data
serializer = self.serializer_class(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
user_data = serializer.data
user = NewUser.objects.get(email=user_data['email'])
token = RefreshToken.for_user(user).access_token
current_site = get_current_site(request).domain
relativeLink = reverse('users:email-verify')
absurl = 'http://'+current_site+relativeLink+"?token="+str(token)
email_body = 'Hi '+user.username + \
' Use the link below to verify your email \n' + absurl
data = {'email_body': email_body, 'to_email': user.email,
'email_subject': 'Verify Your Email'}
ConfirmEmail.send_email(data)
return Response(user_data, status=status.HTTP_201_CREATED)
class VerifyEmail(views.APIView):
permission_classes = [AllowAny]
serializer_class = EmailVerificationSerializer
token_param_config = openapi.Parameter(
'token', in_=openapi.IN_QUERY, description='Description', type=openapi.TYPE_STRING)
@swagger_auto_schema(manual_parameters=[token_param_config])
def get(self, request):
token = request.GET.get('token')
try:
payload = jwt.decode(token, settings.SECRET_KEY).decode("utf-8")
user = NewUser.objects.get(id = payload['user_id'])
if not user.is_verified:
user.is_verified = True
user.save()
return Response({'email': 'Successfully Activated'}, status=status.HTTP_200_OK)
except jwt.ExpiredSignatureError as identifier:
return Response({'error': 'Activation Expired'}, status=status.HTTP_400_BAD_REQUEST)
except jwt.exceptions.DecodeError as identifier:
return Response({'error': 'Invalid token'}, status=status.HTTP_400_BAD_REQUEST)
class LoginAPIView(generics.GenericAPIView):
permission_classes = [AllowAny]
serializer_class = LoginSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
return Response(serializer.data, status=status.HTTP_200_OK)
</code></pre>
<p><code>serializers</code></p>
<pre><code>from django.contrib import auth
from rest_framework import serializers
from rest_framework.exceptions import AuthenticationFailed
from users.models import NewUser
class RegisterSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=True)
username = serializers.CharField(required=True)
password = serializers.CharField(min_length=8, max_length=68, write_only=True)
class Meta:
model = NewUser
fields = ('email', 'username', 'password','first_name','last_name')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
password = validated_data.pop('password', None)
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
class EmailVerificationSerializer(serializers.ModelSerializer):
token = serializers.CharField(max_length=555)
class Meta:
model = NewUser
fields = ['token']
class LoginSerializer(serializers.ModelSerializer):
email = serializers.EmailField(max_length=255, min_length=3)
password = serializers.CharField(max_length=68, min_length=6, write_only=True)
username = serializers.CharField(max_length=255, min_length=3, read_only=True)
tokens = serializers.SerializerMethodField()
def get_tokens(self, obj):
user = NewUser.objects.get(email=obj['email'])
return {
'refresh': user.tokens()['refresh'],
'access': user.tokens()['access']
}
class Meta:
model = NewUser
fields = ['email', 'password', 'username', 'tokens']
def validate(self, attrs):
email = attrs.get('email', '')
password = attrs.get('password', '')
filtered_user_by_email = NewUser.objects.filter(email=email)
user = auth.authenticate(email=email, password=password)
if not user:
raise AuthenticationFailed('Invalid credentials, try again')
if not user.is_active:
raise AuthenticationFailed('Account disabled, contact admin')
if not user.is_verified:
raise AuthenticationFailed('Email is not verified')
return {
'email': user.email,
'username': user.username,
'tokens': user.tokens()
}
return super().validate(attrs)
</code></pre>
<p><code>models</code></p>
<pre><code>from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from rest_framework_simplejwt.tokens import RefreshToken
class NewUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=150, unique=True, db_index=True, default=None)
email = models.EmailField(_('email address'), unique=True)
first_name = models.CharField(max_length=150, blank=True)
last_name = models.CharField(max_length=150, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
#newsletter = models.BooleanField(default=False)
is_verified = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = CustomAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name']
def __str__(self):
return self.email
def tokens(self):
refresh = RefreshToken.for_user(self)
return {
'refresh': str(refresh),
'access': str(refresh.access_token)
}
</code></pre>
<p>Not sure what the problem is, I've tried de-bugging to my extent but now I've hit a wall. Thank you in advance.</p>
<p>EDIT: here is my settings file</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'REFRESH_TOKEN_LIFETIME': timedelta(days=10),
'ROTATE_REFRESH_TOKENS': True,
'BLACKLIST_AFTER_ROTATION': True,
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'VERIFYING_KEY': None,
'AUTH_HEADER_TYPES': ('JWT',),
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
}
</code></pre>
<p>project <code>urls.py</code></p>
<pre><code>
urlpatterns = [
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
path('admin/', admin.site.urls),
path('api/', include('bucket_api.urls', namespace='bucket_api')),
path('auth/', include('users.urls')),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path('', include('bucket.urls', namespace='bucket')),
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]
</code></pre>
<p>app <code>urls.py</code>:</p>
<pre><code>urlpatterns = [
path('register/', CustomUserCreate.as_view(), name="register"),
path('login/', LoginAPIView.as_view(), name="login"),
path('email-verify/', VerifyEmail.as_view(), name="email-verify"),
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
#path('logout/blacklist/', BlacklistTokenUpdateView.as_view(), name='blacklist'),
]
</code></pre>
<p>according to jwt.io , my token should be valid...</p>
|
<p>Okay, I finally managed to solve the error. First and foremost, when you are debugging, it will help commenting out <code>exceptions</code> to view the actual errors. I should of known this but I was stubborn in my methods...</p>
<p>Anyways, you have to state the type of algorithm the JWT was generated in when using <code>JWT.decode</code>. As you see, here is my new payload, with the added <code>HS256</code> algo.
<code>payload = jwt.decode(token, settings.SECRET_KEY, algorithms='HS256')</code></p>
<p>Hope this helps you in the future!</p>
|
python|django|django-rest-framework|jwt
| 2 |
1,902,017 | 65,561,436 |
Pylance not working in VSCode Jupyter notebooks
|
<p>Pylance works for <code>.py</code> files:</p>
<p><img src="https://i.imgur.com/Zf4u8h4.png" alt=".py with pylance" /></p>
<p>But doesn't work with Jupyter <code>.ipynb</code> notebooks:</p>
<p><img src="https://i.imgur.com/1MeTjuK.png" alt=".ipynb with pylance" /></p>
<p>I tried saving the <code>.ipynb</code> - same issue.</p>
<p>How can enable Pylance warnings in my notebooks?</p>
|
<p>It seems that the Jupyter extension doesn't support Pylance.</p>
<p>I submitted this issue to address this shortcoming:</p>
<p><a href="https://github.com/microsoft/vscode-jupyter/issues/4307" rel="noreferrer">Pylance / Language server support #4307</a></p>
|
python|visual-studio-code|jupyter-notebook|pylance
| 8 |
1,902,018 | 50,248,876 |
Python / Selenium - How to get the proper xpath for an html
|
<p>From couple of days I am trying to find out what is the proper XPATH for the button on the website.</p>
<p><a href="https://i.stack.imgur.com/KKJIX.jpg" rel="nofollow noreferrer">enter image description here</a></p>
<p>This is the html code of the button:</p>
<pre><code><div class="rc_library_element_name rc_actionable ia-inline-block" href="reporteditor.phtml?.op=3277&amp;.cr=._%21Mqxtjfi_SFjudmo_SWfssuv&amp;.sess=8Otpr5-9Bz_wpGJTXqAEAPTCP7GkYg..&amp;.done=WvKqgMCoA3IAAEf5xL0AAAAK8">Invoice Detail Report</div>
</code></pre>
<p>I have tried a few methods, such as:</p>
<pre><code>invoice_detail_report = wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[2]/div[2]/div[2]/div[2]/div/div[2]/div[5]/div[2]/div[17]/table/tbody/tr/td[2]/div[1]')))
</code></pre>
<p>or</p>
<pre><code>invoice_detail_report = wait.until(EC.element_to_be_clickable((By.XPATH, '//DIV[@class="rc_library_element_name rc_actionable ia-inline-block"][text()="Invoice Detail Report"]')))
</code></pre>
<p>Unfortunately none of these worked out.</p>
<p>Could you please advise what is the proper xpath for that button?</p>
<p>Thank you very much for your help,</p>
<p>Greetings.</p>
|
<p>You can use this Xpath :</p>
<pre><code>//div[contains(text(),'Invoice Detail Report')]
</code></pre>
<p>or </p>
<pre><code>//div[contains(@href,'reporteditor.phtml')]
</code></pre>
<p>or </p>
<p>this cssSelector : </p>
<pre><code>div[href^='reporteditor.phtml']
</code></pre>
|
python|selenium|selenium-webdriver|xpath|webdriver
| 0 |
1,902,019 | 50,668,216 |
Data passed by POST between angular and python flask is empty
|
<p>I am trying to create a 'pipe' between an angular frontend and a python flask backend. I have managed to communicate from the former to the latter by <code>HttpClient.get</code> calls but updating that to <code>HttpClient.post</code> breaks the communication. My code looks like:</p>
<ul>
<li><p>on the Angular side:</p>
<pre><code>let request =
this.HttpClient.post(`http://127.0.0.1:5000/weather/loc`,
{
"location": this.location,
})
request.subscribe((data) => {
console.log(data); })
</code></pre></li>
</ul>
<p>and on the flask side:</p>
<pre><code>@app.route('/weather/loc', methods=["POST"])
def weather_connection():
print( request.form)
location = request.form.get("location", default="London")
#more code
</code></pre>
<p>The problem I see is that <code>request.form</code> is always <code>ImmutableMultiDict([])</code> an empty dictionary. For some reason the <code>location</code> argument seems to have been lost somewhere.</p>
|
<p>Angular's HttpClient posts data in JSON format. But Flask's <code>request.data</code> is only for data that is form-encoded. Instead, you should use <code>request.get_json()</code>.</p>
|
python|angular|post
| 1 |
1,902,020 | 50,370,433 |
Why does Pandas incorrectly evaluate the week count of the last day of the year?
|
<pre><code>import pandas as pd
t1 = pd.Timestamp('2018-01-01')
print(t1.week)
t364 = pd.Timestamp('2018-12-30')
print(t364.week)
t365 = pd.Timestamp('2018-12-31')
print(t365.week)
</code></pre>
<p>Output:</p>
<pre><code>1
52
1
</code></pre>
<p>If you relying on week number as input it seriously screws your count ifs, max ifs etc.</p>
|
<p>As per @zeeMonkeez's comment, <code>pandas</code> uses <a href="https://en.wikipedia.org/wiki/ISO_week_date" rel="nofollow noreferrer">ISO week date conventions</a>.</p>
<p>A workaround is to convert to <code>datetime</code>, extract days from start of year, then divide by 7:</p>
<pre><code>import pandas as pd
from math import ceil
def weeker(x):
return ceil(x.to_pydatetime().timetuple().tm_yday / 7)
t1 = pd.Timestamp('2018-01-01')
print(t1.week, weeker(t1)) # 1 1
t364 = pd.Timestamp('2018-12-30')
print(t364.week, weeker(t364)) # 52 52
t365 = pd.Timestamp('2018-12-31')
print(t365.week, weeker(t365)) # 1 53
</code></pre>
|
python|python-3.x|pandas|datetime
| 1 |
1,902,021 | 35,080,416 |
How can I pass single options to push/pull of gitpython?
|
<p>The signature of many <code>Repo</code>-functions includes <code>**kwargs</code>, of which the documentation says, that you can pass arguments to the underlying wrapped git command. However, there is no place for <code>*args</code>. In order to pass flag-like arguments like <code>--all</code>. I would have expected them to be passed like <code>my_remote.pull('all')</code>. So, for instance, how would you pass <code>--all</code> to the pull function of <code>Remote</code>?</p>
|
<p>The correct way to do this is to pass <code><argument>=True</code> as part of the <code>**kwargs</code>. So, in the special case, this would be <code>my_remote.pull(all=True)</code>.</p>
|
python|gitpython
| 3 |
1,902,022 | 34,990,170 |
Does urllib in python support interaction with text boxes and buttons on a webpage? If not , are there any modules that support this?
|
<p>I cant seem to find out how to put text into a text box on a webpage then activate a button. I've tryed seeing if urllib supports this but I've noticed it only supports reading and not writing. So are there any modules that support writing in a text box and activation of buttons on a webpage using python?</p>
|
<p>Yes, the solution you're looking for is called <a href="http://docs.seleniumhq.org/docs/03_webdriver.jsp" rel="nofollow">Selenium WebDriver</a>, which has a <a href="https://pypi.python.org/pypi/selenium" rel="nofollow">python binding</a> to work interactively with web pages. You can use a variety of browser clients with WebDriver, including FireFox, Chrome, and IE, along with my favorite: <a href="http://phantomjs.org/" rel="nofollow">PhantomJS</a> which is a headless browser that works great with server apps.</p>
<p>See the article on <a href="https://realpython.com/blog/python/headless-selenium-testing-with-python-and-phantomjs/" rel="nofollow">https://realpython.com/blog/python/headless-selenium-testing-with-python-and-phantomjs/</a> for a quick introduction.</p>
|
python|web-services
| 1 |
1,902,023 | 44,903,755 |
Tkinter - How to use option 'foreground' for some text in Entry widget?
|
<p>Here is my code:</p>
<pre><code>from tkinter import *
root = Tk()
root.title("Punctured Convolution Encoder dan Viterbi Decoder")
root.geometry("1350x655+0+0")
frame_input = LabelFrame(root, text="Input")
frame_input.place(x=20, y=10, width=400, height=200)
# input#
lbl_in = Label(frame_input, text="Input", font=("Arial", 16))
lbl_in.place(x=10, y=20)
bin_in = Entry(frame_input, font=('Gill Sans MT', 16))
bin_in.place(x=130, y=20, width=240)
def klik_proses():
bin_in.selection_range(1,2)
bin_in.config(foreground="red")
bin_in.selection_range(4,5)
bin_in.config(foreground="red")
btn_proses = Button(frame_input, text="test", width=12, command=klik_proses)
btn_proses.place(x=140, y=100)
root.mainloop()
</code></pre>
<p>The result is the color of the whole text in entry widget was changed, when I pressed the button.
How can I change color for some text in the entry widget?</p>
<p>e.g:
I enter <code>123456789</code> in the entry box, then I want to change text color for number <code>2</code> and <code>5</code>.
So, there are 2 numbers have red color and the others have black color. </p>
|
<p>It is not possible to change the color of only part of the text in an Entry, but it is possible in a Text widget using tags. So I suggest you to create a one line Text widget.</p>
<p>Here is an example:</p>
<pre><code>import tkinter as tk
def change_color():
entry.tag_add('red', '1.1')
entry.tag_add('red', '1.4')
root = tk.Tk()
entry = tk.Text(root, height=1, width=20)
entry.tag_configure('red', foreground='red')
entry.bind('<Return>', lambda e: "break") # prevent newlines
entry.insert('1.0', '123456789')
entry.pack()
tk.Button(root, text='Change color', command=change_color).pack()
root.mainloop()
</code></pre>
<p>You can find more information about the Text widget on <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/text.html" rel="nofollow noreferrer">this website</a> .</p>
|
python-3.x|tkinter|widget|foreground|tkinter-entry
| 2 |
1,902,024 | 45,164,246 |
Strange subprocess behavior
|
<pre><code>subprocess.call(["find", ".", "-exec", "sh", "-c", "echo testFirst", ";"])
subprocess.call(["find", ".", "-exec", "sh", "-c", "echo testSecond", ";"], shell=True)
subprocess.call(["find . -exec sh -c 'echo testThird' \\;"], shell=True)
subprocess.call(["find", ".", "-exec", "sh", "-c", "touch testFirst", ";"])
subprocess.call(["find", ".", "-exec", "sh", "-c", "touch testSecond", ";"], shell=True)
subprocess.call(["find . -exec sh -c 'touch testThird' \\;"], shell=True)
</code></pre>
<p>The following outputs:</p>
<pre><code>testFirst
testFirst
testFirst
.
./test.py
./data
testThird
testThird
testThird
.
./test.py
./testFirst
./data
</code></pre>
<p>And only <code>testFirst</code> and <code>testThird</code> files are created.</p>
<p>What is the explanation of the behaviour?</p>
<p>I would assume output of <code>testFirst</code>, <code>testSecond</code>, <code>testThird</code> as well as the three files being created.</p>
|
<p><a href="https://stackoverflow.com/a/10661488/1663462">https://stackoverflow.com/a/10661488/1663462</a></p>
<blockquote>
<p>When you pass shell=True, Popen expects a single string argument, not
a list.</p>
</blockquote>
<p>...........</p>
|
python|subprocess
| 0 |
1,902,025 | 45,016,766 |
I want to create a simple movie recommendation system with Y(i,j)=ith movie rated by jth user and R(i,j)=1 if a movie has been rated ,else r(i,j)=0
|
<pre><code>import tensorflow as tf
import pymatlab as mat
import numpy as np
import matplotlib.pyplot as plt
import scipy.io
mat=scipy.io.loadmat('ex8_movies.mat')
Y=mat['Y']
R=mat['R']
plt.interactive(False)
#plt.plot(Y)
#plt.show()
print(Y[R==1])
#print(Y[R==0])
r=tf.constant(R,dtype=tf.float32)
params=scipy.io.loadmat('ex8_movieParams.mat')
num_users = params['num_users']
num_movies =params['num_movies']
num_features=params['num_features']
print("shape of Y:",np.shape(Y))
print(num_users)
print(num_movies)
x=np.random.rand(1682,2)
X=tf.placeholder(tf.float32,([1682 ,2]))
#X=tf.Variable(tf.zeros([1682,943]),dtype=tf.float32)
thetas=tf.Variable(tf.zeros([943,2]),dtype=tf.float32)
y=tf.placeholder(tf.float32,[1682 ,943])
sess=tf.InteractiveSession()
init = tf.global_variables_initializer()
sess.run(init)
#print((np.transpose(thetas)))
j_temp=tf.square(tf.matmul(X,tf.transpose(thetas))- y)
j_temp=j_temp([R==1])
cost=tf.reduce_mean(tf.reduce_sum(j_temp))
optimizer=tf.train.GradientDescentOptimizer(0.09).minimize(cost)
sess.run(j_temp,{X:x,y:Y})
#sess.run(j_tmp)
sess.run(cost)
print("slodvhbdfh\n\n")
print(Y[R==0])
</code></pre>
<p>I want to create a simple movie recommendation system with Y(i,j)=ith movie rated by jth user and R(i,j)=1 if a movie has been rated ,else r(i,j)=0
I am getting the error:</p>
<pre><code>"C:\Python\python interpreter\pythonw.exe" C:/Python/Projects/recommend.py
[5 4 4 ..., 2 3 3]
shape of Y: (1682, 943)
[[943]]
[[1682]]
File "C:/Python/Projects/recommend.py", line 38, in <module>
j_temp=j_temp([R==1])
TypeError: 'Tensor' object is not callable
Process finished with exit code 1
</code></pre>
|
<p><code>identifier(arguments)</code> is the Python syntax for calling a function. You tried to do this with a tensor, which is <em>not</em> a function -- you can't call it. What are you trying to do? I can't tell, since you provided no description in text, comments, or even useful variable names.</p>
<p>In addition, the construct `[R==1]' is not legal Python. If you're trying to get all rated movies for that user, you need to review the syntax to apply a filter to a tensor. Those keywords should lead you to an answer.</p>
|
python|numpy|machine-learning|tensorflow|tensor
| 1 |
1,902,026 | 64,906,496 |
Searching for a string value in a list
|
<p>My list is a=['Name','Age','Subject'] and I want to search whether an input by the user exists in this list or not.</p>
<p>Let's say the user enters x='name', how do I search for x in this list a (case-insensitively)?</p>
|
<p>I think the following code might help you. You have to <code>string</code> modification methods <code>lower()/upper()</code>. I used lower here, it changes any case of each character to lower case. e.g. after using <code>'NaMe'.lower()</code> to <code>NaMe</code>changed to `'name''. I changed both the input string and list elements and checked whether the input is in the list. That's all.</p>
<p><strong>Code</strong></p>
<pre><code>a=['Name','Age','Subject']
a = [a.lower() for a in a]
user_input = input("Put the input: ").lower()
if user_input in a:
print("Match")
else:
print("Mismatch")
</code></pre>
<p><strong>Output</strong></p>
<pre><code>> Put the input: AGE
> Match
</code></pre>
|
python|string|list|search
| 0 |
1,902,027 | 61,228,530 |
How can I bypass the Attribute error: 'None'?
|
<p>I have this body of code where I am trying to extract the text from the th and td tags. </p>
<pre><code>d = urllib.request.urlopen(url).read()
soup = bs(d,'lxml')
find_tr = soup.find_all('tr') #Iterates through 'tr'
for i in find_tr:
for j in i.find_all('th'): #iterates through 'th' tags in the 'tr'
if j is not None:
print(j.th.text)
for k in i.find_all('td'): #iterates through 'td' tags in 'tr'
if k is not None:
print(k.td.text)
</code></pre>
<p>After running, I keep getting this error:</p>
<pre><code>
AttributeError: 'NoneType' object has no attribute 'text'
</code></pre>
<p>How do I fix this?</p>
|
<p>Use try except on attribute error to step over none issues:</p>
<pre><code>for i in find_tr:
for j in i.find_all('th'): #iterates through 'th' tags in the 'tr'
try:
print(j.th.text)
except AttributeError:
continue
for k in i.find_all('td'): #iterates through 'td' tags in 'tr'
try:
print(k.td.text)
except AttributeError:
continue
</code></pre>
|
python|html|url|web-scraping|beautifulsoup
| 1 |
1,902,028 | 57,830,130 |
How do I convert this histogram into a dot plot/dot chart using matplotlib and numpy?
|
<p>I'm trying to create a dot plot/dot chart based on students' hours of sleep, but the closest I was able to get was a histogram which matched my data. The method I tried which will be provided below didn't work for me either due to my sheer inexperience or incompatibility with my data. Any help would be greatly appreciated. </p>
<p>I've already tried a similar answer which was this: <a href="https://stackoverflow.com/questions/49703938/how-to-create-a-dot-plot-in-matplotlib-not-a-scatter-plot">How to create a "dot plot" in Matplotlib? (not a scatter plot)</a> </p>
<p>This method rounded the float values in hours of sleep up, which was making the plot incorrect, or perhaps I was just using it wrong. I would appreciate a solution using my exact example, because I'm still pretty new to programming and likely won't understand much else. </p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
hours_of_sleep = [9, 6 ,8, 6, 8, 8, 6, 6.5, 6, 7, 9, 4, 3, 4, 5, 6, 11, 6, 3, 6, 6, 10, 7, 8, 4.5, 9, 7, 7]
bin_list = []
for number in hours_of_sleep:
if number not in bin_list:
bin_list.append(number)
bin_list.sort()
item_1 = bin_list[0]
item_2 = bin_list[-1]
proper_bin = np.arange(item_1, item_2+1, 0.5)
plt.hist([hours_of_sleep], bins=proper_bin, rwidth= 0.8)
plt.title('Hours of Sleep for Students')
plt.show()
</code></pre>
<p>I want to end up with something similar to the dot plot example provided by the user who asked the question in the link I've already provided.</p>
|
<p>I feel that this answers your question: <a href="https://stackoverflow.com/questions/49703938/how-to-create-a-dot-plot-in-matplotlib-not-a-scatter-plot">How to create a "dot plot" in Matplotlib? (not a scatter plot)</a><br/></p>
<p>I'm using more or less the same method.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
hours_of_sleep = [9, 6 ,8, 6, 8, 8, 6, 6.5, 6, 7, 9, 4, 3, 4, 5, 6, 11, 6, 3, 6, 6, 10, 7, 8, 4.5, 9, 7, 7]
bins = np.arange(0, max(hours_of_sleep) + 1, 0.5)
hist, edges = np.histogram(hours_of_sleep, bins=bins)
y = np.arange(1, hist.max() + 1)
x = np.arange(0, max(hours_of_sleep) + 0.5, 0.5)
X,Y = np.meshgrid(x,y)
plt.scatter(X, Y, c = Y<=hist, cmap="Blues")
plt.xticks(np.arange(max(hours_of_sleep) + 2))
plt.yticks([])
plt.title('Hours of Sleep for Students')
plt.show()
</code></pre>
<br/>
<h2>Alternative Method</h2>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
hours_of_sleep = [9, 6 ,8, 6, 8, 8, 6, 6.5, 6, 7, 9, 4, 3, 4, 5, 6, 11, 6, 3, 6, 6, 10, 7, 8, 4.5, 9, 7, 7]
bins = np.arange(0, max(hours_of_sleep) + 1, 0.5)
hist, edges = np.histogram(hours_of_sleep, bins=bins)
y = np.arange(1, hist.max() + 1)
x = np.arange(0, max(hours_of_sleep) + 0.5, 0.5)
X,Y = np.meshgrid(x,y)
Y = Y.astype(np.float)
Y[Y>hist] = None
plt.scatter(X, Y)
plt.xticks(np.arange(max(hours_of_sleep) + 2))
plt.yticks([])
plt.title('Hours of Sleep for Students')
plt.show()
</code></pre>
<p>Hope this helps. :)<br/>
Reading some <a href="https://matplotlib.org/3.1.1/index.html" rel="nofollow noreferrer">Matplotlib Documentations</a> will help you too.</p>
|
python|matplotlib|plot|histogram|dot
| 2 |
1,902,029 | 57,780,512 |
How to filter timestamps within a custom interval starting at the index on a condition?
|
<p>I'm trying to filter rows within 5 minutes of the timestamp following each "True" condition, including the timestamp of the "True" condition. I've come up with a solution using a for loop but it can be rather slow with a large amount of data so I'm curious if there's a faster solution.</p>
<pre class="lang-py prettyprint-override"><code>time,cond
2019-08-03 21:44:15.924000+00:00,False
2019-08-03 21:45:15.924000+00:00,False
2019-08-03 22:21:15.937000+00:00,False
2019-08-03 22:26:15.937000+00:00,False
2019-08-03 22:33:15.946000+00:00,False
2019-08-03 22:42:15.939000+00:00,False
2019-08-03 22:44:15.948000+00:00,False
2019-08-03 22:45:15.955000+00:00,True
2019-08-03 22:46:15.949000+00:00,False
2019-08-03 23:01:15.932000+00:00,False
2019-08-03 23:08:15.933000+00:00,False
2019-08-03 23:17:15.957000+00:00,False
2019-08-03 23:45:15.952000+00:00,False
2019-08-03 23:46:15.943000+00:00,False
2019-08-03 23:52:15.943000+00:00,False
2019-08-03 23:54:15.952000+00:00,False
2019-08-04 00:05:15.929000+00:00,False
2019-08-04 00:29:15.944000+00:00,False
2019-08-04 00:45:15.956000+00:00,False
2019-08-04 00:46:15.939000+00:00,True
2019-08-04 00:47:15.955000+00:00,False
2019-08-04 01:00:15.956000+00:00,False
2019-08-04 01:02:15.943000+00:00,False
</code></pre>
<pre class="lang-py prettyprint-override"><code>for i in x[x.cond].index.to_list():
x.loc[(x.time >= x.iloc[i].time) & (x.time <= (x.iloc[i].time + pd.Timedelta('5min'))), 'cond'] = True
</code></pre>
<p>This is the expected output. The 'cond' column updated to true if it falls within 5 minutes of the timestamp of the original "True" condition timestamp. I've tried a few other solutions but to no avail. Any help is much appreciated.</p>
<pre class="lang-py prettyprint-override"><code>time,cond
2019-08-03 21:44:15.924000+00:00,False
2019-08-03 21:45:15.924000+00:00,False
2019-08-03 22:21:15.937000+00:00,False
2019-08-03 22:26:15.937000+00:00,False
2019-08-03 22:33:15.946000+00:00,False
2019-08-03 22:42:15.939000+00:00,False
2019-08-03 22:44:15.948000+00:00,False
2019-08-03 22:45:15.955000+00:00,True
2019-08-03 22:46:15.949000+00:00,True
2019-08-03 23:01:15.932000+00:00,False
2019-08-03 23:08:15.933000+00:00,False
2019-08-03 23:17:15.957000+00:00,False
2019-08-03 23:45:15.952000+00:00,False
2019-08-03 23:46:15.943000+00:00,False
2019-08-03 23:52:15.943000+00:00,False
2019-08-03 23:54:15.952000+00:00,False
2019-08-04 00:05:15.929000+00:00,False
2019-08-04 00:29:15.944000+00:00,False
2019-08-04 00:45:15.956000+00:00,False
2019-08-04 00:46:15.939000+00:00,True
2019-08-04 00:47:15.955000+00:00,True
2019-08-04 01:00:15.956000+00:00,False
2019-08-04 01:02:15.943000+00:00,False
</code></pre>
|
<p>I agree, iterating over rows in Pandas is not very efficient. I'm suggesting this solution, which avoids iterating all rows and takes advantage of Pandas capabilities. I think it is quite explicit and you wont have problems to understand/improve it, you may be able to avoid the short loop I left. I hope this helps as a starting point.</p>
<pre><code>import pandas as pd
import datetime
mins = 5
data = pd.read_csv('data.csv', sep=',', skiprows=1, header=None, names=['datetime', 'stamp'])
data['datetime'] = pd.to_datetime(data['datetime'])
print(data)
g = data.groupby('stamp')
for i, r in g.get_group(True).iterrows():
data.loc[(data['datetime'] > r['datetime']) & (data['datetime'] < r['datetime'] + datetime.timedelta(0, 60 * mins)), 'stamp'] = True
print(data)
</code></pre>
|
python|pandas|numpy
| 0 |
1,902,030 | 56,075,479 |
GenericForeignKey in Grappelli admin: filter content_type to display only relevant models
|
<p>With <a href="https://django-grappelli.readthedocs.io/en/autocomplete/customization.html#related-lookups" rel="nofollow noreferrer">related lookups</a>, I can easily get access to all the models I have to have a generic foreign key. Obviously, this is not what I want to do. I want to restrict it to just a sub set of the models I have -- specifically all the inherit from the abstract model <code>Registry</code>.</p>
<p>My models look like thus:</p>
<pre><code>class Registry(models.Model):
"""A base registry class."""
number = models.BigAutoField(primary_key=True)
when = models.DateField(default=timezone.now)
title = models.CharField(
max_length=1024, default='', blank=True, null=True)
class Meta:
"""The meta class."""
abstract = True
[…]
class Revision(models.Model):
"""A revision model."""
when = models.DateTimeField(default=timezone.now)
identification = models.BigIntegerField()
content_type = models.ForeignKey(
ContentType, on_delete=models.CASCADE, related_name='+')
object_id = models.PositiveIntegerField()
parent = GenericForeignKey('content_type', 'object_id')
[…]
class Document(Registry):
[…]
class Drawing(Registry):
[…]
</code></pre>
<p>So that each <code>Registry</code> derived instances can have many different revisions.</p>
<p>And the relevant admin:</p>
<pre><code>class RevisionAdmin(admin.ModelAdmin):
"""Revision administration definition."""
fieldsets = [
('Revision', {
'fields': [
'when',
'identification',
]
}),
('Registry', {
'classes': ('grp-collapse grp-open',),
'fields': ('content_type', 'object_id', )
}),
]
</code></pre>
|
<p>You can use a <a href="https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to" rel="nofollow noreferrer"><strong><code>limit_choices_to</code></strong> [Django-doc]</a>. Since you want to limit the choices to the <em>descendants</em>, we will need to write some extra logic to calculate these first:</p>
<p>We can for example first calculate all the subclasses with <a href="https://stackoverflow.com/a/52853645/67579">this function</a>:</p>
<blockquote>
<pre><code>def get_descendants(klass):
gen = { klass }
desc = set()
while gen:
gen = { skls for kls in gen for skls in kls.__subclasses__() }
desc.update(gen)
return desc
</code></pre>
</blockquote>
<p>Now we can define a callable to obtain the primary keys of the <code>ContentType</code>s that are subclasses of a class, in this case <code>Registry</code>:</p>
<pre><code>from django.db.models import Q
from django.contrib.contenttypes.models import ContentType
def filter_qs():
if not hasattr(filter_qs_registry, '_q'):
models = get_descendants(<b>Registry</b>)
pks = [v.pk for v in ContentType.objects.get_for_models(*models).values()]
filter_qs_registry._q = Q(pk__in=pks)
return filter_qs_registry._q</code></pre>
<p>In the <code>ForeignKey</code> to the <code>ContentType</code>, we can then use the <code>limited_choices_to</code> field:</p>
<pre><code>class Revision(models.Model):
"""A revision model."""
when = models.DateTimeField(default=timezone.now)
identification = models.BigIntegerField()
content_type = models.ForeignKey(
ContentType,
on_delete=models.CASCADE,
<b>limit_choices_to=filter_qs_registry</b>,
related_name='+'
)
object_id = models.PositiveIntegerField()
parent = GenericForeignKey('content_type', 'object_id')</code></pre>
<h1>Variable number of <em>ascents</em></h1>
<p>We can generalize the number of ascents, by generalizing for example the <code>get_descendants</code> function:</p>
<blockquote>
<pre><code>def get_descendants(*klass):
gen = { *klass }
desc = set()
while gen:
gen = { skls for kls in gen for skls in kls.__subclasses__() }
desc.update(gen)
return desc
</code></pre>
</blockquote>
<p>Next we can simply call it with:</p>
<pre><code>from django.db.models import Q
from django.contrib.contenttypes.models import ContentType
def filter_qs():
if not hasattr(filter_qs_registry, '_q'):
models = get_descendants(<b>Registry, OtherAbstractModel</b>)
pks = [v.pk for v in ContentType.objects.get_for_models(*models).values()]
filter_qs_registry._q = Q(pk__in=pks)
return filter_qs_registry._q</code></pre>
|
django|python-3.x|django-grappelli
| 2 |
1,902,031 | 71,699,387 |
Module import fails for unknow reason
|
<p>Today I tried to make a project where I need to use <code>import random</code>, but when I use it, its imports not library but only function random, and I get alert: <code>NameError: name 'randint' is not defined</code>.</p>
<p>My code looks like:</p>
<pre><code>import random
randomList = []
def randoming() :
for i in range(8) :
randomNum = randint(2, 8)
randomList.append(randomNum)
randoming()
def sixCounter() :
sixNums = 0
for a in range(8) :
if randomList[a] == 6 :
sixNums = sixNums + 1
print(f"In that list are {sixNums} six numbers")
print("The numbers in list are:")
print(*randomList, sep = ", ")
sixCounter()
</code></pre>
|
<p>You either need to reference randint as random.randin or import randint from random</p>
<p>i.e. either:</p>
<pre><code>from random import randint
randomList = []
def randoming() :
for i in range(8) :
randomNum = randint(2, 8)
randomList.append(randomNum)
randoming()
def sixCounter() :
sixNums = 0
for a in range(8) :
if randomList[a] == 6 :
sixNums = sixNums + 1
print(f"In that list are {sixNums} six numbers")
print("The numbers in list are:")
print(*randomList, sep = ", ")
sixCounter()
</code></pre>
<p>or</p>
<pre><code>import random
randomList = []
def randoming() :
for i in range(8) :
randomNum = random.randint(2, 8)
randomList.append(randomNum)
randoming()
def sixCounter() :
sixNums = 0
for a in range(8) :
if randomList[a] == 6 :
sixNums = sixNums + 1
print(f"In that list are {sixNums} six numbers")
print("The numbers in list are:")
print(*randomList, sep = ", ")
sixCounter()
</code></pre>
|
python
| 2 |
1,902,032 | 69,364,742 |
Make dataframe header as rows and row as header
|
<p>I have a dataframe where I want to convert the columns headers into aggregated rows and a column into the header:</p>
<pre class="lang-py prettyprint-override"><code>Athlete Variable 28.0 28.0 28.0 29.0 29.0 29.0
John Minutes 23 32 43 21 43 35
John Distance 23.2 32.7 54.2 24.2 47.8 32.1
John Sprints 5 3 8 3 9 2
Bob Minutes 25 23 43 31 38 23
Bob Distance 32.4 35.6 43.7 21.8 26.8 12.5
Bob Sprints 8 4 8 6 9 2
</code></pre>
<p>Desired dataframe:</p>
<pre class="lang-py prettyprint-override"><code>Athlete week Minutes Distance Sprints
John 28 98 110.1 16
John 29 99 104.1 14
Bob 28 91 111.7 20
Bob 29 92 61.1 17
</code></pre>
|
<p>You’re looking for <a href="https://pandas.pydata.org/pandas-docs/version/1.2.0/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>pivot_table</code></a>, but you’ll need to <a href="https://pandas.pydata.org/pandas-docs/version/1.2.0/reference/api/pandas.melt.html" rel="nofollow noreferrer"><code>melt</code></a> the dataframe to a mono-dimensional format first:</p>
<pre><code>>>> data = df.melt(id_vars=['Athlete', 'Variable'], var_name='week')
>>> data
Athlete Variable week value
0 John Minutes 28.0 23.0
1 John Distance 28.0 23.2
2 John Sprints 28.0 5.0
3 Bob Minutes 28.0 25.0
4 Bob Distance 28.0 32.4
5 Bob Sprints 28.0 8.0
6 John Minutes 28.0 32.0
7 John Distance 28.0 32.7
8 John Sprints 28.0 3.0
9 Bob Minutes 28.0 23.0
10 Bob Distance 28.0 35.6
11 Bob Sprints 28.0 4.0
12 John Minutes 28.0 43.0
13 John Distance 28.0 54.2
14 John Sprints 28.0 8.0
15 Bob Minutes 28.0 43.0
16 Bob Distance 28.0 43.7
17 Bob Sprints 28.0 8.0
18 John Minutes 29.0 21.0
19 John Distance 29.0 24.2
20 John Sprints 29.0 3.0
21 Bob Minutes 29.0 31.0
22 Bob Distance 29.0 21.8
23 Bob Sprints 29.0 6.0
24 John Minutes 29.0 43.0
25 John Distance 29.0 47.8
26 John Sprints 29.0 9.0
27 Bob Minutes 29.0 38.0
28 Bob Distance 29.0 26.8
29 Bob Sprints 29.0 9.0
30 John Minutes 29.0 35.0
31 John Distance 29.0 32.1
32 John Sprints 29.0 2.0
33 Bob Minutes 29.0 23.0
34 Bob Distance 29.0 12.5
35 Bob Sprints 29.0 2.0
</code></pre>
<p>So using pivot_table, you have to specify the aggregation function, here we use <code>sum</code>, the default being <code>mean</code>:</p>
<pre><code>>>> data.pivot_table(index=['Athlete', 'week'], columns='Variable', values='value', aggfunc='sum')
Variable Distance Minutes Sprints
Athlete week
Bob 28.0 111.7 91.0 20.0
29.0 61.1 92.0 17.0
John 28.0 110.1 98.0 16.0
29.0 104.1 99.0 14.0
</code></pre>
|
python|pandas|dataframe
| 1 |
1,902,033 | 55,561,043 |
TF Object Detection API Mixed Precision
|
<p>I'm using the TensorFlow Object Detection API for training a detection model on a V100 GPU. Since it has tensor cores available, is there any config flag / kwarg available to turn on mixed precision training? Not sure if this is a current feature or not. Something similar to <code>model_main.py --mixed</code> would be awesome if it exists.</p>
|
<p>Yesterday (May 16th) Nvidia showcased Automatic Mixed Precision, which greatly eases the implementation of this feature, lowering the effort massively: add one line of code and voilá!!!. </p>
<p>It seems the webcast was recorded and will be available on demand, here the links meanwhile:</p>
<p><a href="https://developer.nvidia.com/automatic-mixed-precision" rel="nofollow noreferrer">https://developer.nvidia.com/automatic-mixed-precision</a></p>
<p><a href="https://devblogs.nvidia.com/nvidia-automatic-mixed-precision-tensorflow/" rel="nofollow noreferrer">https://devblogs.nvidia.com/nvidia-automatic-mixed-precision-tensorflow/</a></p>
<p>Also talks about strategies, tools and things to avoid when implementing MP/AMP.</p>
<p>There is an excellent paper that talks about an implementation (among other things) of Mixed Precision. I've prepared this 4-min video that summarizes the research "Supercharging AI with high performance distributed computing"</p>
<p><a href="http://youtu.be/JvssZESVcjI" rel="nofollow noreferrer">http://youtu.be/JvssZESVcjI</a>)</p>
<p>BTW, according to Nvidia MP can be effectively implemented on Volta and Turing GPUs (i.e. Google Collab uses Voltas V100!) and AMP (Automatic Mixed Precision is integrated on TF1.14)</p>
|
tensorflow|precision|object-detection-api|mixed
| 0 |
1,902,034 | 55,219,538 |
sum list object value with same code in python
|
<p>I am a beginner in python, I have faced some problem. I have an object list like this :</p>
<pre><code>[
{
'balance':-32399.0,
'code':u'1011',
'name':u'Stock Valuation Account'
},
{
'balance':-143503.34,
'code':u'1011',
'name':u'Stock Interim Account (Received)'
},
{
'balance':117924.2499995,
'code':u'1011',
'name':u'Stock Interim Account (Delivered)'
},
{
'balance':-3500000.0,
'code':u'1101',
'name':u'Cash'
},
{
'balance':-50000.0,
'code':u'1101',
'name':u'Other Cash'
},
]
</code></pre>
<p>I need to sum it based on the code, so the result will be.</p>
<pre><code>[
{
'balance':6819,91,
'code':u'1011',
},
{
'balance':-3550000.0,
'code':u'1101',
},
]
</code></pre>
<p>have search over StackOverflow, but still not got what I need.
any help?...</p>
|
<p>Exactly, using <code>groupby</code> and <code>sum</code> within some <code>comprehensions</code>:
As said in the comments, for using groupby the list need to be presorted.
In addition you can use <code>operator.attrgetter</code> instead of lambdas in the <code>key</code> parameters of <code>sorted</code> and <code>groupby</code>.</p>
<pre><code>l = [
{
'balance':-32399.0,
'code':u'1011',
'name':u'Stock Valuation Account'
},
...
]
from itertools import groupby
import operator
selector_func = operator.attrgetter("code")
l = sorted(l, key=selector_func)
result = [{"code" : code, "balance" : sum(x["balance"] for x in values)} for code, values in groupby(l, selector_func)]
print(result)
</code></pre>
<p>Result:</p>
<pre><code>[{'code': '1011', 'balance': -57978.0900005}, {'code': '1101', 'balance': -3550000.0}]
</code></pre>
<p>Here you have the <a href="https://repl.it/repls/CuteQuaintWebsites" rel="nofollow noreferrer">live example</a></p>
|
python
| 2 |
1,902,035 | 57,650,356 |
Fetch datetime from strings faster from pandas dataframe
|
<p>Extract day,month,year,hour,weekday,day_month_year from the data and put then in columns</p>
<p>Data columns : </p>
<pre><code>+----------------------+
| Date |
+----------------------+
| '11/28/17 00:36 ' |
| '11/28/17 01:15 AM' |
| 'abc' |
| 11/28/17 01:28 ' |
| 'pqr' |
+----------------------+
</code></pre>
<p>Target:</p>
<pre><code>+-----+-------+------+---------+------+-----------------+
| Day | Month | Year | Weekday | Hour | Day_month_year |
+-----+-------+------+---------+------+-----------------+
| 28 | Nov | 2017 | Tue | 00 | 2017-11-28 |
| 28 | Nov | 2017 | Tue | 01 | 2017-11-28 |
| Nan | Nan | Nan | Nan | Nan | Nan |
| 28 | Nov | 2017 | Tue | 01 | 2017-11-28 |
| Nan | Nan | Nan | Nan | Nan | Nan |
+-----+-------+------+---------+------+-----------------+
</code></pre>
<p>Code: </p>
<pre><code>df['datetime'] = pd.to_datetime(df['Date'],infer_datetime_format=True,errors='coerce')
df['Day'] = df['datetime'].dt.strftime('%d')
df['Month'] = df['datetime'].dt.strftime('%b')
df['Year'] = df['datetime'].dt.strftime('%Y')
df['WeekDay'] = df['datetime'].dt.strftime('%a')
df['Hour'] = df['datetime'].dt.strftime('%H')
df['Day_month_year'] = pd.to_datetime(df['datetime']).dt.to_period('D')
</code></pre>
<p>These lines of code takes long time as my Date column doesn't have a particular data format and has few values which can't be parsed as datetime. Is there a faster way to perform this operation as my Date columns have almost 40k records.</p>
|
<p>Use <code>pd.to_datetime</code>:</p>
<pre><code>s = pd.to_datetime(df['Date'], errors='coerce')
df['Day'] = s.dt.day
df['Month'] = s.dt.month
df['Year'] = s.dt.year
df['Weekday'] = s.dt.strftime('%a')
df['Hour'] = s.dt.hour
df['Day_Month_Year'] = s.dt.date
</code></pre>
<p>Output:</p>
<pre><code> Date Day Month Year Weekday Hour Day_Month_Year
0 11/28/17 00:36 28.0 11.0 2017.0 Tue 0.0 2017-11-28
1 11/28/17 01:15 AM 28.0 11.0 2017.0 Tue 1.0 2017-11-28
2 abc NaN NaN NaN NaT NaN NaT
3 11/28/17 01:28 28.0 11.0 2017.0 Tue 1.0 2017-11-28
4 pqr NaN NaN NaN NaT NaN NaT
</code></pre>
<p>The columns are converted to floats because they have to deal with <code>NaN</code>. They are easy enough to convert to <code>int</code>.</p>
|
python|pandas|datetime|optimization
| 1 |
1,902,036 | 42,212,672 |
Function that takes integer n and prints pi to n digits using string formatting
|
<p>I want to print pi to <code>n</code> decimal places by passing an integer <code>n</code> to the string formatting field. However, this gives me an error. What is the correct way to do this?</p>
<p>My code:</p>
<pre><code>from math import pi
def print_pi(n):
print(("%."+str(n)) % pi)
</code></pre>
<p>The error:</p>
<pre><code>Traceback (most recent call last):
File "1.2.3.py", line 4, in <module>
print_pi(5)
File "1.2.3.py", line 3, in print_pi
print(("%."+str(n)) % pi)
ValueError: incomplete format
</code></pre>
|
<p>You code is missing the type specifier:</p>
<pre><code>from math import pi
import sys
def print_pi(n):
print(("%%.%df" % n) % pi)
print_pi(int(sys.argv[1]))
</code></pre>
|
python|python-3.x|string-formatting
| 3 |
1,902,037 | 54,096,360 |
How to properly use tf.scatter_update for N-Dimensional Updating?
|
<p>I've been trying to make an N-Dimensional update using <code>tf.scatter_update</code> (after <code>tf.scatter_nd</code> was failing due to shape mismatch). In general, these will be used to create masks for filtering slices of an incoming tensor.</p>
<p>Presumption is that input Tensor A is of shape (batch, i, j, k(depth)).
I am only interested in modifying <strong>i,j</strong> values for <strong>all k</strong>, and for <strong>all b</strong>.</p>
<p>MWE:</p>
<pre><code>import tensorflow as tf
b, i, j, k = 64, 128, 128, 256
A = tf.random_uniform(shape=(64, 128, 128, 256), dtype='int32', seed=1234) # Batch, i, j, k
mask = tf.ones(shape=(b,i,j,k), dtype='int32')
# Placeholder for more complicated index Tensor. GPU Ignores OOB indices.
indices = tf.random_uniform(shape=(b, 25, k, 2), dtype='int32', seed=4321) # Index number, k, i-j coord.
updates = tf.random_uniform(shape=(i, j, k), dtype='int32', seed=1111)
scatter = tf.scatter_update(mask, indices, updates)
with tf.Session() as sess:
sess.run(scatter)
</code></pre>
<p>Resulting in:</p>
<blockquote>
<p>AttributeError: 'Tensor' object has no attribute '_lazy_read'</p>
</blockquote>
<p>I have tried this via Python Script, Python Notebook, and with/without Eager Execution. No luck.</p>
<p>Input absolutely must be a tensor, as the idea is to sparsely update this tensor midway through a series of operations.</p>
<p>Is there something fundamental I'm missing regarding <code>tf.scatter_update</code>? Would <code>tf.scatter_nd</code> be more suited? If so, what are the differences, specifically with indices for the updates.</p>
<p>When referencing <a href="https://www.tensorflow.org/api_docs/python/tf/scatter_nd" rel="nofollow noreferrer">tf.scatter_update</a> documentation, the examples are basic and utilise constants; I'm having difficulty applying this to a more realistic situation and problem.</p>
|
<p>Tensorflow's documentation makes use of all the <em>scatter</em> operations (such as scatter_nd_add, etc) by inputing the <em>ref</em> arguments as a <strong>tf.Variable</strong>:</p>
<blockquote>
<p>ref: A mutable Tensor. Must be one of the following types: blablabla. A mutable Tensor. <strong>Should be from a Variable node</strong>.</p>
</blockquote>
<p>I had the same issue and it works fine when used on a tf variable for <em>ref</em>. All the other arguments can remain whatever they are I guess, but I did not investigate thoroughly.</p>
|
python|tensorflow|bitmask
| 1 |
1,902,038 | 58,314,509 |
calling shell script from python where shell connects to database
|
<p>I want to call shell script from python code. The shell script which I am trying to call is having multiple database (DB2) call in it; means it connects to DB2 database multiple times and execute different database sqls. I tried using subprocess.call method like (<code>subprocess.call(['./<shell script with full path>'])</code>); but it seems before the script connects to database and executes the commands mentioned within the script, it is terminating. But when I am calling the shell script as a standalone script from command line, then it is working good.</p>
<p>Is there any other way this can be handled?</p>
|
<blockquote>
<p>subprocess: The subprocess module allows you to spawn new processes,
connect to their input/output/error pipes, and obtain their return
codes.</p>
</blockquote>
<p><a href="http://docs.python.org/library/subprocess.html" rel="nofollow noreferrer">http://docs.python.org/library/subprocess.html</a></p>
<p>Usage:</p>
<pre><code>import subprocess
process = subprocess.Popen(command, shell=True)
process.wait()
print process.returncode
</code></pre>
<p>Side note: It is best practice to avoid using shell=True as it is a security hazard.</p>
<p><a href="https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess">Actual meaning of 'shell=True' in subprocess</a></p>
|
python|bash|shell|db2
| 0 |
1,902,039 | 22,671,704 |
What type should be used for cookies values str or unicode in Python/Google App Engine?
|
<p>What type should be used for cookies values str or unicode in Python/Google App Engine?</p>
<p>This question is trivial but very important - I wan to encrypt binary information into cookies and learn limitation.</p>
<p>After reading some specification I found I should use <a href="http://docs.python.org/2/library/cookie.html" rel="nofollow">http://docs.python.org/2/library/cookie.html</a> - whatever this library allow str and unicode.</p>
<p>Problems start with encoding <strong>binary cookies</strong>:</p>
<p>This code will not work - str can not be unicode</p>
<pre><code>''.join([chr(x) for x in range(256)]).decode('utf8')
</code></pre>
<p>This code will work but what encoding should choosen 'latin1' or 'base64':</p>
<pre><code>''.join([chr(x) for x in range(256)]).decode('latin1')
''.join([chr(x) for x in range(256)]).decode('base64')
</code></pre>
<p>Should I set cookies or headers with only <strong>str</strong> not with <strong>unicode</strong> and not care about encoding?</p>
<p>I will use of course <code>Cookie().value_encode(value)</code> for <strong>str</strong> to follow rfc and browser specific behaviour?</p>
<p>Can you suggest some practical solution?</p>
|
<p>Potentially unreliable links in the cookie chain are HTTP(S) proxy servers, and user agents such as browsers and client applications. Servers send out cookies. These remote programs created in all kinds of computer languages may handle the cookies according to their own concepts of "strings", store the cookies in various file formats, and later return the cookies to the servers. With so many potential failure points the safest option for binary data in cookies must be base64.</p>
|
python|google-app-engine|cookies
| 1 |
1,902,040 | 28,472,572 |
Cron job in google application engine
|
<p>I wrote a Python program to post things to the Internet.there is a function called send(x),with x is the xth record of my post list.I want to call the functions like send(0), send(1),....,with a rate about 5 min/post.How can I implement this task by using the cron configuration? Or task queue?</p>
|
<p>I think I might consider using <a href="https://cloud.google.com/appengine/articles/deferred" rel="nofollow"><code>deferred.defer</code></a> here.</p>
<pre><code>def send_wrapper(value):
send(value)
deferred.defer(send_wrapper, value + 1, _countdown=5*60)
</code></pre>
<p>Now you just need to manage to call this method once (e.g. from a handler) and it will call <code>send</code> every 5 minutes with an incremented value. Underneath it all, this uses the TaskQueue API and pickling to provide a really easy interface for deferred tasks. Neat.</p>
<p>Of course, calling this forever seems a bit strange but it wouldn't be too hard to add logic to terminate the sequence of deferred calls.</p>
<hr>
<p>Your other option is to keep the value in the datastore and use cron... It's a bit more work (and requires a <code>db.Model</code> or <code>ndb.Model</code> that would really only be used for a single entity), but at the end of the day, it's still probably not that hard to implement.</p>
|
python|google-app-engine|cron
| 1 |
1,902,041 | 28,516,572 |
Django complementary external source authentication
|
<p>I'm trying to build a Django website that will be maintained and used by university students mainly. I need to restrict access to a few pages for certain approved students, but it would be very unmaintainable if I needed to create a new Django user for every student that wants to log in. Luckily, the university provides an API to check whether a username/password combination is correct. So I had the idea to create an authentication model complementary to Django's model, where users' university account can get approved by an admin, after which it is a valid login to view certain pages.</p>
<p>So essentially, some users may use a Django account (if they're in charge for the content of the website), and other users may just log in to view some pages with their uni account. For the uni account, the minimum amount of info should be stored (in other words, only the username is really required to approve certain users).</p>
<p>I can't seem to figure out how to build such a system in Django. I cannot use the standard <a href="https://docs.djangoproject.com/en/1.7/ref/contrib/auth/#django.contrib.auth.models.User" rel="nofollow"><code>User</code></a> object because it stores data that is completely redundant, and I cannot <a href="https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#substituting-a-custom-user-model" rel="nofollow">substitute the user model</a> because that would only make things incredibly complex. It seems reasonable to forget the <code>User</code> model altogether, but <a href="https://docs.djangoproject.com/en/1.7/topics/auth/default/#django.contrib.auth.authenticate" rel="nofollow"><code>Authenticate</code></a> needs to return a valid user. This makes me wonder, can I create regular Django users with as little information filled in as possible (dummy data except for the username), and then authenticate them with the API? Probably, but that hardly seems like a good idea.</p>
|
<p>To authenticate users using the university API, all you need to do is to write <a href="https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#writing-an-authentication-backend" rel="nofollow">an authentication backend</a>. You can then create a local user for these uni users the first time they login, since there is only two required fields: username and password. You can use <code>set_unusable_password()</code> so <code>check_password()</code> for this user will never return True.</p>
<blockquote>
<p>The Django admin system is tightly coupled to the Django User object
described at the beginning of this document. For now, the best way to
deal with this is to create a Django User object for each user that
exists for your backend (e.g., in your LDAP directory, your external
SQL database, etc.) You can either write a script to do this in
advance, or <strong>your authenticate method can do it the first time a user
logs in</strong>.</p>
</blockquote>
|
python|django|django-authentication
| 1 |
1,902,042 | 28,786,608 |
Read text file and count number of words between two words(Two Dates)
|
<p>I have a text file that contains lot of dates in in it. Dates are of format ( March 4 2012 or March 2012). If suppose I have few words between these dates, I want to count certain word. Like wise, I want to count the same word between each two of those dates and produce an output in exel file with date and count.Can somebbody help me with this?</p>
<p>I've given sample text file. </p>
<p>textfile.txt </p>
<p>BACKGROUND OF THE SOLICITATION
At the Company’s 2011 and 2012 annual meetings of shareholders, Biglari previously had nominated individuals for election to the Board. The following is a chronology of events leading up to the proxy solicitation related to the 2013 Annual Meeting:
*
On November 30, 2012, a telephone conference was held among Sardar Biglari, Chairman and Chief Executive Officer of Biglari Holdings Inc. and Biglari Capital; Sandra B. Cochran, President and Chief Executive Officer of the Company; and James W. Bradford, Chairman of the Board of the Company. Ms. Cochran and Mr. Bradford conveyed to Mr. Biglari the Company’s interest in exploring a buyback of all of the Shares owned by Biglari and its affiliates. Mr. Biglari subsequently replied that Biglari was not interested in a share repurchase not offered to all other Cracker Barrel shareholders.
*
On February 13, 2013, during a telephone conference among Mr. Biglari, Ms. Cochran and Mr. Bradford, the Cracker Barrel representatives reiterated the Company’s willingness to explore a repurchase of all of the Shares owned by Biglari and its affiliates. Mr. Biglari restated his position on this matter and urged the Company instead either to tender for 20% of the outstanding Shares or to issue a one-time special dividend to all shareholders. Later that same day, Biglari received a written offer from the Company, authorized by the Board, for the buyback of all of the 4,737,794 Shares then owned by Biglari and its affiliates at market price (subject to any adjustments that may be required by applicable Tennessee law).
*
On February 14, 2013, Mr. Biglari sent a letter to the Cracker Barrel Board stating that he was not interested in a share repurchase that is not offered to all other Cracker Barrel shareholders. The letter continued that, since Cracker Barrel has the capability of purchasing Biglari’s nearly 20% stake, then worth over $300 million, Mr. Biglari had two recommendations to the Board: (1) tender for 20% of the Company’s outstanding Shares or (2) issue a one-time special dividend of $300 million. Mr. Biglari contended that shareholders deserve a rational capital allocation strategy, one that benefits everyone proportionally. Mr. Biglari stated that it was his desire to see management succeed because of his investment in the Company. Mr. Biglari concluded that he and Dr. Cooley remained ready to offer their services to work with the Board productively and to discuss ways to augment shareholder value.
*
On March 6, 2013, Mr. Biglari and Philip L. Cooley, Vice Chairman of the Board of Biglari Holdings Inc., held a telephone conference with Mr. Bradford and Ms. Cochran in which Mr. Biglari proposed that Cracker Barrel pay a one-time special dividend of $15.00 per Share to all shareholders of the Company. Mr. Biglari provided the rationale for the Board’s adjusting the capital structure to return a substantial amount of cash to Cracker Barrel’s shareholders.
*
On March 25, 2013, Mr. Biglari received a voice message from Mr. Bradford in which Mr. Bradford specified he would place before the Board Mr. Biglari’s $15.00 per Share special dividend proposal.
*
On May 16, 2013, Messrs. Biglari and Cooley held a telephone conference with Mr. Bradford and Ms. Cochran. Mr. Biglari inquired about the status of the Board’s review of the proposed special dividend. Mr. Bradford replied that the Board had not met to discuss the matter. Mr. Biglari urged the Company to reach a swift resolution of this matter for the benefit of all shareholders. Mr. Biglari asserted that in the absence of a decision on the special dividend, he would use all means to advance the concept of a special dividend</p>
|
<p>Use a regex to find the dates.</p>
<pre><code>import re
regex = '\s(\w+)\s(\d+\,)\s(\d+)' # this will match the form "str int, int"
with open('textfile.txt', 'r') as f:
text = f.read()
all_dates = [' '.join(date) for date in re.findall(regex, text)]
</code></pre>
<p>This will create a list of all the dates in the file, called <code>all_dates</code>.</p>
|
python|date
| 0 |
1,902,043 | 28,857,046 |
Use of eval when building a dict in a for loop. Name is not defined
|
<p>Mostly curious why this syntax isn't behaving in the way I would expect it to.</p>
<p>Inside of a class's <strong>init</strong> which accepts multiple parameters (id, departmentId, active), I have the following variable:</p>
<pre><code>attributes = [
{'id': 5},
{'departmentId': 10},
{'active': True}
]
</code></pre>
<p>Essentially, I'm trying to build a dictionary where the key is the first key for each item in the attribute list, and the value is the parameter variable of that key string by getting its eval.</p>
<p>This works:</p>
<pre><code>keys = [k.keys()[0] for k in attributes]
values = [eval(v) for v in keys]
vdict = {keys[i]: values[i] for i,v in enumerate(keys)}
</code></pre>
<p>However, this does not work:</p>
<pre><code>vdict = {a.keys()[0]: eval(a.keys()[0]) for a in attributes}
</code></pre>
<p>Nor does this:</p>
<pre><code>keys = [k.keys()[0] for k in attributes
vdict = {v: eval(v) for v in keys}
</code></pre>
<p>Doing so raises a NameError: name 'id' is not defined</p>
<p>I'm confused why this is the case since, to me at least, this syntax seems perfectly logical. Building a dictionary in that manor works fine when I'm doing it from two lists, not so much when I'm doing it from the attribute dictionary's key list or a list of keys.</p>
<p>EDIT: Python 2.7.9 on Windows if that makes any difference, here.</p>
|
<p>The variables given by the keys are not in scope inside the comprehension. If I use a loop, it works for me:</p>
<pre><code>class TestClass(object):
def __init__(self, id, departmentId, active):
values = [
{'id': 5},
{'departmentId': 10},
{'active': True}]
vdict = {}
for a in values:
vdict[list(a.keys())[0]] = eval(list(a.keys())[0])
print(vdict)
var = TestClass(1,2,False)
</code></pre>
|
python|dictionary|eval
| 0 |
1,902,044 | 14,455,871 |
Adding an item to an already populated combobox
|
<p>I have populated a combobox with an <strong>QSqlQueryModel</strong>. It's all working fine as it is, but I would like to add an extra item to the combobox that could say <strong>"ALL_RECORDS"</strong>. This way I could use the combobox as a filtering device. </p>
<p>I obviously don't want to add this extra item in the database, how can I add it to the combobox after it's been populated by a model?</p>
|
<p>You could use a proxy model that takes gets it's data from two models, one for your default values, the other for your database, and use it to populate your <code>QComboBox</code>.</p>
|
python|qt|pyqt|pyqt4|pyside
| 1 |
1,902,045 | 41,361,362 |
Launch python commands in parallel using shell
|
<p>I have a command in python this way:</p>
<pre><code>Python my_prog in1.fa ins.fa out1.fa
Python my_prog in2.fa ins.fa out2.fa
Python my_prog in3.fa ins.fa out3.fa
</code></pre>
<p>I used the parallel command of GNU parallel and I assemble the files in1.fa, in2.fa and in3.fa in the one file IN.fa.
My problem is I do not know how to put another agument or more in the parallel command.
here is my command:</p>
<pre><code>cat IN.fa | parallel -j 20 --cat --pipe --block 3M --recstart '>' time python my_prog.py
</code></pre>
<p>How can I make several arguments in the command Parallel please?</p>
|
<p>Let us assume that <code>my_prog</code> can read from stdin and send output to stdout and that it takes a single argument (<code>ins.fa</code>):</p>
<pre><code>parallel --pipepart -a in.fa --block 3M Python my_prog ins.fa > out.fa
</code></pre>
<p>If <code>my_prog</code> cannot read from stdin, but from a named pipe (fifo) this will work:</p>
<pre><code>parallel --fifo --pipepart -a in.fa Python my_prog {} ins.fa > out.fa
</code></pre>
<p>If <code>my_prog</code> cannot read from a fifo, but only an actual file, this will work:</p>
<pre><code>parallel --cat --pipepart -a in.fa Python my_prog {} ins.fa > out.fa
</code></pre>
<p>If <code>my_prog</code> cannot output to stdout, but can output to a fifo you can often use:</p>
<pre><code>parallel --cat --pipepart -a in.fa Python my_prog {} ins.fa {#}.out /dev/stdout > out.fa
</code></pre>
<p>Or:</p>
<pre><code>parallel --cat --pipepart -a in.fa Python my_prog {} ins.fa {#}.out '>(cat)' > out.fa
</code></pre>
<p>If <code>my_prog</code> cannot output to a fifo, you need to have it output to a uniquely named file, which you can then <code>cat</code> and remove. Here we use the sequence number to make a unique file.</p>
<pre><code>parallel --cat --pipepart -a in.fa Python my_prog {} ins.fa {#}.out '; cat {#}.out; rm {#}.out' > out.fa
</code></pre>
<p>You really should consider walking through the tutorial. It will answer this and <em>so</em> many other questions: man parallel_tutorial</p>
|
python|shell|parallel-processing|gnu-parallel
| 1 |
1,902,046 | 41,392,466 |
messy code when using emacs ipython Inferior Python
|
<p>I am using the newest emacs25.1.1 with the newest archlinux. </p>
<p>However, when I edit a python scripts and send it to the Inferior ipython by using Ctrl-Enter, the inferior Python show me a ugly messy code termial indicater like:</p>
<pre><code>Python 3.5.2 (default, Nov 7 2016, 11:31:36)
Type "copyright", "credits" or "license" for more information.
IPython 5.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
[JIn [1]: import numpy as np[26D
[J
[6n[JIn [2]: [8D[8C[8D[J[6n[JIn [2]: [8D[8C
</code></pre>
<p>When press Enter in this Inferior python, it shows:</p>
<pre><code>error in process filter: Args out of range: "
^[[6n^[[0m^[[0m^[[J^[[0;38;5;28mIn [^[[0;38;5;28m: ^[[8D^[[8C[[0m^[[0m", 128
</code></pre>
<p>I change the emacs locale from:</p>
<pre><code>LANG=zh_CN.UTF-8
LC_CTYPE="zh_CN.UTF-8"
LC_NUMERIC=en_US.UTF-8
LC_TIME=en_US.UTF-8
LC_COLLATE="zh_CN.UTF-8"
LC_MONETARY=en_US.UTF-8
LC_MESSAGES="zh_CN.UTF-8"
LC_PAPER=en_US.UTF-8
LC_NAME="zh_CN.UTF-8"
LC_ADDRESS="zh_CN.UTF-8"
LC_TELEPHONE="zh_CN.UTF-8"
LC_MEASUREMENT=en_US.UTF-8
LC_IDENTIFICATION="zh_CN.UTF-8"
LC_ALL=
</code></pre>
<p>To:</p>
<pre><code>LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC=en_US.UTF-8
LC_TIME=en_US.UTF-8
LC_COLLATE="en_US.UTF-8"
LC_MONETARY=en_US.UTF-8
LC_MESSAGES="en_US.UTF-8"
LC_PAPER=en_US.UTF-8
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT=en_US.UTF-8
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=
</code></pre>
<p>with the command $"export LANGUAGE="en_US:en" && emacs"$, no help to resolve the messy code.</p>
<p>I also try python-mode.et or elpy package in emacs, all show the same
messy terminal code.</p>
<p>Further,python2.7 also tried, no work:</p>
<pre><code>Python 2.7.12 (default, Nov 7 2016, 11:55:55)
Type "copyright", "credits" or "license" for more information.
IPython 5.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
[JIn [1]: import numpy as np[26D
[J
[6n[JIn [2]: [8D[8C[8D[J[6n[JIn [2]: [8D[8C
</code></pre>
<p>Is the newest ipython problem?</p>
<p>At last the <em>message</em> in emacs paste here:</p>
<pre><code>error in process filter: ansi-color-filter-apply: Args out of range: "Python 3.5.2 (default, Nov 7 2016, 11:31:36)
Type \"copyright\", \"credits\" or \"license\" for more information.
IPython 5.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
[6n[0m
[0m[J
[0m", 408
error in process filter: Args out of range: "Python 3.5.2 (default, Nov 7 2016, 11:31:36)
Type \"copyright\", \"credits\" or \"license\" for more information.
IPython 5.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
[6n[0m
[0m[J
[0m", 408
error in process filter: ansi-color-filter-apply: Args out of range: "[0m[0m[J[0;38;5;28mIn [[0;38;5;10;1m1[0;38;5;28m]: [0;38;5;28;1mimport[0m [0;38;5;32;1mnumpy[0m [0;38;5;28;1mas[0m [0;38;5;32;1mnp[26D[0m
[J[0m", 177
error in process filter: Args out of range: "[0m[0m[J[0;38;5;28mIn [[0;38;5;10;1m1[0;38;5;28m]: [0;38;5;28;1mimport[0m [0;38;5;32;1mnumpy[0m [0;38;5;28;1mas[0m [0;38;5;32;1mnp[26D[0m
[J[0m", 177
error in process sentinel: elpy-rpc--default-error-callback: peculiar error: "exited abnormally with code 1"
error in process sentinel: peculiar error: "exited abnormally with code 1"
error in process filter: ansi-color-filter-apply: Args out of range: #("[JIn [1]: import numpy as np[26D
[J
[6n[0m[0m[J[0;38;5;28mIn [[0;38;5;10;1m2[0;38;5;28m]: [8D[8C[0m[0m[8D[J[0m[6n[0m[0m[J[0;38;5;28mIn [[0;38;5;10;1m2[0;38;5;28m]: [8D[8C[0m" 0 38 (fontified nil) 38 39 (fontified nil)), 283
error in process filter: Args out of range: #("[JIn [1]: import numpy as np[26D
[J
[6n[0m[0m[J[0;38;5;28mIn [[0;38;5;10;1m2[0;38;5;28m]: [8D[8C[0m[0m[8D[J[0m[6n[0m[0m[J[0;38;5;28mIn [[0;38;5;10;1m2[0;38;5;28m]: [8D[8C[0m" 0 38 (fontified nil) 38 39 (fontified nil)), 283
</code></pre>
|
<p>I've used recomendation from <a href="https://github.com/jorgenschaefer/elpy/issues/992#issuecomment-249165923" rel="noreferrer">https://github.com/jorgenschaefer/elpy/issues/992#issuecomment-249165923</a>. In short - add the following code:
<code>(setenv "IPY_TEST_SIMPLE_PROMPT" "1")</code> into emacs configuration file.</p>
|
python|emacs|ipython|emacs25
| 5 |
1,902,047 | 41,257,336 |
OpenCV Error: Assertion failed (L.channels() == 1 && I.channels() == 1) in connectedComponents_sub1
|
<p>I got the following error in OpenCV (python) and have googled a lot but have not been able to resolve.</p>
<p>I would be grateful if anyone could provide me with some clue. </p>
<blockquote>
<p>OpenCV Error: Assertion failed (L.channels() == 1 && I.channels() == 1)
in connectedComponents_sub1, file /home/snoopy/opencv-
3.1.0/modules/imgproc/src/connectedcomponents.cpp, line 341
Traceback (most recent call last):
File "test.py", line 30, in
plant = analyzeplant.analyzeSideView(plant)
File "/home/snoopy/Desktop/Leaf-201612/my-work-
editing/ripps/src/analyzePlant.py", line 229, in analyzeSideView
plant_img = self.__extractPlantArea(plant_img)
File "/home/snoopy/Desktop/Leaf-201612/my-work-
editing/ripps/src/analyzePlant.py", line 16, in __extractPlantArea
output = cv2.connectedComponentsWithStats(plant, 4, cv2.CV_32S)
cv2.error: /home/snoopy/opencv-
3.1.0/modules/imgproc/src/connectedcomponents.cpp:341: error: (-215) > L.channels() == 1 && I.channels() == 1 in function
connectedComponents_sub1</p>
</blockquote>
|
<p>Let us analyze it:</p>
<blockquote>
<p>Assertion failed (L.channels() == 1 && I.channels() == 1)</p>
</blockquote>
<p>The images that you are passing to some function should be 1 channel (gray not color).</p>
<blockquote>
<p>__extractPlantArea(plant_img)</p>
</blockquote>
<p>That happened in your code exactly at the function called <code>__extractPlantArea</code>.</p>
<blockquote>
<p>cv2.connectedComponentsWithStats</p>
</blockquote>
<p>While you are calling the OpenCV function called <code>connectedComponentsWithStats</code>.</p>
<p><strong>Conclusion:</strong></p>
<p>Do not pass colorful (BGR) image to <code>connectedComponentsWithStats</code></p>
|
python|python-2.7|opencv|opencv3.1|connected-components
| 12 |
1,902,048 | 41,346,188 |
Python kill bash while loop started from subprocess
|
<p>I am trying to execute the bash script <code>while :; do afplay beep.wav ; done</code> command from a python script, but be able to kill it afterwards.</p>
<p>I tried:</p>
<pre><code>process = subprocess.Popen("exec while :; do afplay %s ; done" % fileName, shell=True, executable='/bin/bash')
</code></pre>
<p>as <a href="https://stackoverflow.com/a/13143013/3310334">this answer</a> suggests, but the above doesn't work for me. (The script doesn't run.)</p>
<p>How can I run <code>while :; do afplay beep.wav ; done</code> from python and kill it at any point after it is started?</p>
<hr>
<p><strong>EDIT</strong>: just noticed that <code>exec >(while :; do afplay %s; done)</code> will launch the script, but now <code>process.kill()</code> won't kill it.</p>
|
<pre><code>os.killpg(os.getpgid(process.pid), signal.SIGINT)
</code></pre>
<p>this seemed to do the trick. I am killing the process group (<code>os.killpg</code>) instead of the sole process.</p>
|
python|bash|shell|subprocess|exec
| 1 |
1,902,049 | 6,318,880 |
Python loop with lists
|
<p>I was writing some Python 3.2 code and this question came to me:</p>
<p>I've got these variables:</p>
<pre><code># a list of xml.dom nodes (this is just an example!)
child_nodes = [node1, node2, node3]
# I want to add every item in child_node into this node (this also a xml.dom Node)
parent = xml_document.createElement('TheParentNode')
</code></pre>
<p>This is exactly what I want to do:</p>
<pre><code>for node in child_nodes:
if node is not None:
parent.appendChild(node)
</code></pre>
<p>I wrote it in one line like this:</p>
<pre><code>[parent.appendChild(c) for c in child_nodes if c is not None]
</code></pre>
<p>I'm not going to use the list result at all, I only need the appendChild to do its work.</p>
<p>I'm not a very experienced python programmer, so I wonder which one is better?
I like the single line solution, but I would like to know from experienced python programmers:</p>
<p>Which one is better, in a context of either code beauty/maintainability) and performance/memory use.</p>
|
<p>The former is preferable in this situation.</p>
<p>The latter is called a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="noreferrer">list comprehension</a> and creates a new <code>list</code> object full of the results of each call to <code>parent.appendChild(c)</code>. <em>And then discards it</em>.</p>
<p>However, if you <em>want</em> to make a <code>list</code> based on this kind of iteration, then you should certainly employ a list comprehension.</p>
|
python|for-loop|python-3.x
| 8 |
1,902,050 | 6,875,599 |
With python socketserver how can I pass a variable to the constructor of the handler class
|
<p>I would like to pass my database connection to the EchoHandler class, however I can't figure out how to do that or access the EchoHandler class at all.</p>
<pre>
class EchoHandler(SocketServer.StreamRequestHandler):
def handle(self):
print self.client_address, 'connected'
if __name__ == '__main__':
conn = MySQLdb.connect (host = "10.0.0.5", user = "user", passwd = "pass", db = "database")
SocketServer.ForkingTCPServer.allow_reuse_address = 1
server = SocketServer.ForkingTCPServer(('10.0.0.6', 4242), EchoHandler)
print "Server listening on localhost:4242..."
try:
server.allow_reuse_address
server.serve_forever()
except KeyboardInterrupt:
print "\nbailing..."
</pre>
|
<p>Unfortunately, there really isn't an easy way to access the handlers directly from outside the server.</p>
<p>You have two options to get the information to the EchoHandler instances:</p>
<ol>
<li>Store the connection as a property of the server (add <code>server.conn = conn</code> before calling <code>server_forever()</code>) and then access that property in EchoHandler.handler through <code>self.server.conn</code>.</li>
<li>You can overwrite the server's <code>finish_request</code> and assign the value there (you would have to pass it to the constructor of EchoHandler and overwrite EchoHandler.__init__). That is a <strong><em>far messier</em></strong> solution and it pretty much requires you to store the connection on the server anyway.</li>
</ol>
<p>My optionon of your best bet:</p>
<pre><code>class EchoHandler(SocketServer.StreamRequestHandler):
def handle(self):
# I have no idea why you would print this but this is an example
print( self.server.conn );
print self.client_address, 'connected'
if __name__ == '__main__':
SocketServer.ForkingTCPServer.allow_reuse_address = 1
server = SocketServer.ForkingTCPServer(('10.0.0.6', 4242), EchoHandler)
server.conn = MySQLdb.connect (host = "10.0.0.5",
user = "user", passwd = "pass", db = "database")
# continue as normal
</code></pre>
|
python|python-2.7|socketserver
| 31 |
1,902,051 | 57,251,201 |
Python Flask-restful multiple api endpoints
|
<p>How to check what route has been used?</p>
<p>Using @api with Flask-restful and Python at the moment I'm not doing it in a clean way by checking <code>api.endpoint</code> value.</p>
<p>How do I do it correctly? </p>
<pre><code>@api.route('/form', endpoint='form')
@api.route('/data', endpoint='data')
class Foobar(Resource):
def post(self):
if api.endpoint == 'api.form':
print('form')
elif api.endpoint == 'api.data':
print('data')
</code></pre>
<p>EDIT:</p>
<p>Should I split it into two classes? </p>
|
<p>I am in no way a professional with flask so please do take my answer with a grain of salt. First of all I would definitely split it into 2 different classes just to have a better overview of what you are doing. Also as a rule of thumb I would always split the apis and write its own logic for a higher degree of granularity. </p>
<p>Second if you want to have a look at <a href="https://flask-restful.readthedocs.io/en/latest/api.html#flask_restful.Api.owns_endpoint" rel="nofollow noreferrer">https://flask-restful.readthedocs.io/en/latest/api.html#flask_restful.Api.owns_endpoint</a>. This might be of assistance for you. </p>
|
python|flask|endpoint|flask-restful
| 4 |
1,902,052 | 25,672,198 |
Conversions of np.timedelta64 to days, weeks, months, etc
|
<p>When I compute the difference between two pandas <code>datetime64</code> dates I get <code>np.timedelta64</code>. Is there any easy way to convert these deltas into representations like hours, days, weeks, etc.?</p>
<p>I could not find any methods in <code>np.timedelta64</code> that facilitate conversions between different units, but it looks like Pandas seems to know how to convert these units to days when printing timedeltas (e.g. I get: <code>29 days, 23:20:00</code> in the string representation dataframes). Any way to access this functionality ?</p>
<h2>Update:</h2>
<p>Strangely, none of the following work:</p>
<pre><code>> df['column_with_times'].days
> df['column_with_times'].apply(lambda x: x.days)
</code></pre>
<p>but this one does:</p>
<pre><code>df['column_with_times'][0].days
</code></pre>
|
<p>pandas stores timedelta data in the numpy <code>timedelta64[ns]</code> type, but also provides the <code>Timedelta</code> type to wrap this for more convenience (eg to provide such accessors of the days, hours, .. and other components).</p>
<pre><code>In [41]: timedelta_col = pd.Series(pd.timedelta_range('1 days', periods=5, freq='2 h'))
In [42]: timedelta_col
Out[42]:
0 1 days 00:00:00
1 1 days 02:00:00
2 1 days 04:00:00
3 1 days 06:00:00
4 1 days 08:00:00
dtype: timedelta64[ns]
</code></pre>
<p>To access the different components of a full column (series), you have to use the <code>.dt</code> accessor. For example:</p>
<pre><code>In [43]: timedelta_col.dt.hours
Out[43]:
0 0
1 2
2 4
3 6
4 8
dtype: int64
</code></pre>
<p>With <code>timedelta_col.dt.components</code> you get a frame with all the different components (days to nanoseconds) as different columns.<br>
When accessing one value of the column above, this gives back a <code>Timedelta</code>, and on this you don't need to use the <code>dt</code> accessor, but you can access directly the components:</p>
<pre><code>In [45]: timedelta_col[0]
Out[45]: Timedelta('1 days 00:00:00')
In [46]: timedelta_col[0].days
Out[46]: 1L
</code></pre>
<p>So the <code>.dt</code> accessor provides access to the attributes of the <code>Timedelta</code> scalar, but on the full column. That is the reason you see that <code>df['column_with_times'][0].days</code> works but <code>df['column_with_times'].days</code> not.<br>
The reason that <code>df['column_with_times'].apply(lambda x: x.days)</code> does not work is that apply is given the <code>timedelta64</code> values (and not the <code>Timedelta</code> pandas type), and these don't have such attributes.</p>
|
python|numpy|pandas
| 3 |
1,902,053 | 44,627,329 |
Parsing column values in Pandas
|
<p>I have columns Name with this values:</p>
<pre><code>NY0528_3
NY5366_2
4536
NY1244_5
5363
PH1734_3
</code></pre>
<p>Desired output:</p>
<pre><code>0528
5366
6363
1244
5363
1734
</code></pre>
<p>Whatever I've tried, I can't get a universal solution, but I need that cause I have 200.000 rows.
Thanks </p>
|
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html#pandas-series-str-extract" rel="nofollow noreferrer"><code>extract</code></a>:</p>
<pre><code>df.Name.str.extract('(\d+)')
</code></pre>
<p>Output:</p>
<pre><code>0 0528
1 5366
2 4536
3 1244
4 5363
5 1734
Name: Name, dtype: object
</code></pre>
|
python|pandas|parsing|dataframe
| 3 |
1,902,054 | 61,884,348 |
removing words that appear more than x% in a corpus Python
|
<p>I am dealing with a large corpus in the form of a list of tokens/words. The corpus contains ~1900,000 words, I have run a code to get the most frequent words and now the corpus has 140,000 word.</p>
<p>I would like to remove the words that appear more than 95% of the document and less than 5% </p>
<p>sample of the corpus</p>
<pre><code>['problems', 'guess', 'sleep', 'holy']
</code></pre>
<p>First I found the most frequent words</p>
<pre><code>from nltk.probability import FreqDist
corpus_frequency = FreqDist(corpus)
corpus_commom=corpus_frequency.most_common()
</code></pre>
<p>Then, I applied this for loop to find the list of words that appear more than 95%</p>
<pre><code>most_frequent=[mytuple for mytuple in corpus_commom if mytuple[1]<len(corpus*95)/100]
</code></pre>
<p>But this code takes very long time to run, and it does not return any output.</p>
<p>I also tried to follow some answers I found and apply CountVectorizer but I get an error message </p>
<pre><code>from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(min_df=0.05, max_df=0.95, lowercase=True)
X = cv.fit_transform(corpus)
</code></pre>
<p>The error message</p>
<pre><code>ValueError: After pruning, no terms remain. Try a lower min_df or a higher max_df.
</code></pre>
<p><strong>Update</strong></p>
<p>The CountVectorizer works if I do this </p>
<pre><code>cv = CountVectorizer(corpus,max_df=0.95)
count_vector=cv.fit_transform(corpus)
</code></pre>
<p>But it returns a list of numbers. I would like the output to be my corpus(list of words) filtered. </p>
<p>Can anyone give me a tip on how to achieve this? Thanks </p>
|
<p>Here is some code that computes the frequency fraction of each token in a list. You can use the fraction to perform your filtering.</p>
<pre class="lang-py prettyprint-override"><code>import nltk
def get_frac_dist(token_list):
'''
Computes frequency count and fraction of individual words in a list.
Parameters
----------
token_list : list
List of all (non-unique) tokens from some corpus
Returns
-------
dict
Dictionary of { token, (count, fraction) } pairs.
'''
token_list = nltk.word_tokenize(content)
total_token_count = len(token_list)
freq_dict = nltk.FreqDist(token_list)
frac_dict = {}
for token, count in freq_dict.items():
frac_dict[token] = (count, count / total_token_count)
return frac_dict
</code></pre>
<p>Here's how you can use it:</p>
<ol>
<li>Open a file, tokenize it with <code>nltk.word_tokenize()</code>, and pass the token list into <code>get_frac_dist()</code>.</li>
</ol>
<pre class="lang-py prettyprint-override"><code>with open('speech.txt') as f:
content = f.read()
token_list = nltk.word_tokenize(content)
frac_dist = get_frac_dist(token_list)
</code></pre>
<ol start="2">
<li>The <code>get_frac_dist()</code> returns a dictionary. The key is a token, and the value is a tuple containing (frequency count, frequency fraction). Let's take a look at the first 10 items in the dictionary.</li>
</ol>
<pre class="lang-py prettyprint-override"><code>i = 0
for k, v in frac_dist.items():
i += 1
if i > 10:
break
token = k
count = v[0]
frac = v[1]
print('%-20s: %5d, %0.5f' % (token, count, frac))
</code></pre>
<p>prints out:</p>
<pre><code>President : 2, 0.00081
Pitzer : 1, 0.00040
, : 162, 0.06535
Mr. : 3, 0.00121
Vice : 1, 0.00040
Governor : 1, 0.00040
Congressman : 2, 0.00081
Thomas : 1, 0.00040
Senator : 1, 0.00040
Wiley : 1, 0.00040
</code></pre>
<ol start="3">
<li>Now, if you want to get the words with the fraction greater than or less than some value, run a loop or a list comprehension using <code><</code> or <code>></code> appropriately.</li>
</ol>
<pre class="lang-py prettyprint-override"><code>l = [ (k, v[0], v[1]) for k, v in frac_dist.items() if v[1] > 0.04 ]
print(l)
</code></pre>
<p>prints out:</p>
<pre><code>[(',', 162, 0.0653489310205728), ('and', 104, 0.04195240016135539), ('the', 115, 0.0463896732553449)]
</code></pre>
<p>Be aware that your desire to get the words that occur more than 95% of the time may not return any valid answer. You should plot out the distribution of words and see what their counts are. </p>
|
python|for-loop|text-processing
| 1 |
1,902,055 | 20,494,056 |
I have just started learning Python. Whats wrong with this code?
|
<pre><code>import random
print("Let's play the Random Number Game")
guess=random.randint(1,15)
print("\n I've choosed a random Number from 1 to 15", "Try guessing the number")
def strt( ):
userguess=input("\n Enter the number")
if userguess==guess :
print("wow! you've guessed the correct number in" ,"time")
else:
if userguess>guess:
print("Guess a smaller number")
strt( )
else : print("Guess a Larger number")
strt( )
strt()
input("Hit Enter to Exit")
</code></pre>
<p>I have just started learning Python. Whats wrong with this code?</p>
|
<p>Aside from the lack of <strong>Proper Indentation</strong> your program also contained a minor bug.</p>
<p><code>input()</code> returns a <code>str</code> in Python and you cannot compare strings with ints in Python without doing some kind of conversion. e.g:</p>
<pre><code>userguess = int(input("Guess: "))
</code></pre>
<p>Without this type conversion a <code>TypeError</code> is thrown like this:</p>
<pre><code>>>> "foo" > 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
</code></pre>
<p>A correct version of your program with proper indentation and the above bug fixed:</p>
<pre><code>import random
print("Let's play the Random Number Game")
guess = random.randint(1, 15)
print("\n I've choosed a random Number from 1 to 15", "Try guessing the number")
def strt():
userguess = int(input("\n Enter the number"))
if userguess == guess:
print("wow! you've guessed the correct number in", "time")
else:
if userguess > guess:
print("Guess a smaller number")
strt()
else:
print("Guess a Larger number")
strt()
strt()
input("Hit Enter to Exit")
</code></pre>
|
python|python-3.3
| 4 |
1,902,056 | 15,307,589 |
numpy array with mpz/mpfr values
|
<p>I want to have a numpy array with mpz/mpfr values. Because my code:</p>
<pre><code>import numpy as np
import gmpy2
A=np.ones((5,5));
print A/gmpy2.mpfr(1);
</code></pre>
<p>generates:</p>
<pre><code>RuntimeWarning: invalid value encountered in divide
print A/gmpy2.mpfr(1);
[[1.0 1.0 1.0 1.0 1.0]
[1.0 1.0 1.0 1.0 1.0]
[1.0 1.0 1.0 1.0 1.0]
[1.0 1.0 1.0 1.0 1.0]
[1.0 1.0 1.0 1.0 1.0]]
</code></pre>
<p>Which as I can understand is the impossibility to convert gmpy mpfr to numpy float64. So how can I get a numpy array with mpfr values in the first place?</p>
<p>Thanks.</p>
|
<p>You will need to create your array with <code>dtype=object</code>, and then you can use any python type inside your array. I don't have gmpy2 installed, but the following example should show how it works:</p>
<pre><code>In [3]: a = np.ones((5, 5), dtype=object)
In [5]: import fractions
In [6]: a *= fractions.Fraction(3, 4)
In [7]: a
Out[7]:
array([[3/4, 3/4, 3/4, 3/4, 3/4],
[3/4, 3/4, 3/4, 3/4, 3/4],
[3/4, 3/4, 3/4, 3/4, 3/4],
[3/4, 3/4, 3/4, 3/4, 3/4],
[3/4, 3/4, 3/4, 3/4, 3/4]], dtype=object)
</code></pre>
<p>Having a numpy array of <code>dtype=object</code> can be a liitle misleading, because the powerful numpy machinery that makes operations with the standard dtypes super fast, is now taken care of by the default object's python operators, which means that the speed will not be there anymore:</p>
<pre><code>In [12]: b = np.ones((5, 5)) * 0.75
In [13]: %timeit np.sum(a)
1000 loops, best of 3: 1.25 ms per loop
In [14]: %timeit np.sum(b)
10000 loops, best of 3: 23.9 us per loop
</code></pre>
|
python|numpy|type-conversion|gmp
| 7 |
1,902,057 | 29,395,674 |
Generate two random strings with dash in between
|
<p>I am wondering how to make a code in python 3.4.3 that can generate two 3 character long strings. One Digits 0 - 9, and the other capital letters of the alphabet. There also has to be a dash between them. </p>
<p>Examples:</p>
<pre><code>MUS-875
KLE-443
AMI-989
</code></pre>
<p>This is what I have</p>
<pre><code>from random import randint
print(randint(2,9))
</code></pre>
|
<p>Try picking a random string of letters, then a random string of digits, then joining them with a hyphen:</p>
<pre><code>import string, random
def pick(num):
for j in range(num):
print("".join([random.choice(string.ascii_uppercase) for i in range(3)])+"-"+"".join([random.choice(string.digits) for i in range(3)]))
</code></pre>
<p>As such:</p>
<pre><code>>>> pick(5)
OSD-711
KRH-340
MDE-271
ZJF-921
LUX-920
>>> pick(0)
>>> pick(3)
SFT-252
XSL-209
MAF-579
</code></pre>
|
python|python-3.x|random
| 4 |
1,902,058 | 46,375,886 |
extendscript return argument from python script
|
<p>I am working on an extendscript code (Adobe After Effects - but it is basically just javascript) which needs to iterate over tens of thousands of file names on a server. This is extremely slow in extendscript but I can accomplish what I need to in just a few seconds with python, which is my preferred language anyway. So I would like to run a python file and return an array back into extendscript. I'm able to run my python file and pass an argument (the root folder) by creating and executing a batch file, but how would pass the result (an array) back into extendscript? I suppose I could write out a .csv and read this back in but that seems a bit "hacky".</p>
|
<p>In After Effects you can use the "system" object's callSystem() method. This gives you access to the system's shell so you can run any script from the code. So, you can write your python script that echos or prints the array and that is essentially what is returned by the system.callSystem() method. It's a synchronous call, so it has to complete before the next line in ExtendScript executes.</p>
<p>The actual code might by something like:</p>
<p><code>var stdOut = system.callSystem("python my-python-script.py")</code></p>
|
python|batch-file|extendscript
| 5 |
1,902,059 | 60,802,534 |
How URL query parameters are generated?
|
<p><img src="https://i.stack.imgur.com/I3uIV.png" alt="enter image description here"></p>
<p>How are the parameters after node?_=xxxxxx are being generated?</p>
<h2>How can I capture these if using a Python script to get the URL?</h2>
<p>edit:
Apologies for not enough info. My first novice post. </p>
<p>I am trying to get the nodes dictionary using Python from Eve-NG API.</p>
<p>Eve-NG API Docs Ref:
<a href="https://www.eve-ng.net/index.php/documentation/howtos/how-to-eve-ng-api/" rel="nofollow noreferrer">https://www.eve-ng.net/index.php/documentation/howtos/how-to-eve-ng-api/</a></p>
<pre><code>curl -s -c /tmp/cookie -b /tmp/cookie
-X GET -H 'Content-type: application/json'
http://127.0.0.1/api/labs/User1/Lab%201.unl/nodes
</code></pre>
<p>with above I get a dictionary with nodes data, all the info is correct except url key value "url":"/html5/#/client/MzI3OTIAYwBteXNxbA==?token=AE...000"</p>
<p>expected value is - "url": "telnet://127.0.0.1:32769" as show in eve-ng docs.</p>
<p>From Chrome Developer Tools if I open - <a href="http://127.0.0.1/api/labs/User1/Lab%201.unl/nodes?158489xxxx" rel="nofollow noreferrer">http://127.0.0.1/api/labs/User1/Lab%201.unl/nodes?158489xxxx</a> in a tab, I can see the correct "url": "telnet://127.0.0.1:32769" key/value pair.</p>
<p>you can see in the screenshot the GET request has query parameters node?_=xxxxxxx
how can find out how these numbers/timestamps/encoded values are being generated?
or how can I modify Python script to capture these can make the correct GET request?</p>
<p>Hope this explains the issue. </p>
<p>Thanks</p>
|
<pre><code><div class="form-group has-feedback">
<select name="html5" class="form-control" ng-init="html5='-1'" placeholder="html5" ng-model="html5">
<option value="-1" selected="">Native console</option>
<option value="1">Html5 console</option>
</select>
</div>
</code></pre>
|
javascript|python|jquery|html|ajax
| 0 |
1,902,060 | 70,319,731 |
always show error : 'DataFrame' object does not support item assignment in databricks
|
<pre><code>import numpy as np
import pandas as pd
df = df_final_bureau_balance
df.show()
df.printSchema()
df["*"] = df['STATUS']
</code></pre>
<p>I wanna create one column but there is always one error:'DataFrame' object that does not support item assignment<br />
but from pandas user manual there is nothing wrong.
the object does support item assignment isn't dataframe?</p>
<pre><code>+------------+------+-------------------+-------------------+-----+
|SK_ID_BUREAU|STATUS|max(MONTHS_BALANCE)|min(MONTHS_BALANCE)|count|
+------------+------+-------------------+-------------------+-----+
| 5001709| C| 0| -85| 86|
| 5001709| X| -86| -96| 11|
| 5001710| C| 0| -47| 48|
| 5001710| X| -49| -82| 30|
| 5001710| 0| -48| -53| 5|
| 5001711| X| 0| 0| 1|
| 5001711| 0| -1| -3| 3|
| 5001712| C| 0| -8| 9|
| 5001712| 0| -9| -18| 10|
| 5001713| X| 0| -21| 22|
| 5001714| X| 0| -14| 15|
| 5001715| X| 0| -59| 60|
| 5001716| 0| -39| -65| 27|
| 5001716| X| -66| -85| 20|
| 5001716| C| 0| -38| 39|
| 5001717| 0| -5| -21| 17|
| 5001717| C| 0| -4| 5|
| 5001718| C| 0| -2| 3|
| 5001718| X| -9| -38| 10|
| 5001718| 0| -3| -37| 24|
+------------+------+-------------------+-------------------+-----+
only showing top 20 rows
root
|-- SK_ID_BUREAU: integer (nullable = true)
|-- STATUS: string (nullable = true)
|-- max(MONTHS_BALANCE): integer (nullable = true)
|-- min(MONTHS_BALANCE): integer (nullable = true)
|-- count: long (nullable = true)
TypeError: 'DataFrame' object does not support item assignment
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<command-2083632421660035> in <module>
7 df.show()
8 df.printSchema()
----> 9 df["*"] = df['STATUS']
10
11
TypeError: 'DataFrame' object does not support item assignment
</code></pre>
|
<p>following syntaxs are not belong in panda dataframe. Those are related spark dataframe.</p>
<pre><code>df.show()
df.printSchema()
</code></pre>
<p>Same functionality should be in panda dataframe,</p>
<pre><code>print(df)
df.info(verbose=True)
</code></pre>
<p><a href="https://i.stack.imgur.com/4btXy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4btXy.png" alt="enter image description here" /></a></p>
|
pandas|databricks
| 0 |
1,902,061 | 70,370,474 |
Can't start multiprocessing Pool in dask task
|
<p>I am trying to compute a dask custom graph in a remote cluster using the Client.get method, but I have been running into the following error: <code>AssertionError: daemonic processes are not allowed to have children</code></p>
<p>I realized that one of the underlying methods in the dask graph uses a process pool, which causes this error to be raised, since dask also tries to use a process pool himself. So, the way I sort of fixed this was by using a LocalCluster and passing the argument <code>processes=False</code>. However, the unfortunate thing is that dask won't let me pass the <code>process=False</code> if I am using a Client attached to a remote cluster, and also initializing the remote workers with the --nprocs=1 argument won't work as well.</p>
<p>All in all, I am able to run the graph, but it is quite frustrating that I can't use multiprocessing capabilities when computing the dask graph, and can't use remote clusters. Any ideas on how to implement one (or maybe both) of these requirements?</p>
<p>Thanks in advance</p>
<h2>Code Sample</h2>
<p>This is what I intended to do, but got the AssertionError to be thrown:</p>
<pre><code>from multiprocessing import Pool
from dask.distributed import Client
client = Client(<some-remote-ip-address-here>)
def foo():
pool = Pool() # the exception is raised here, on the Pool object initialization
... does something here ...
returns True
graph = {'result': foo}
client.get(graph, 'result')
</code></pre>
<p>This is how I "fixed" it, by removing the multiprocessing capabilities, and setting a local cluster:</p>
<pre><code>from multiprocessing import Pool
from dask.distributed import Client
client = Client(processes=False) # this yields a LocalCluster that doesn't have multiprocessing capabilities (doc is very brief and not very helpful: http://distributed.dask.org/en/stable/api.html#distributed.LocalCluster)
def foo():
pool = Pool() # no exception is raised
... does something here ...
returns True
graph = {'result': foo}
client.get(graph, 'result')
</code></pre>
|
<p>Like @Michael Delgado told himself, there is no way to do such thing. The only workaround I found was using a LocalCluster passing <code>processes=False</code> or launching a remote worker passing the <code>--no-nanny</code> argument. This shall make the code above work, but without multiprocessing capabilities.</p>
|
python|multiprocessing|cluster-computing|dask|distributed-computing
| 0 |
1,902,062 | 53,511,783 |
how to map with multiple data frame?
|
<p>I would like to map between two data frames which are</p>
<pre><code>df_list
a b
0 1 3
1 2 1
2 3 4
3 2 4
4 3 1
</code></pre>
<p>and df_name</p>
<pre><code> num_l name
0 1 Mark
1 2 John
2 3 Sara
3 4 David
</code></pre>
<p>and then get the result like this</p>
<pre><code>result
a b name_a name_b
0 1 3 Mark Sara
1 2 1 John Mark
2 3 4 Sara David
3 2 4 John David
4 3 1 Sara Mark
</code></pre>
<p>at first, I try to create data frames that collect from 'a' and 'name' and 'b','name' then concat it together, but the order refer to df_list is not working. thank you in advance.</p>
|
<p>You can using <code>replace</code> </p>
<pre><code>df2=df.replace(dict(zip(df1.num_l,df1.name))).add_prefix('name_')
pd.concat([df,df2],1)
a b name_a name_b
0 1 3 Mark Sara
1 2 1 John Mark
2 3 4 Sara David
3 2 4 John David
4 3 1 Sara Mark
</code></pre>
|
python|pandas
| 2 |
1,902,063 | 53,688,564 |
How import 'html5lib' package to Python 3.5 Script in Azure Machine Learning Studio?
|
<p>I'm trying to import the package <code>html5lib</code> to <code>Azure Machine Learning</code>, into a <code>Execute Python Script</code> module. It's a similar question as <a href="https://stackoverflow.com/questions/44593469/how-can-certain-python-libraries-be-imported-in-azure-mllike-the-line-import-hu">here</a>, but same solution didn't work... :/</p>
<p>My steps until now:</p>
<ol>
<li>I got the latest version of <code>HTML5LIB</code> package from the <a href="https://pypi.org/project/html5lib/" rel="nofollow noreferrer">project website</a>;</li>
<li>Unzip tar.gz file and re-zip as .ZIP file;</li>
<li>Upload the file in Azure Studio as a Dataset named as 'html5lib.zip';
<a href="https://i.stack.imgur.com/o3UvI.png" rel="nofollow noreferrer">enter image description here</a></li>
<li>Add the zip file as dataset into my Experiment and connected to Script Bundle Input;
<a href="https://i.stack.imgur.com/thDfa.png" rel="nofollow noreferrer">enter image description here</a></li>
<li>Run the following script:
<a href="https://i.stack.imgur.com/4cj91.png" rel="nofollow noreferrer">enter image description here</a></li>
</ol>
<p>Then, I got the error:</p>
<pre><code>Error 0085: The following error occurred during script evaluation, please view the output log for more information:
---------- Start of error message from Python interpreter ----------
Caught exception while executing function: Traceback (most recent call last):
File "C:\server\invokepy.py", line 189, in batch
mod = import_module(moduleName)
File "C:\pyhome\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 662, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "C:\temp\6d718116a1f549e59a5b96c5d6360911.py", line 22, in <module>
import html5lib
ImportError: No module named 'html5lib'
Process returned with non-zero exit code 1
</code></pre>
<p>Any idea how can I fix this?</p>
<p>Thanks in advance.</p>
|
<p>This worked for me. Ran the following commands on windows command line. </p>
<pre><code>mkdir html5lib
# cd into above directory
pip install html5lib --target=.
# Zip the contents of the directory html5lib.zip
</code></pre>
<p>This is code in Python Script Module</p>
<p><a href="https://i.stack.imgur.com/srMsu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/srMsu.png" alt="This is code in Python Script Module"></a></p>
<p>This is screenshot of the experiment and success message after executing the experiment</p>
<p><a href="https://i.stack.imgur.com/D8Fmw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D8Fmw.png" alt="This is screenshot of the experiment and success message after executing the experiment"></a></p>
|
python|python-import|azure-machine-learning-studio
| 0 |
1,902,064 | 53,397,576 |
how to install python packages into nao's gentoo?
|
<p>I want to install numpy,PIL packages into Nao robot's hardware for my project. (python 2.7, Nao 1.14.5 Gentoo lınux) How Could I do that? Thanks in advance.</p>
|
<p>As mentioned <a href="https://stackoverflow.com/questions/48387823/install-things-on-pepper">here</a>: You might also not have root access on Nao, which limits where you can install.</p>
<p>you can install python packages with pip install but you need the --user tag</p>
<p>upgrade pip as descriped in the other post and</p>
<p>try</p>
<pre><code>pip install --user yourPackage
</code></pre>
<p>respective:</p>
<pre><code>/home/nao/.local/bin/pip install --user yourPackage
</code></pre>
<p>this will install the package to a directory where you have write access without root.</p>
|
python-2.7|numpy|installation|nao-robot
| 0 |
1,902,065 | 54,908,624 |
Panda reading csv with a datetime column
|
<p>I am trying to read a csv row like this:</p>
<pre><code>headers = ['col1', 'col2', 'col3', 'col4','col5','col6']
dtypes = {'col1': 'int', 'col2': 'str', 'col3': 'str', 'col4': 'str','col5': 'str','col6': 'int'}
test = pd.read_csv("solution.csv", sep=',', header=None, names=headers, dtype=dtypes, date_parser = pd.to_datetime)
</code></pre>
<p>if I now print out the values with test.values i get this array back:</p>
<pre><code>array([[107, 'Berg Live', 'Berg', '2017-01-08','Concert', 7]], dtype=object)
</code></pre>
<p>However I need the "col4" as a datetime.date because I want to compare it to a sql query.
Is there an easy way(preferably while reading the csv) to do that?
I able to get it back as an Timestamp but that is useless for me because the sql query gives an datetime.date back.</p>
<p>Solution i am looking for should look like this:</p>
<pre><code>array([[107, 'Berg Live', 'Berg',
datetime.date(2017, 1, 8), 'Concert', 7]], dtype=object)
</code></pre>
|
<p>Just tested it locally at my end. If you want to read a column as datetime while reading the CSV itself, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">parse_dates</a>:</p>
<p>So you can do:</p>
<pre><code>df = pd.read_csv("solution.csv", sep=',', header = None, names = headers, dtype = dtypes, parse_dates = ['col4'])
</code></pre>
|
pandas
| 0 |
1,902,066 | 54,872,828 |
Sphinx Docs | Can it support Algolia's Doc Search
|
<p>I am wondering if anyone, knows if Algolia's DocSearch Free Service for Docs, can be integrated into a Sphinx Documentation Website. Thank you..</p>
|
<p>It can definitely be integrated into a Sphinx-Documentation and that quite easily. </p>
<p>I applied for an account and got the API keys.</p>
<p>Read: <a href="https://community.algolia.com/docsearch/run-your-own.html" rel="nofollow noreferrer">https://community.algolia.com/docsearch/run-your-own.html</a></p>
<p>I installed the free <code>docsearch-scraper</code> from github under Python 2.7 and MacOS 10.13 and got it to work using pipenv and an additional post install of the missing dotenv module. </p>
<p>After some fiddling I used a self customized <code>config.json</code> based on the output of the <code>./docsearch bootstrap</code> command replacing all occurences of "FIXME" in the lines starting with "lvln" with ".section" and replacing "FIXME" in the line starting with "text" with ".document" (see example below).</p>
<p>We successfully indexed the Sphinx-Documentation and running the <code>.docsearch playground</code> command opened a test Webserver that delivered instantly excellent results.</p>
<p>We use the readthedocs <code>sphinx_rtd_theme</code> and you can add the CSS-Links and Javascript snippets from the algolia docs easily in a <code>page.html</code> template extension file created into the <code>_source/_templates/</code> folder (see below). This folder may be necessary to be registered in the <code>conf.py</code>of your setup!</p>
<p>Add this to your <code>conf.py</code> at the existing position:</p>
<pre><code># Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
</code></pre>
<p>and</p>
<pre><code># Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
</code></pre>
<p>I may come back here with a more detailled step-by-step guide, when I finish the integration.</p>
<p>example config.json:</p>
<pre><code>{
"index_name": "yourindexname",
"start_urls": [
"https://replaceme.com"
],
"stop_urls": [
"https://replaceme.com/omit"
],
"selectors": {
"lvl0": ".section h1",
"lvl1": ".section h2",
"lvl2": ".section h3",
"lvl3": ".section h4",
"lvl4": ".section h5",
"lvl5": ".section h6",
"text": ".document p, .document li"
},
}
</code></pre>
<p>more in: <a href="https://community.algolia.com/docsearch/config-file.html" rel="nofollow noreferrer">https://community.algolia.com/docsearch/config-file.html</a></p>
<p>This adds the algolia CSS and a <code>custom.css</code> file in the <code>_source/_static/</code> folder to override styles. Source of the snippets see <a href="https://community.algolia.com/docsearch/dropdown.html" rel="nofollow noreferrer">https://community.algolia.com/docsearch/dropdown.html</a></p>
<p>example <code>page.html</code> template:</p>
<pre><code>{% extends "!page.html" %}
{% set css_files = css_files + ["https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.css", "_static/custom.css"] %}
{% block footer %}
<script
src="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.js"></script>
<script>
docsearch({
// Your apiKey and indexName will be given to you once
// we create your config. The appId value is missing in the first
// version of this example and in the algolia community doc
// until today (5th march of 2019).
appId: '<your-app-id>',
apiKey: '<yourkey>',
indexName: '<yourindex>',
// Replace inputSelector with a CSS selector
// matching your search input
inputSelector: '#rtd-search-form input[type=text]',
// Set debug to true if you want to inspect the dropdown
debug: true
});
</script>
{% endblock %}
</code></pre>
<p>ToDo: Test links to the algolia community documentation</p>
<p>Tipp: You can test if the input selector works by adding this style to your <code>custom.css</code> file:</p>
<pre><code>#rtd-search-form input[type=text]{
background-color: #c51919; /* red */
}
</code></pre>
|
python-sphinx|algolia
| 1 |
1,902,067 | 55,099,757 |
OpenCV(4.0.0) assertion failed in function 'contourArea'
|
<p>My aim is to identify car logos using HOG descriptors. I am following tutorial linked <a href="https://gurus.pyimagesearch.com/lesson-sample-histogram-of-oriented-gradients-and-car-logo-recognition/#" rel="nofollow noreferrer">https://gurus.pyimagesearch.com/lesson-sample-histogram-of-oriented-gradients-and-car-logo-recognition/#</a> . I have testing and training images in separate folders.</p>
<p>While extracting HOG features using following code:</p>
<pre><code># import the necessary packages
from sklearn.neighbors import KNeighborsClassifier
from skimage import exposure
from skimage import feature
from imutils import paths
import argparse
import imutils
import cv2
# construct the argument parse and parse command line arguments
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--training", required=True, help="Path to the logos training dataset")
ap.add_argument("-t", "--test", required=True, help="Path to the test dataset")
args = vars(ap.parse_args())
# initialize the data matrix and labels
print('[INFO] extracting features...')
data = []
labels = []
# loop over the image paths in the training set
for imagePath in paths.list_images(args["training"]):
# extract the make of the car
make = imagePath.split("/")[-2]
# load the image, convert it to grayscale, and detect edges
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edged = imutils.auto_canny(gray)
# find contours in the edge map, keeping only the largest one which
# is presmumed to be the car logo
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
c = max(cnts, key=cv2.contourArea)
# extract the logo of the car and resize it to a canonical width
# and height
(x, y, w, h) = cv2.boundingRect(c)
logo = gray[y:y + h, x:x + w]
logo = cv2.resize(logo, (200, 100))
# extract Histogram of Oriented Gradients from the logo
H = feature.hog(logo, orientations=9, pixels_per_cell=(10, 10),
cells_per_block=(2, 2), transform_sqrt=True, block_norm="L1")
# update the data and labels
data.append(H)
labels.append(make)
</code></pre>
<p>I came across this error:</p>
<pre><code>/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/externals/joblib/externals/cloudpickle/cloudpickle.py:47: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
import imp
[INFO] extracting features...
Traceback (most recent call last):
File "hog.py", line 36, in <module>
c = max(cnts, key=cv2.contourArea)
cv2.error: OpenCV(4.0.0) /Users/travis/build/skvark/opencv-python/opencv/modules/imgproc/src/shapedescr.cpp:272: error: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function 'contourArea'
</code></pre>
<p>How do I remove this error ?.</p>
|
<p>Before finding countours of image <strong>edged</strong>, convert it into uint8 type:</p>
<pre><code>edged = np.uint8(edged)
cnts, _ = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
</code></pre>
<p>I have edited your code. I checked it on my system, it is working fine. Try this:</p>
<pre><code># import the necessary packages
from sklearn.neighbors import KNeighborsClassifier
from skimage import exposure
from skimage import feature
from imutils import paths
import argparse
import imutils
import cv2
# construct the argument parse and parse command line arguments
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--training", required=True, help="Path to the logos training dataset")
ap.add_argument("-t", "--test", required=True, help="Path to the test dataset")
args = vars(ap.parse_args())
# initialize the data matrix and labels
print('[INFO] extracting features...')
data = []
labels = []
# loop over the image paths in the training set
for imagePath in paths.list_images(args["training"]):
# extract the make of the car
make = imagePath.split("/")[-2]
# load the image, convert it to grayscale, and detect edges
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edged = imutils.auto_canny(gray)
# find contours in the edge map, keeping only the largest one which
# is presmumed to be the car logo
edged = np.uint8(edged)
cnts, _ = = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if cnts is not None:
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
c = max(cnts, key=cv2.contourArea)
# extract the logo of the car and resize it to a canonical width
# and height
(x, y, w, h) = cv2.boundingRect(c)
logo = gray[y:y + h, x:x + w]
logo = cv2.resize(logo, (200, 100))
# extract Histogram of Oriented Gradients from the logo
H = feature.hog(logo, orientations=9, pixels_per_cell=(10, 10),
cells_per_block=(2, 2), transform_sqrt=True, block_norm="L1")
# update the data and labels
data.append(H)
labels.append(make)
</code></pre>
|
python-3.x|opencv|computer-vision
| 3 |
1,902,068 | 73,545,574 |
Python Android App Crashes when saving file
|
<p>I am struggling trying to get my app to store a text file on an android device. I took some sample code from <a href="https://github.com/kivy/plyer/tree/master/examples/storagepath" rel="nofollow noreferrer">https://github.com/kivy/plyer/tree/master/examples/storagepath</a>. I installed in and it worked fine on my android device and also on windows. Here is the sample code, I deleted some lines as I am only interested in the 'Documents' path. On pressing a button, the button.text changes to the path to the My Documents file. According to <a href="https://developer.android.com/training/data-storage" rel="nofollow noreferrer">https://developer.android.com/training/data-storage</a> I don't need to request any permissions to do this</p>
<pre><code>'''
Storage Path Example.
'''
from kivy.lang import Builder
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
Builder.load_string('''
#: import storagepath plyer.storagepath
<StoragePathInterface>:
BoxLayout:
Button:
text: 'Documents'
on_press: label.text = str(storagepath.get_documents_dir())
''')
class StoragePathInterface(BoxLayout):
pass
class StoragePathApp(App):
def build(self):
return StoragePathInterface()
if __name__ == "__main__":
StoragePathApp().run()
</code></pre>
<p>When I tried to change the code so that it would save a text file, the code still worked on windows and the file was saved but it made the android device crash.All I did was add an Export method to the StoragePathInterface class</p>
<pre><code>class StoragePathInterface(BoxLayout):
ToPrint = ["Hello", "World", "This", "Is", "A", "Kivy", "App"]
def Export(self, path):
doc = open(f'{path}/Questions.txt', 'w')
for word in self.ToPrint:
doc.write(f"{word}\n")
doc.close()
</code></pre>
<p>And on the builder.load_string I allocated this method to the on_press of the Documents button with the path of the My Documents file as an argument</p>
<pre><code> Button:
text: 'Documents'
on_press: label.text = str(storagepath.get_documents_dir()); root.Export(str(storagepath.get_documents_dir()))
</code></pre>
<p>This saved the text file in windows but not in android, any ideas why it didn't work in android??</p>
<p>Thanks</p>
|
<p>So I found the answer here.. <a href="https://stackoverflow.com/questions/66639629/permissions-on-android-from-buildozer">Permissions on Android from Buildozer</a></p>
<p>added these few lines, didn't need to specify permissions in spec file but with these lines when the app opens, permission is requested and the button works!!</p>
<pre><code>from kivy.utils import platform
if platform == "android":
from android.permissions import request_permissions, Permission
request_permissions([Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE])
</code></pre>
|
python|kivy
| 0 |
1,902,069 | 73,803,919 |
Can I do a SQL select on a subquery and also retrieve the subquery?
|
<p>I have the following SQL:</p>
<pre><code>SELECT id, user_id, coordinates
FROM fields
WHERE id IN (SELECT field_id FROM transactions WHERE id IN (11,10,12))
</code></pre>
<p>There are 2 tables: transactions and fields. Both of them have their own id field. However, in transactions there's also a field to connect each row to the fields.id called field_id. I have a list of transactions.id, and I would like to obtain a few fields from table fields, but I would like to obtain too the transactions.id associated. For example for the first row it would be:</p>
<p>fields.id (for transactions.id=11), fields.user_id (for transactions.id=11), fields.coordinates (for transactions.id=11), 11</p>
<p>and so on.</p>
<p>Is this possible? I will do these queries using python with postgresql v14.</p>
|
<p>If I understood the question correctly</p>
<pre><code>SELECT * FROM fields f
join transactions t on f.id = t.field_id
WHERE t.id in (11,10,12)
</code></pre>
|
python|sql|postgresql
| 1 |
1,902,070 | 73,777,623 |
Django add file and select automatic employe id
|
<p>I would like to add documents to an employee's profile in a form but I would like the form to automatically select the employe id (Matricule), anyone have the solution?</p>
<p>models.py</p>
<pre><code>class Employe(models.Model):
Matricule = models.CharField(max_length=10, null=False)
Prenom = models.CharField(max_length=40, null=True)
Nom = models.CharField(max_length=40, null=True)
Tel = models.CharField(max_length=20, null=True)
Adresse = models.CharField(max_length=100, null=True)
Courriel = models.EmailField(max_length = 254)
class Document(models.Model):
employe = models.ForeignKey(Employe, null=True, on_delete=models.SET_NULL)
Description = models.CharField(max_length=100, null=True)
Fichier = models.FileField(upload_to='documents/')
</code></pre>
<p>views.py</p>
<pre><code>def createDocument(request, id):
employe = Employe.objects.only('Matricule')
forms = documentForm(instance=employe)
if request.method == 'POST':
forms = documentForm(request.POST, request.FILES)
if forms.is_valid():
forms.save()
return redirect('/employe')
context = {'forms':forms}
return render(request, 'accounts/document_form.html', context)
</code></pre>
<p><a href="https://i.stack.imgur.com/zP6RK.png" rel="nofollow noreferrer">Button</a>
<a href="https://i.stack.imgur.com/xWwcR.png" rel="nofollow noreferrer">Form</a></p>
|
<p>try this way:</p>
<pre><code>def createDocument(request, id):
data = get_object_or_404(Employe, id=id)
form = documentForm(instance=data)
if request.method == "POST":
form = documentForm(request.POST, instance=data)
if form.is_valid():
form.save()
return redirect('/employe')
context = {
"form":form
}
return render(request, 'accounts/document_form.html', context)
</code></pre>
|
python|html|django
| 0 |
1,902,071 | 13,157,302 |
python initialization of constants in separate file
|
<p>I have a question similar to the question asked here: <a href="https://stackoverflow.com/questions/6343330/importing-a-long-list-of-constants-to-a-python-file">Importing a long list of constants to a Python file</a></p>
<p>Basically, I have a separate module which just contains a long list of constants, e.g.
</p>
<pre><code>constants.py
x = 1.2
y = 30.4
.
.
.
</code></pre>
<p>In another module, I would like import these constants and initialize them as instance attributes.</p>
<pre><code>class.py
class something(object):
def __init__(self):
import constants
self.x = constants.x
self.y = constants.y
.
.
.
</code></pre>
<p>Is there an easier or more pythonic way to do this instead of retyping all of the variable names?</p>
|
<p>Python developers have developed a cool solution: it's called <a href="http://docs.python.org/2/library/configparser.html" rel="noreferrer">ConfigParser</a>.</p>
<p>A practical example: config.ini</p>
<pre><code>[constants]
key = value
x = 0
y = 1
</code></pre>
<p>class.py</p>
<pre><code>from ConfigParser import SafeConfigParser
class MyClass(object):
def __init__(self, **kwargs):
self.config = SafeConfigParser(defaults=kwargs).read('config.ini')
def get_x(self):
return self.config.get('constants', 'x')
</code></pre>
<p>I hope this helps.</p>
<p>EDIT: If you need instance attributes, you can do:</p>
<pre><code>class MyClass(object):
...
def __getattr__(self, key):
return self.config.get('constants', key)
</code></pre>
<p>EDIT2: need a Python file and a .ini file is not a solution?</p>
<pre><code>from . import config
class Myclass(object):
def __getattr__(self, key):
return getattr(config, key)
</code></pre>
|
python|class|import|constants
| 5 |
1,902,072 | 12,719,542 |
Decoding JSON from Reddit API in Python using PRAW
|
<p>I am using PRAW for Reddit API in a Python/GTK application. I have been successful in using the API, but I can't seem to be able to decode the JSON for use. It should be known that I am a beginner in Python and GTK applications.</p>
<pre><code># -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# This file is in the public domain
### END LICENSE
import gettext
from gettext import gettext as _
gettext.textdomain('redditreader')
from gi.repository import Gtk # pylint: disable=E0611
import logging
logger = logging.getLogger('redditreader')
from redditreader_lib import Window
from redditreader.AboutRedditreaderDialog import AboutRedditreaderDialog
from redditreader.PreferencesRedditreaderDialog import PreferencesRedditreaderDialog
import praw
import json
import simplejson
from pprint import pprint
# See redditreader_lib.Window.py for more details about how this class works
class RedditreaderWindow(Window):
__gtype_name__ = "RedditreaderWindow"
def finish_initializing(self, builder): # pylint: disable=E1002
"""Set up the main window"""
super(RedditreaderWindow, self).finish_initializing(builder)
self.AboutDialog = AboutRedditreaderDialog
self.PreferencesDialog = PreferencesRedditreaderDialog
# Code for other initialization actions should be added here.
r = praw.Reddit(user_agent='example')
try:
submissions = r.get_front_page(limit=5)
[str(x) for x in submissions]
jsondatafirst = simplejson.loads(str(submissions))
jsondata = unicode(jsondatafirst, 'utf-8')
print(jsondata)
except (simplejson.decoder.JSONDecodeError, ValueError):
print 'Decoding JSON has failed'
</code></pre>
|
<p>With PRAW you do not need to do any json decoding as PRAW handles all of that for you.</p>
<p>Say for example for each submission you want to print out the number of upvotes, the number of downvotes, and the submission title. You could do:</p>
<pre><code>for submission in r.get_front_page(limit=5):
print submission.ups, submission.downs, submission.title
</code></pre>
<p>If you want to see all the attributes available to use on a submission object you can run:</p>
<pre><code>import pprint
for submission in r.get_front_page(limit=5):
pprint.pprint(vars(submission))
</code></pre>
<p>Additionally if you want to get the comments from a submission then you can use the <code>submission.comments</code> property. You can also manually look at the json response for a request to see what attributes <em>should</em> be available through PRAW (<a href="http://www.reddit.com/.json?limit=5" rel="nofollow">example</a>).</p>
<p>The attributes are not explicitly listed anywhere for the objects because the attributes are created directly from whatever the key name is in the associated json response for the request.</p>
|
python|json|api|gtk|reddit
| 3 |
1,902,073 | 41,200,283 |
creating an object doesn't work
|
<pre><code>class phonebook:
def __init__(self,first_name, last_name, street, postcode, city, number):
root = tk.Tk()
root.title('Book')
menubar = tk.Menu(root)
root.config(menu = menubar)
menubar.add_command(label = 'Anlegen', command = self.create)
menubar.add_command(label = 'Bearbeiten', command = self.change)
menubar.add_command(label = 'Löschen')
menubar.add_command(label = 'Sortieren')
menubar.add_command(label = 'Suche')
menubar.add_command(label = 'Hilfe')
root.mainloop()
def printing(self):
account = (self.first_name.get(), self.last_name.get(), self.street.get(), self.postcode.get(), self.city.get(), self.number.get())
accounts.append(account)
for i in accounts:
print(i)
def change(self):
account = accounts[0]
account.first_name = 'test'
self.printing
def create(self):
creation = tk.Toplevel()
tk.Label(creation, text = 'Vorname').grid(row = 1, column = 0)
tk.Label(creation, text = 'Nachname').grid(row = 2, column = 0)
tk.Label(creation, text = 'Stadt').grid(row = 3, column = 0)
tk.Label(creation, text = 'Postleitzahl').grid(row = 4, column = 0)
tk.Label(creation, text = 'Straße').grid(row = 5, column = 0)
tk.Label(creation, text = 'Telefonnummer').grid(row = 6, column = 0)
self.first_name = tk.Entry(creation)
self.last_name = tk.Entry(creation)
self.city = tk.Entry(creation)
self.postcode = tk.Entry(creation)
self.street = tk.Entry(creation)
self.number = tk.Entry(creation)
a = tk.Button(creation, text = 'end', command = self.printing)
self.first_name.grid(row = 1, column = 1)
self.last_name.grid(row = 2, column = 1)
self.city.grid(row = 3, column = 1)
self.postcode.grid(row = 4, column = 1)
self.street.grid(row = 5, column = 1)
self.number.grid(row = 6, column = 1)
a.grid(row = 7, column = 1)
phonebook()
</code></pre>
<p>As you can see in my code I'm trying to create and edit objects. The problem is that I cannot create a real object. When I want to create a object with class <code>phonebook</code>, I get this error:</p>
<blockquote>
<p>TypeError: <code>__init__()</code> missing 6 required positional arguments: 'first_name', 'last_name', 'street', 'postcode', 'city', and 'number'</p>
</blockquote>
<p>What do I have to do so that I don't get this error and so that I can edit the objects?</p>
|
<p><code>phonebook</code> must be called with 6 arguments, not 0. You call <code>phonebook()</code>, which causes your code to break. Try calling with something like this:</p>
<pre><code>phonebook("first_name", "last_name", "street", "post_code", "your_city", 123)
</code></pre>
<p>substitute in the appropriate values instead of the ones I've provided.</p>
<p>P.S. You won't get much help on this site with a username like that</p>
|
python|object|typeerror
| 0 |
1,902,074 | 40,820,955 |
Numpy Average distance from array center
|
<p>I have the center point of an array, </p>
<pre><code>center_point = (array.shape[0]/2.,array.shape[1]/2.)
</code></pre>
<p>I have a binary image array, <code>array</code>, which has a shape whose relevant pixels are set to 0 (all other pixels are 255). </p>
<hr>
<p>I need the average distance from the center of the array for all the pixels set to zero, and I need it to be vectorized (it can't be interpreted at the python level--way to slow). </p>
<p>Here is what I have, and now I am stuck, because the other answers I found point to SciPy, but the server <strong>only</strong> supports numpy. </p>
<pre><code>centerpoint = array_center_point(shape_array)
distance_shape = np.zeros(size=shape_array.shape,dtype=float)
distance_shape[shape==0] = ...???
avg_distance = np.sum(distance_shape) / len(np.where(shape_array == 0)[0])
</code></pre>
<p>I can't figure out how to do this without making multiple calls to np.where and iterating through the shape indices with a python for loop. There must be a way to get this done inside the numpy code...??</p>
<hr>
<p>Here is the non-vectorized version that works:</p>
<pre><code>def avg_distance_from_center(shape_array):
center_point = array_center_point(shape_array)
distance_shape = np.zeros(shape=shape_array.shape, dtype=float)
shape_pixels = np.where(shape_array == 0)
total_distance = 0.
for i in range(len(shape_pixels[0])):
i_ind = float(shape_pixels[0][i])
j_ind = float(shape_pixels[1][i])
total_distance += ((i_ind - center_point[0])**2.0 + (j_ind - center_point[1])**2.0)**0.5
avg_distance = total_distance / len(shape_pixels[0])
return avg_distance
</code></pre>
|
<p><strong>Approach #1 :</strong> With <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>NumPy broadcasting</code></a> -</p>
<pre><code>np.sqrt(((np.argwhere(shape_array==0) - center_point)**2).sum(1)).mean()
</code></pre>
<p><strong>Approach #2 :</strong> With <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a> -</p>
<pre><code>subs = (np.argwhere(a==0) - center_point)
out = np.sqrt(np.einsum('ij,ij->i',subs,subs)).mean()
</code></pre>
|
python|arrays|performance|numpy|vectorization
| 4 |
1,902,075 | 41,195,446 |
How to pass multiple date1 i.e(10/12/2016) , date2 i.e(23/12/2016) to url in django?
|
<p>I am trying to pass starting_date i.e(10/12/2016) ,report_to_date i.e(23/12/2016)</p>
<pre><code>starting_date = '31/12/2015'
report_to_date = '31/12/2016'
<a class ="btn btn-success" href="/downloadpdf/"+starting_date+"/"+report_to_date+"/">Download</a>
</code></pre>
<p>below url not working -</p>
<pre><code>url(r'^/downloadpdf/(?P<starting_date>[A-Za-z0-9+/=]+)/(?P<report_to_date>[A-Za-z0-9+/=]+)/$', views.report, name='report'),
</code></pre>
<p>I need the date i.e '31/12/2015' and i.e '31/12/2016' format/date object to my view function :</p>
<pre><code>def report(request,starting_date,report_to_date):
starting_date = parse('starting_date')
report_to_date = parse('report_to_date')
</code></pre>
<p>this is not working. Please help me.. Thanks in advance.</p>
|
<p>As @Felk said in <a href="https://stackoverflow.com/questions/41195446/how-to-pass-multiple-date1-i-e10-12-2016-date2-i-e23-12-2016-to-url-in-dja#comment69590924_41195446">comment</a> you need to change date format to dd-mm-YYYY to avoid problems with readability.</p>
<p>For that you need to change urlpattern to accept <code>-</code> and numbers:</p>
<pre><code>url(r'^downloadpdf/(?P<starting_date>[0-9-]+)/(?P<report_to_date>[0-9-]+)$', views.report, name='report')
</code></pre>
<p>Now you can use this pattern inside template like this:</p>
<pre><code><a href="{% url 'report' starting_date='17-12-2016' report_to_date='17-12-2016' %}">date</a>
</code></pre>
<p>To parse date values inside view you can use <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime" rel="nofollow noreferrer">strptime</a> function:</p>
<pre><code>import datetime
...
def report(request, starting_date, report_to_date):
starting_date = datetime.datetime.strptime(starting_date, '%d-%m-%Y').date()
report_to_date = datetime.datetime.strptime(report_to_date, '%d-%m-%Y').date()
</code></pre>
|
javascript|jquery|python|html|django
| 0 |
1,902,076 | 38,341,716 |
Iterating over Multiple Lists in Python When the Lists are Different Lengths
|
<p>I have this table of data that I'm pulling from a MySQL database and trying to match up the rows and I am having trouble figuring out this last piece of it. I'm using Flask to pass three lists of dictionaries using 'izip_longest' to the Jinja template and then a for loop inside the Jinja template to go through the variables from each row. The problem is the three lists I'm iterating through have variable lengths and aren't always going to be the same length.</p>
<p>I've gotten this far as shown below, but I need the dates to match across the entire row. In this case, S-Date/07-11 should either be 07-11 across the whole row, or be blank in the other columns.</p>
<pre><code>S-Date | S-Place | G-Date | G-Place | F-Date | F-Place
------------------------------------------------------
07-11 7 07-12 7 07-11 7
07-12 7 07-13 7
07-13 7 07-14 7
07-14 7
</code></pre>
<p>I feel like I'm close to figuring it out but I've been staring at this forever and can't quite get it.</p>
<p>This is the SQL table I'm drawing data from:</p>
<pre><code>location | date | status
------------------------
001 07-10 success
002 07-10 success
123 07-11 fail
222 07-11 fail
333 07-11 fail
232 07-11 fail
444 07-12 pending
555 07-13 pending
</code></pre>
<p>This is the query to get the number of failures for each particular day:</p>
<pre><code>SELECT 'date', COUNT(`location`) as 'location' FROM mytable
WHERE YEARWEEK(`date`, 1) = YEARWEEK(CURDATE(), 1)
AND `status` LIKE '%fail%' GROUP BY DATE(`date`)
</code></pre>
<p>This is for the number of successes per day:</p>
<pre><code>SELECT `date`, COUNT(`location`) as 'location' FROM mytable
WHERE YEARWEEK(`date`, 1) = YEARWEEK(CURDATE(), 1)
AND `status` NOT LIKE '%fail%' GROUP BY DATE(`date`)
</code></pre>
<p>I need the failures and successes to match up to the day grouping so I can generate a stacked bar chart to show each number for a single date/bar.</p>
|
<p>Not really sure what all this <code>S-Date</code>, <code>F-Date</code> business is, but I think what you want to know is how many total success and failures you have for each unique date.</p>
<p>I have a very simple solution for you in Python:</p>
<pre><code>from collections import defaultdict
from collections import Counter
data = defaultdict(list)
for row in database_table:
data[row[1]].append(row[2])
results = {}
for date, attempts in data.iteritems():
stats = Counter(attempts)
results[date] = {'total': len(attempts)}
for stat, count in stats.most_common():
results[date][stat] = count
</code></pre>
<p>Now results is a dictionary, with the key being the date, and the value is another dictionary with all your stats. In your template you would simply:</p>
<pre><code><table>
<thead>
<tr>
<th>Date</th>
<th>Total Places</th>
<th>Success</th>
<th>Failed</th>
<th>Pending</th>
</tr>
</thead>
<tbody>
{% for date, stats in results.iteritems() %}
<tr>
<td>{{ date }}</td>
<td>{{ stats['total'] }}</td>
<td>{{ stats['success'] }}</td>
<td>{{ stats['fail'] }}</td>
<td>{{ stats['pending'] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</code></pre>
<blockquote>
<p>One thing I'm having trouble with is the dates aren't showing in the
correct order. They go from 07-14 to 07-11, rather than 07-11 to
07-14. I know Python dictionaries are not ordered so now I need to
investigate how to get the dates ordered correctly.</p>
</blockquote>
<p>To sort the dates, you need to convert them first to datetime objects; so that the sorting works properly.</p>
<pre><code>import datetime
# rest of the code here
fmt = '%m-%d'
results = [] # a list, so its sortable
for date, attempts in data.iteritems():
stats = Counter(attempts)
record = {'total': len(attempts),
'date': datetime.datetime.strptime(date, fmt)}
for stat, count in stats.most_common():
record[stat] = count
results.append(record)
results = sorted(results, key=lamdba x: x['date'])
</code></pre>
<p>Then, just adjust your template:</p>
<pre><code>{% for record in results %}
<tr>
<td>{{ record['date'] }}</td>
<td>{{ record['total'] }}</td>
<td>{{ record['success'] }}</td>
<td>{{ record['fail'] }}</td>
<td>{{ record['pending'] }}</td>
</tr>
{% endfor %}
</code></pre>
|
python|mysql|for-loop|flask|jinja2
| 1 |
1,902,077 | 31,061,894 |
Serving static files when in deployment mode with debug = false
|
<p>I have deployed my app on heroku and I am serving static files using <code>whitenoise</code>.
Everything works perfectly, but when I turn <code>debug=false</code> the css stops being rendered.What could be the issue here? The static files are not be supplied by django but by <code>whitenoise</code>.Can't figure it out.</p>
<p>relevant <code>settings.py</code></p>
<pre><code> STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
</code></pre>
<p>project's <code>urls.py</code></p>
<pre><code>urlpatterns = [
url(r'^', include('watch.urls', namespace="watch")),
url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code></pre>
<p>template's static file declaration</p>
<pre><code>{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'css/finale.css' %}" />
</code></pre>
|
<p>You should start by following the <a href="https://whitenoise.readthedocs.org/en/latest/django.html" rel="nofollow">documentation on using WhiteNoise with Django</a> more closely. The first difference I see is that your line:</p>
<pre><code>STATIC_ROOT = 'staticfiles'
</code></pre>
<p>differs from the docs:</p>
<pre><code>STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
</code></pre>
<p>If following that tutorial doesn't work you should make sure to include all the relevant parts of your app (e.g., I'd need to see <code>wsgi.py</code> along with the files you show above) including all the <code>WHITENOISE_XXXXXX</code> settings in your <code>settings.py</code> to figure out the issue.</p>
|
python|django|heroku|django-staticfiles|django-settings
| 0 |
1,902,078 | 30,969,571 |
Specifying amount of numbers to sum in loop
|
<p>I think the best way to explain my predicament is with an example. Say I have a file that contains this information:</p>
<pre><code>isoform snp_rein
NM_005101 97
NM_005101 144
NM_198576 20790
</code></pre>
<p>and a dictionary that looks like so:</p>
<pre><code>exons = {'NM_005101': [(0, 110), (517, 1073)], 'NM_198576': [(0, 251), (2078, 2340), (15154, 15202), (20542, 20758), (21050, 21275), (21355, 21580), (21833, 22040), (23116, 23335), (23415, 23610), (23700, 23901), (23986, 24135), (24211, 24317), (25038, 25155), (25236, 25401), (25610, 25754), (25841, 25966), (26037, 26143), (26274, 26613), (26697, 26835), (27204, 27332), (27450, 27565), (27653, 27773), (27889, 28243), (28744, 28937), (29113, 29329), (29443, 29673), (29780, 29915), (30110, 30207), (30304, 30469), (30603, 30715), (31130, 31247), (31330, 31523), (31605, 31693), (33630, 33855), (34325, 34429), (34701, 35997)]}
</code></pre>
<p>I've been working on some code that finds between which pair of numbers the <code>snp_rein</code> number lies. I then was able to calculate the difference between the max of the first set of numbers and the min from the second set of numbers and so on. My code is as below:</p>
<pre><code>totalintron=0
if name in exons:
y = exons[name]
for sd, i in enumerate(exons[name]):
if snpos<=max(i):
exonnumber = sd+1
position = sd
print exonnumber
break
for index in range(len(y) -1):
first_max = max(y[index])
second_min = min(y[index + 1])
intron = second_min - first_max
print intron
totalintron = totalintron + intron
print totalintron
totalintron = 0
</code></pre>
<p>My output looks as so: (<code>**x**</code> indicates the <code>exonnumber</code> and the last number indicates the total I want to change):</p>
<pre><code>**1**
407
407
**2**
407
407
**5**
1827
12814
5340
292
80
253
1076
80
90
85
76
721
81
209
87
71
131
84
369
118
88
116
501
176
114
107
195
97
134
415
83
82
1937
470
272
28671
</code></pre>
<p>My problem lies with the total. I want to total only the amount of numbers specified by the exonnumber. For the first output I would want the total to read 0 because the tested number was within the specified ranged for exon 1. For the second output I want the total to read 407 because it was in the exon 2. For the last output, I want to sum the first 4 numbers because the the tested number was in exon 5. </p>
<p>This is what I want my output to look like:</p>
<pre><code>**1**
0
**2**
407
**5**
20273
</code></pre>
<p>Any suggestions on how to change the way I total to only total for a specified amount of numbers, if that makes sense? Please explain what you suggest because I'm new to python...</p>
|
<p>You want that last inner loop to look like this:</p>
<pre><code># reset the `totalintron` for the current `exonnumber`
totalintron = 0
# only iterate `exonnumber - 1` (which is guaranteed to be len(y) - 1 at max)
for index in range(exonnumber - 1):
first_max = max(y[index])
second_min = min(y[index + 1])
intron = second_min - first_max
# don’t print `intron`, we only care about the total
totalintron = totalintron + intron
print totalintron
</code></pre>
|
python
| 1 |
1,902,079 | 30,771,380 |
how use ctypes with msvc*.dll from within matlab on windows
|
<p>i'm using winpython (2.7) on windows 7/64, matlab 2015a, with matlab's new <a href="http://www.mathworks.com/help/matlab/call-python-libraries.html" rel="nofollow noreferrer">python bridge</a>. </p>
<pre><code>>> py.ctypes.util.find_library('c')
ans =
Python str with no properties.
msvcr90.dll
>> py.ctypes.util.find_msvcrt()
ans =
Python str with no properties.
msvcr90.dll
>> py.ctypes.CDLL(py.ctypes.util.find_library('c'))
Python Error: [Error 1114] A dynamic link library (DLL) initialization routine failed
>> x=CDLL('C:\Users\nlab\Downloads\WinPython-64bit-2.7.9.5\python-2.7.9.amd64\msvcr90.dll')
Python Error: [Error 1114] A dynamic link library (DLL) initialization routine failed
</code></pre>
<p>a popup also comes up: </p>
<pre><code>Microsoft Visual C++ Runtime Library
R6034 "an application has made an attempt to load the c runtime library incorrectly"
</code></pre>
<p>a <a href="https://stackoverflow.com/a/14680947/1441998">couple other</a> <a href="https://stackoverflow.com/questions/27273594/run-time-error-r6034-when-compiling-from-the-command-prompt#comment43021210_27273594">SO answers</a> suggest it's matlab putting its incompatible copy of msvc*.dll somewhere on the path, so i removed everything not from WinPython in sys.path (just matlab's <code>\bin\win64\</code> and the <code>\Python27\site-packages\</code> from another python install i have):</p>
<pre><code>>> py.pprint.PrettyPrinter().pprint(py.sys.path)
['',
'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\python27.zip',
'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\DLLs',
'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib',
'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib\\plat-win',
'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib\\lib-tk',
'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64',
'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib\\site-packages',
'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib\\site-packages\\FontTools',
'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib\\site-packages\\win32',
'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib\\site-packages\\win32\\lib',
'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib\\site-packages\\Pythonwin']
</code></pre>
<p>there are still tons of msvc*.dll sprinkled everywhere on the system, and surely some on the PATH:</p>
<pre><code>>> x = py.os.environ
x =
Python _Environ with properties:
data: [1x1 py.dict]
{'TMP': 'C:\\Users\\nlab\\AppData\\Local\\Temp', <<snip>>, 'USERPROFILE': 'C:\\Users\\nlab'}
>> cellfun(@(s)fprintf('%s\n',s),strsplit(char(x{'PATH'}),';'))
C:\Program Files\Haskell\bin
C:\Program Files\Haskell Platform\2014.2.0.0\lib\extralibs\bin
C:\Program Files\Haskell Platform\2014.2.0.0\bin
C:\Users\nlab\Downloads\WinPython-64bit-2.7.9.5\python-2.7.9.amd64
C:\Users\nlab\Downloads\opencv\build\x64\vc12\bin
C:\ProgramData\Oracle\Java\javapath
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v5.0\bin\
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v5.0\libnvvp\
C:\Program Files\ImageMagick-6.8.3-Q16
C:\Program Files (x86)\OSSBuild\GStreamer\v0.10.7\bin
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.1\\bin
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.1\libnvvp\
C:\Program Files (x86)\PHP\
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Program Files\Intel\DMIX
C:\Program Files\TortoiseSVN\bin
C:\Program Files\SlikSvn\bin\
C:\Program Files\MySQL\MySQL Server 5.5\bin
C:\Program Files (x86)\Common Files\Acronis\SnapAPI\
C:\Program Files (x86)\PostgreSQL\9.2\bin
C:\Python27
C:\Python27\Scripts
C:\Program Files\Microsoft SQL Server\110\Tools\Binn\
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\Program Files (x86)\LilyPond\usr\bin
C:\Program Files (x86)\Git\cmd
C:\Program Files\Microsoft Windows Performance Toolkit\
C:\Program Files\TortoiseGit\bin
C:\Program Files (x86)\QuickTime\QTSystem\
C:\Program Files (x86)\Skype\Phone\
C:\Program Files\Mosek\7\tools\platform\win64x86\bin
C:\Program Files\Haskell Platform\2014.2.0.0\mingw\bin
C:\Users\nlab\AppData\Roaming\cabal\bin
C:\Program Files (x86)\SSH Communications Security\SSH Secure Shell
C:\Gtk+\bin
</code></pre>
<p>i notice that in <code>C:\Program Files\MATLAB\R2015a\bin\win64\</code> we only have <code>msvc[r|p][100|110].dll</code> -- does that mean it won't work with a distribution of python based on msvcr90 like winpython 2.7.9.5?</p>
|
<p>@eryksun's method works.</p>
<p>the question remains, why are <code>ctypes.cdll.msvcrt</code> and <code>find_library('c')</code> implemented the way they are? they should just use @eryksun's method to return the dll in python's manifest, right?</p>
<pre><code>from ctypes import *
from ctypes.wintypes import *
kernel32 = WinDLL("kernel32")
ACTCTX_FLAG_PROCESSOR_ARCHITECTURE_VALID = 0x001
ACTCTX_FLAG_LANGID_VALID = 0x002
ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID = 0x004
ACTCTX_FLAG_RESOURCE_NAME_VALID = 0x008
ACTCTX_FLAG_SET_PROCESS_DEFAULT = 0x010
ACTCTX_FLAG_APPLICATION_NAME_VALID = 0x020
ACTCTX_FLAG_HMODULE_VALID = 0x080
DEACTIVATE_ACTCTX_FLAG_FORCE_EARLY_DEACTIVATION = 1
INVALID_HANDLE_VALUE = HANDLE(-1).value
ULONG_PTR = WPARAM # pointer-sized unsigned integer
class ACTCTX(Structure):
_fields_ = (("cbSize", ULONG),
("dwFlags", DWORD),
("lpSource", LPCWSTR),
("wProcessorArchitecture", USHORT),
("wLangId", LANGID),
("lpAssemblyDirectory", LPCWSTR),
("lpResourceName", LPCWSTR),
("lpApplicationName", LPCWSTR),
("hModule", HMODULE))
def __init__(self, *args, **kwds):
super(ACTCTX, self).__init__(sizeof(self), *args, **kwds)
CreateActCtxW = kernel32.CreateActCtxW
CreateActCtxW.restype = HANDLE
CreateActCtxW.argtypes = (POINTER(ACTCTX),)
ReleaseActCtx = kernel32.ReleaseActCtx
ReleaseActCtx.restype = None
ReleaseActCtx.argtypes = (HANDLE,)
ActivateActCtx = kernel32.ActivateActCtx
ActivateActCtx.argtypes = (HANDLE, POINTER(ULONG_PTR))
DeactivateActCtx = kernel32.DeactivateActCtx
DeactivateActCtx.argtypes = (DWORD, ULONG_PTR)
def getMsvcr90():
ctx = ACTCTX(hModule = cdll.python27._handle
,lpResourceName = c_wchar_p(2)
,dwFlags = ACTCTX_FLAG_HMODULE_VALID | ACTCTX_FLAG_RESOURCE_NAME_VALID
)
hActCtx = CreateActCtxW(byref(ctx))
if hActCtx == INVALID_HANDLE_VALUE:
raise WinError()
cookie = ULONG_PTR()
if not ActivateActCtx(hActCtx, byref(cookie)):
raise WinError()
msvcr90 = CDLL("msvcr90")
if not DeactivateActCtx(0, cookie):
raise WinError()
ReleaseActCtx(hActCtx)
# show DLL path
hModule = HANDLE(msvcr90._handle)
path = (c_wchar * 260)()
kernel32.GetModuleFileNameW(hModule, path, len(path))
print(path.value)
return msvcr90
</code></pre>
|
python|matlab|ctypes|msvcrt|msvcr90.dll
| 0 |
1,902,080 | 29,262,625 |
BeautifulSoup Cannot Find Tag
|
<p>I am trying to scrape <a href="http://www.presidency.ucsb.edu/ws/index.php?pid=99556" rel="nofollow">this page</a> and all of the other pages like it. I have been using BeautifulSoup (also have tried lxml but there have been installation issues). I am using the following code:</p>
<pre><code>value = "http://www.presidency.ucsb.edu/ws/index.php?pid=99556"
desiredTag = "span"
r = urllib2.urlopen(value)
data = BeautifulSoup(r.read(), 'html5lib')
displayText = data.find_all(desiredTag)
print displayText
displayText = " ".join(str(displayText))
displayText = BeautifulSoup(displayText, 'html5lib')
</code></pre>
<p>For some reason this isn't pull back the <code><span class="displaytext"></code> and also I have tried <code>desiredTag</code> as <code>p</code></p>
<p>Am I missing something?</p>
|
<p>You are definitely experiencing the differences <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#differences-between-parsers" rel="nofollow">between different parsers</a> used by <code>BeautifulSoup</code>. <code>html.parser</code> and <code>lxml</code> worked for me:</p>
<pre><code>data = BeautifulSoup(urllib2.urlopen(value), 'html.parser')
</code></pre>
<p>Proof:</p>
<pre><code>>>> import urllib2
>>> from bs4 import BeautifulSoup
>>>
>>> url = "http://www.presidency.ucsb.edu/ws/index.php?pid=99556"
>>>
>>> data = BeautifulSoup(urllib2.urlopen(url), 'html.parser')
>>> data.find("span", class_="displaytext").text
u'PARTICIPANTS:Former Speaker of the House Newt Gingrich (GA);
...
</code></pre>
|
python|web-scraping|beautifulsoup
| 3 |
1,902,081 | 29,001,671 |
Python Sudoku Reduce the number of for loops
|
<p>I am trying to solve the sudoku problem and I need to add all the tuples that satisfy the constraint.</p>
<p>Here is the problem,</p>
<p>The variables contain non-repeated number from 0 to 9 in sorted order. The domain of each variable can be different.</p>
<p>Eg: </p>
<p>v1 = [1,2,3,4]</p>
<p>v2 = [3,4,6,7]</p>
<p>v3 = [3,5,7,8,9]</p>
<p>...</p>
<p>v9 = [1,2,3,4,5,6,7,8,9]</p>
<p>I want all sets of number where there is no repeated number, </p>
<p>I have come up with the following cumbersome and slow algorithm, but is there a better way to do this?</p>
<pre><code>for d0 in v1:
for d1 in v2:
...
for d9 in v9:
if d0 != d1 and d0 != d2 and d0 != d3 ... d0 != d9
...
and d7 != d8 and d7 != d9:
and d8 != d9:
print(d0,d1,d2,d3,d4,d5,d6,d7,d8,d9)
</code></pre>
<p>Is there a more effective way of doing it without using 9 for loops and a long list of and statements??</p>
<p>I can't use the constraint solver like python-constraint since I need to implement it.</p>
|
<p>I wrote a sudoku solver a while back for fun...</p>
<p>I've posted the code for your reference. It's actually really efficient. I also explain it at the end.</p>
<pre><code>#imports
import sys
import time
#test sudoku puzzle
a = [[0, 6, 0, 1, 3, 0, 0, 0, 8],
[0, 0, 2, 0, 0, 6, 0, 0, 0],
[1, 8, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 7, 0, 4, 2, 0, 0, 0],
[5, 0, 0, 0, 0, 0, 0, 0, 9],
[0, 0, 0, 5, 9, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 9, 2],
[0, 0, 0, 7, 0, 0, 3, 0, 0],
[7, 0, 0, 0, 1, 3, 0, 4, 0]]
'''
a = [[0, 0, 4, 0],
[0, 2, 0, 3],
[2, 0, 0, 0],
[0, 4, 0, 1]]
'''
#store all of the cells that have been solved already
solved = {}
for p in range(len(a)):
for q in range(len(a)):
if a[p][q] != 0:
solved[p, q] = 1
#denotes what direction the code is moving (if it is moving backwards, then we want the already solved cells to return, and if it is moving forwards, we want the solved cells to call next)
goingForward = True
#if the sudoku is solved or not
done = False
# number of iterations
counter = 0
#prints a sudoku neatly
def printSudoku(a):
for i in a:
array = ""
for j in i:
array += str(j) + " "
print array
def next(i, j, a):
global counter
global goingForward
global done
if done:
return
counter += 1
# gets the vertical in which a[i][j] is located
vertical = [z[j] for z in a]
# gets the "box" in which a[i][j] is located
box = []
x = (i/3 + 1)*3
y = (j/3 + 1)*3
for p in range(x-3, x):
for q in range(y-3, y):
box.append(a[p][q])
#if it already solved and it is going forward, call next
#else, return
if solved.has_key((i, j)):
if i == 8 and j == 8:
done = True
printSudoku(a)
return
if goingForward:
if j==8:
next(i+1, 0, a)
else:
next(i, j+1, a)
else:
return
#try every number for cell a[i][j]
#if none work, return so that the previous number may be changed
else:
for k in range(1, 10):
if k not in a[i] and k not in vertical and k not in box:
a[i][j] = k
if i == 8 and j == 8:
done = True
printSudoku(a)
return
if j==8:
goingForward = True
next(i+1, 0, a)
a[i][j] = 0
else:
goingForward = True
next(i, j+1, a)
a[i][j] = 0
goingForward = False
return
start_time = time.time()
#where we actually call the function
next(0, 0, a)
if done == False:
print "no solution!!"
print "It took " + str(time.time()-start_time) + " to solve this sudoku"
print "With " + str(counter) + " iterations"
</code></pre>
<p>This uses a technique called recursive backtracking. It starts at the very first cell and tries all possible values. If it finds a possible solution, then it keeps that value and goes on the next cell. For that cell, it employs the same method, trying all values from 1-9 until one works, then moving to the next cell. When it encounters a cell for which no values work, it gives up and goes to the previous cell, where it is determined that that particular value does not work and a new one must be used. The previous cell skips the errant value and goes to the next integer. Through a combination of backtracking and guessing, it eventually arrives at the correct answer.</p>
<p>It's also super speedy since a lot of the cases are skipped due to the error backtracking. For most "guessed" values, it does not get past the third or fourth cell.</p>
|
python|sudoku
| 1 |
1,902,082 | 29,223,453 |
Python: Get new list without items in other list
|
<p>I want to create a new list with elements in mainlist except those in other list</p>
<p>How to do below in python 2.7. Is there any fast builtin function to do it?</p>
<pre><code> Input (Mainlist) :[['P', ['not', 'R']], [['not', 'Q'], ['not', 'R'], 'P']]
Input (Otherlist) : ['P', ['not', 'R']]
Output (NewlistIwant) : [['not', 'Q']]
</code></pre>
<p>i.e everything in main list except two items 'P' and ['not','R']</p>
|
<p>If I'm understanding you right, you have a list of lists, of which each list has some combination of strings and lists. You want to strip out everything that is in the inner list that is in the other list.</p>
<p>The following code works for me.</p>
<pre><code>>>> mainlist = [['P', ['not', 'R']], [['not', 'Q'], ['not', 'R'], 'P']]
>>> otherlist = ['P', ['not', 'R']]
>>> def filter_list():
newlist = []
for list_ in mainlist:
for item in list_:
if item not in otherlist:
newlist.append(item)
return newlist
>>> filter_list()
[['not', 'Q']]
</code></pre>
<p>Note that this isn't safe - if you mutate the old list you'll mess up your new list.</p>
<pre><code>>>> a = filter_list()
>>> mainlist[1][0][1] = 'L'
>>> a
[['not', 'L']]
</code></pre>
<p>It was unclear if you wanted this behavior or not.</p>
|
python|python-2.7
| 1 |
1,902,083 | 29,245,204 |
Force a function to exit
|
<p>I've tried everything from using <code>return</code> to <code>sys.exit</code> to <code>SystemExit</code> and it doesn't work.</p>
<p>I have a <code>main</code> function, that runs the 1st function; at the end of the 1st function it runs the 2nd function; at the end of the 2nd function it runs the 3rd function; and after that it asks whether I want to run the program again or exit. No matter the choice, it always returns me to <code>main</code>. </p>
<p>Is there a way to force close a function inside a function inside a function inside a function?</p>
<p>edit:
example:</p>
<pre><code>def main(RPNlist):
some code here
#this function converts a .txt file to a list, wich is a math operation
y=list
print(list)
return(func2(y))
def func2(y):
some code here
#this function converts the operation to reverse polish notation
z=RPNlist
print(RPNlist)
return(function3(RPNlist))
def func3(RPNlist):
some code here
# this solves the RPN operation
a=answer
print(a)
choice=input("do you want to exit?(Input y to continue or n to exit): ")
if choice=="y":
return(main(x))
elif choice=="n":
#here's the part where I need to exit
#I think this may be the issue, but is the only way I found for the whole program to run
global RPNlist
RPNlist=[]
main(RPNlist)
</code></pre>
|
<p>It's really depend of your code.</p>
<pre><code>return value
</code></pre>
<p>It will always quit your function. The problem is not here. Maybe the return is not called (if it's in a if). Maybe you have a loop, in that case, use a break to exit the loop. Let the app close by itself. When there is no method call remaining, the app will exit by itself. Just get out of the loop. You can also put a condition for the loop if it's an infinite loop, put a boolean in it then turn the boolean to false. </p>
<p>It's hard to help without your code, you need to show your code if you want better answers.</p>
|
python|function|exit
| 0 |
1,902,084 | 51,964,209 |
Correct way of handling Tornado read_bytes method
|
<p>I am working on the python app with a tornado, In which I want to listen data sent by the client continuously.
Here is my code:</p>
<pre><code>async def handle_stream(self, stream, address):
try:
while True:
data = stream.read_bytes(1024, callback = self._on_read, partial = True)
print(data)
stream.write(data)
except StreamClosedError:
logger.error("%s disconnected", address)
</code></pre>
<p>But I am facing following problems:</p>
<ul>
<li>when I send data for the first time it invokes _on_read function but for the 2nd time, it does not process that data.</li>
<li><code>stream.write(data)</code> gives the following error,</li>
</ul>
<blockquote>
<p>tornado.application:Exception in callback functools.partial(.null_wrapper at 0x7fd3ddf2ce18>,
exception=AssertionError('Already reading',)>)
Traceback (most recent call last):
File "/venv/lib/python3.6/site-packages/tornado/ioloop.py", line 758, in
_run_callback
ret = callback()
File "/venv/lib/python3.6/site-packages/tornado/stack_context.py", line
300, in null_wrapper
return fn(*args, **kwargs)
File "/server.py", line 143, in
lambda f: f.result())
File "/server.py", line 90, in handle_stream
data = stream.read_bytes(1024, callback = self._on_read, partial = True)
File "/venv/lib/python3.6/site-packages/tornado/iostream.py", line 432, in
read_bytes
future = self._set_read_callback(callback)
File "/venv/lib/python3.6/site-packages/tornado/iostream.py", line 859, in
_set_read_callback
assert self._read_callback is None, "Already reading"
AssertionError: Already reading</p>
</blockquote>
|
<p>You try to get the data through two incompatible methods, through both the callback and the future. The error is not in stream.write, but when you call stream.read_bytes a second time with a callback.</p>
<p>As <a href="http://www.tornadoweb.org/en/stable/iostream.html#tornado.iostream.BaseIOStream.read_bytes" rel="nofollow noreferrer">callbacks are deprecated</a>, the best is to use the future. That is, something like this :</p>
<pre><code>async def handle_stream(self, stream, address):
try:
while True:
data = await stream.read_bytes(1024, partial = True)
print(data)
# stream.write(data)
except StreamClosedError:
logger.error("%s disconnected", address)
</code></pre>
<p>Also, the stream.write will write the data back to the same stream. Is it really what you want to do ?</p>
|
python-3.x|tornado
| 1 |
1,902,085 | 59,612,684 |
Rotate an image by 90 degrees using Eigen from OpenCV Matrix in C++
|
<p>How can I rotate an image by 90 degrees using Eigen from OpenCV Matrix and then convert the rotated image back to OpenCV Matrix in C++. The <code>rotate</code> function of OpenCV takes time and I want to do it as fast as possible. I have tried using Numpy <code>rot90</code> function in Python and it is extremely fast compared to OpenCV <code>rotate</code> function in C++. Unfortunately Numpy is not available for C++. I have read that there are other libraries like Eigen and Armadillo in C++ which can do these matrix operations quickly. That is the reason I want to rotate the image using Eigen and check the timing. </p>
<p>I tested the functions in Visual Studio 2019 on an i5 machine in Windows 10. The numpy <code>rot90</code> function in Python is roughly 10 times faster than the OpenCV <code>rotate</code> function in C++.</p>
|
<p>I guess that the function <code>warpAffine</code> is faster. At least you should compare to check.<br>
There is an example here:<br>
<a href="https://docs.opencv.org/master/dd/d52/tutorial_js_geometric_transformations.html" rel="nofollow noreferrer">https://docs.opencv.org/master/dd/d52/tutorial_js_geometric_transformations.html</a>. </p>
<p>The same kind of functions are available with cuda:<br>
<a href="https://docs.opencv.org/master/db/d29/group__cudawarping.html" rel="nofollow noreferrer">https://docs.opencv.org/master/db/d29/group__cudawarping.html</a></p>
<p>EDIT:<br>
<code>warpAffine</code> in OpenCV can actually use the <code>ippiWarpAffine*</code> function from the Intel Performance Primitives library. This is probably the fastest performance that could get. The cuda version is expected to be faster if you can run your software on a platform with an nvidia gpu. The performance depends on the type of data that you use. If you can use 8bit unsigned images you can be much faster.</p>
<p>EDIT 2:
After the comment saying that warpAffine is slower I ran a few tests and it can sometimes be faster. However, when compare to the numpy's rotate there is nothing comparable, even a cv2.flip or cv2.transpose are way slower. Therefore I would recommend to look into <a href="https://software.intel.com/en-us/forums/intel-integrated-performance-primitives/topic/295709" rel="nofollow noreferrer">this recommendation on Intel's developer zone</a> which is to use ippiRotate and ippiMirror functions to perform 90 rotations. If you are really interested into getting the best performance out of an Intel cpu, that would be my guess. Also take care about the multithreading, some functions can be multithreaded in IPP. In the end this depend if you look for a solution to rotate a single large image or multiple ones, of the type of data, the number of channels. With IPP at least you use the best function for your type of data.<br>
Hereafter a few trials in python to compare with numpy's <code>rot90</code> function. Of course the results can change with the parameters but still there is a large difference with numpy. It is also not obvious from my trials that cv2.rotate is so faster.</p>
<pre><code>100x np.rot90 time : 0.001626729965209961
100x cv2.rotate time : 0.21501994132995605
100x cv2.transpose time : 0.18512678146362305
100x cv2.remap time : 0.6473801136016846
100x cv2.warpAffine time : 0.11946868896484375
</code></pre>
<pre><code>import cv2
import numpy as np
import time
img = np.random.randint(0, 255, (1000, 1000, 3)).astype(np.uint8)
##################################
start = time.time()
for i in range(100):
rotated = np.rot90(img)
end = time.time()
print("100x np.rot90 time :", end - start)
##################################
start = time.time()
for i in range(100):
rotated = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)
end = time.time()
print("100x cv2.rotate time :", end - start)
##################################
start = time.time()
for i in range(100):
rotated = cv2.transpose(img, 1)
end = time.time()
print("100x cv2.transpose time :", end - start)
##################################
mapx, mapy = np.meshgrid(np.arange(0, img.shape[1]), np.arange(0, img.shape[0]))
mapx = mapx.transpose()
mapy = mapy.transpose()
start = time.time()
for i in range(100):
rotated = cv2.remap(img, mapx.astype(np.float32), mapy.astype(np.float32), cv2.INTER_NEAREST)
end = time.time()
print("100x cv2.remap time :", end - start)
##################################
rows = img.shape[0]
cols = img.shape[1]
M = cv2.getRotationMatrix2D((rows / 2, cols / 2), 90, 1)
M[0, 2] = 0
M[1, 2] = cols
start = time.time()
for i in range(100):
rotated = cv2.warpAffine(img, M, (rows, cols), flags=cv2.INTER_NEAREST)
end = time.time()
print("100x cv2.warpAffine time :", end - start)
</code></pre>
<p>I hope this helps!</p>
|
python|c++|numpy|opencv|eigen
| 1 |
1,902,086 | 19,070,145 |
Change parent in xml by Python (lxml)
|
<p>Hi I am parsing and completely modifying XML file in Python3 using lxml and I need put new Element into existing Elements and change their parent.</p>
<p>Example:
old xml </p>
<pre><code><a>
<b>something</b>
<c>something different</c>
</a>
</code></pre>
<p>new xml</p>
<pre><code><a>
<new_parent>
<b>something</b>
<c>something different</c>
</new_parent>
<a>
</code></pre>
<p>Is it possible ?</p>
|
<p>I'm not sure there is a function that do directly what you want. I would do it as follow: Create a <code>new_parent</code> node and append children of <code>a</code> to <code>new_parent</code> node, and append <code>new_parent</code> to <code>a</code>.</p>
<pre><code>import lxml.etree
xml = '''<?xml version='1.0' encoding='ASCII'?>
<root>
<a>
<b>something</b>
<c>something different</c>
</a>
</root>'''
root = lxml.etree.fromstring(xml)
a = root.find('.//a')
parent = lxml.etree.Element('new_parent')
for child in a:
parent.append(child)
a.append(parent)
print lxml.etree.tostring(root, xml_declaration=True)
</code></pre>
<p>prints (output format is modified to make it easy to read)</p>
<pre><code><?xml version='1.0' encoding='ASCII'?>
<root>
<a>
<new_parent>
<b>something</b>
<c>something different</c>
</new_parent>
</a>
</root>
</code></pre>
<p><strong>UPDATE</strong> You can use <code>extend</code> instead of multiple calls of <code>append</code>.</p>
<pre><code>root = lxml.etree.fromstring(xml)
a = root.find('.//a')
parent = lxml.etree.Element('new_parent')
parent.extend(a)
a.append(parent)
</code></pre>
|
python|xml|parsing|lxml
| 3 |
1,902,087 | 19,264,053 |
make django look for data in my custom model
|
<p>i am new to django and concept i am trying is very simple.
I created the custom model(i dont want to extend any pre-defined model).
And using this code i tried to authenticate my login :</p>
<p>Models.py : (i have given just sample data here. This is not the real data i use. And my client dosent want me to use any builtin models like AbstractBaseUser etc.,)</p>
<pre><code>from django.db import models
#from django.contrib.auth.models import User
class logindata(models.Model):
fname= models.CharField(max_length=30)
lname = models.CharField(max_length=30)
uname = models.CharField(max_length=30)
password = models.CharField(max_length = 30)
</code></pre>
<hr>
<p>Views.py</p>
<pre><code>def auth_view(request):
username = request.POST.get('username','')
password = request.POST.get('password','')
user =auth.authenticate(uname=username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/accounts/loggedin',{'user':user})
else:
return HttpResponseRedirect('/accounts/invalid')
def loggedin(request):
return render_to_response('loggedin.html',
{'name':request.user.uname})
</code></pre>
<p>My question is very simple. i want authenticate to look at my custom model(logindata) instead of the default one.
how do i do that ??</p>
|
<p>If you want to create a custom user model, Django provides an <code>django.contrib.auth.models.AbstractBaseUser</code> model that you can extend and use. Django documentation has a whole section dedicated to that, <a href="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-a-custom-user-model" rel="nofollow">take a look</a>.</p>
<p>If you’re entirely happy with Django’s User model and you just want to add some additional profile information, you can simply subclass <code>django.contrib.auth.models.AbstractUser</code> and add your custom profile fields. This class provides the full implementation of the default <code>User</code> as an abstract model.</p>
<p>You can go through the <a href="https://github.com/django/django/blob/master/django/contrib/auth/models.py#L192" rel="nofollow">code at github</a> to see what to extend.</p>
|
python|django|django-models|django-views|custom-model-binder
| 1 |
1,902,088 | 18,959,658 |
Simple Palindrome check in Python?
|
<p>I am doing a palindrome check program for school, but there is a twist.</p>
<p>Now I already know that I could use a reverse function or something like:</p>
<pre><code>[-1::-1]
</code></pre>
<p>However, the program specifically calls for no string slicing or use of the .reverse() function. So, my question is how would I go about doing this if I cannot use these two simple methods?</p>
|
<p>It's clear that this is for academic purposes only because using reversed function this code would be trivial.</p>
<pre><code>def is_palindrome(string):
for i,char in enumerate(string):
if char != string[-i-1]:
return False
return True
>>> is_palindrome('hello')
False
>>> is_palindrome('helloolleh')
True
>>> is_palindrome('')
True
>>> is_palindrome(' ')
True
>>> is_palindrome('a')
True
</code></pre>
|
python|string|reverse|slice|palindrome
| 5 |
1,902,089 | 62,399,967 |
How to fix this simple code involving main?
|
<pre><code>def execute():
url_test = "21{}"
for i in{count}:
url = url_test.format(i)
def main():
count = 20000001
while True:
count += 1
print(count)
if execute():
break
main()
</code></pre>
<pre><code>Traceback (most recent call last):
File "C:/Users/Guest/AppData/Local/Programs/Python/Python38-32/1.py", line 15, in <module>
main()
File "C:/Users/Guest/AppData/Local/Programs/Python/Python38-32/1.py", line 12, in main
if execute():
File "C:/Users/Guest/AppData/Local/Programs/Python/Python38-32/1.py", line 3, in execute
for i in{count}:
NameError: name 'count' is not defined
</code></pre>
<p>How do i define count without messing the execute?</p>
|
<p>Good programming practice indicates that you should minimise coupling between different components<sup>(1)</sup> as much as possible. In this case, that means using parameters to pass information, such as with:</p>
<pre><code>def execute(count):
url_test = "21{}"
for i in{count}:
url = url_test.format(i)
return False
def main():
count = 20000001
while True:
count += 1
print(count)
if execute(count):
break
main()
</code></pre>
<hr>
<p>As an aside, I'm not sure I fully understand what this segment of your code is <em>meant</em> to be doing:</p>
<pre><code>for i in {count}:
url = url_test.format(i)
</code></pre>
<p>Since <code>{count}</code> is a one-element set containing <code>count</code>, it's no different to just doing (without the <code>for</code> loop):</p>
<pre><code>url = url_test.format(count)
</code></pre>
<p>You may want to rethink either how you're doing this, or what you're <em>trying</em> to do.</p>
<hr>
<p><sup>(1)</sup> What I mean by that is that there should be limited information flow. The general practice is "maximum coherence, minimum coupling", meaning that things that belong together should <em>be</em> together, while things that don't should be well isolated from each other.</p>
<p>For calling functions, it should be parameters passed in and values returned, <em>not</em> attempting global variable access or access to variables created in another function. You can <em>do</em> that, by putting <code>global count</code> at the top of <code>man()</code>, making it global, but it's actually not a good idea since it allows any function access to it, breaking encapsulation.</p>
|
python
| 4 |
1,902,090 | 56,293,905 |
how to incorporate try and except into a block of code in python
|
<p>I am working on a collatz sequence code in python. The code should give me a sequence of numbers that end in 1. The code I have here does that when I enter a number.</p>
<pre><code> try:
number = int(input('Pick a number'))
except ValueError:
print('Error! input a number')
def collatz(number):
if number % 2 == 0:
x = number // 2
return x
else:
x = 3 * number + 1
return x
while number != 1:
number = collatz(number)
print(number)
</code></pre>
<p>However, when I try to invoke the try and except function by entering a letter,I get the desired error message but I also get a NameError.</p>
<pre><code>Traceback (most recent call last):
File "/home/PycharmProjects/collatz/collatz.py", line 14, in <module>
while number != 1:
NameError: name 'number' is not defined
Error! input a number *Desired Error Message*
</code></pre>
<p>I dont get this error when I remove the try and except function. I have tried defining 'name' as a global variable and also played around with the indentation but nothing seems to work. I would greatly appreciate any kind of help. </p>
<p>I am using python 3.6. </p>
|
<p>The reason you get the NameError is because <code>number</code> is simply not defined. The call to <code>int</code> fails, thus the assignment to <code>number</code> never happens, you catch and print the error but then just proceed. To force the user to enter a valid number you have to repeat the prompt until the user enters the correct input.</p>
<pre><code>def read_number():
while True:
try:
return int(input('Pick a number'))
except ValueError:
print('Error! Input a number')
</code></pre>
<p>Then, to read a sequence of numbers you do:</p>
<pre><code>while True:
number = read_number()
if number == 1:
break
</code></pre>
|
python
| 0 |
1,902,091 | 67,310,343 |
Using for loops in python interpreter
|
<p>I'm trying to start a for loop after doing something else in python interpreter on the same line, and it throws a SyntaxError when I do so.</p>
<pre><code>>>> a,b = 0, 1;\
... for i in range(1, 10):
File "<stdin>", line 2
for i in range(1, 10):
^
SyntaxError: invalid syntax
</code></pre>
<p>Of course I could just execute them separately here, but if I want to have this inside a function definition then I can't exactly do that. What is the correct syntax to do it in the interpreter?</p>
|
<p>When you have a backslash, you are telling it to ignore the new line. So Python thought your code was <code>a,b = 0, 1 for i in range(1,10):</code>. This is clearly invalid syntax. So, you must remove the semicolon and the backslash. When you want to go to the new line, use <code>shift + enter key</code>.</p>
<p>After that, it should work:</p>
<p><a href="https://i.stack.imgur.com/EjH2n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EjH2n.png" alt="enter image description here" /></a></p>
|
python|syntax|syntax-error|pythoninterpreter
| 0 |
1,902,092 | 36,311,599 |
Installing python packages in a central location
|
<p>Hi my question is about the installation of python packages in a central location. I have many computers on my network and would ideally want to install python packages in only one location and have the packages available to all the computers . Is there a clean way to do this ? </p>
|
<p>I think it depends on the type of the packages. </p>
<p>Plain Python packages could be potentially installed to a network drive and reused on any device that has that location mounted. It would be then just the matter of adding this location to the <code>PYTHONPATH</code> (which can be done through environment variables or some local settings file in your application).</p>
<p>However cpython packages that need to be linked against other libraries (e.g. database drivers) would possibly not work as they are compiled against a specific library version and any difference across your computers would possibly cause them to break.</p>
|
python|pip
| 1 |
1,902,093 | 19,648,008 |
Write result of Python Script to txt file
|
<p>I have the following script in Python that is meant to find words with two or more vowels in them and output the result to a txt file. The script currently runs, but the output file is empty. I have tried several different methods to no avail, any idea why the output file is blank? I am using the (re) import to treat the input as a regular expression.</p>
<pre><code>#!C:\Python33\python.exe
import re
file = open("Text of Steve Jobs' Commencement address (2005).htm");
output = open('twoVoweledWordList.txt', 'w');
for word in file.read():
if len(re.findall('[aeiouy]', word)) >= 2:
match == True;
while True :
output.write(word, '\n');
file.close()
output.close()
</code></pre>
|
<p>You asked for a better way to read a word at a time. Here you go:</p>
<pre><code>with open(input_file_name, "rt") as f:
for line in f:
for word in line.split():
# do something with each word here
</code></pre>
<p>Comments:</p>
<ul>
<li>In general I try to avoid using built-in Python features as variable names. Since <code>file</code> is a built-in in Python 2.x, syntax-coloring text editors will flag it in a different color... might as well just use <code>f</code> for the variable name.</li>
<li>It's best to use the <code>with</code> statement. It is very clear, and in all versions of Python it makes sure your file is properly closed when you are done. (Here it won't matter, but it's really a best practice.)</li>
<li><code>open()</code> returns an object that you can use in a <code>for</code> loop. You will get one line of input from the file at a time.</li>
<li><code>line.split()</code> splits the line into words, using any "white space" (spaces, tabs, etc.)</li>
</ul>
<p>I don't know if you have seen generator functions yet, but you can wrap up the above doubly-nested <code>for</code> loops into a generator function like this:</p>
<pre><code>def words(f):
for line in f:
for word in line.split():
yield word
with open(input_file_name, "rt") as f:
for word in words(f):
# do something with word
</code></pre>
<p>I like hiding the machinery like this. And if you ever needed to make the word-splitting more complicated, the complex part is nicely separated from the part that actually handles the words.</p>
|
python|regex
| 5 |
1,902,094 | 22,103,630 |
sublimetext view run_command appears to have no effect
|
<p>In the following code if a text edit needs to be made it is, successfully. If it doesnt need to be made I see the 'try and close' in the console. But the view doesn't close.
I've tried both close and close_file.</p>
<pre><code>if not text == orig:
view.run_command('select_all')
view.run_command('cut')
view.run_command('insert_text', {'string': text})
else:
#no change, close if it wasnt already open
if not open_stat:
print('try and close')
view.run_command('close')
</code></pre>
|
<p>I believe close is a window command, so try <code>view.window().run_command("close")</code>. I'd also run <code>window#focus_view</code> just to make sure it is in focus. Wouldn't want to be closing the wrong view on accident (though I suppose even with that it's possible).</p>
|
python|sublimetext3
| 1 |
1,902,095 | 22,126,657 |
Heroku pg:psql command throwing psql: FATAL: database "'" does not exist
|
<p>heroku pg:psql command throws error when trying to connect to the db.</p>
<pre><code>(venv) PS C:\Users\Mevin\Desktop\poster> heroku pg:psql
---> Connecting to HEROKU_POSTGRESQL_ROSE_URL (DATABASE_URL)
psql: warning: extra command-line argument "--set" ignored
psql: warning: extra command-line argument "PROMPT2='posterback::ROSE%R%#" ignored
psql: warning: extra command-line argument "'" ignored
psql: warning: extra command-line argument "dbg2gm01rci0jp" ignored
psql: FATAL: database "'" does not exist
</code></pre>
<p>Here's my output for <code>heroku pg:info</code></p>
<pre><code>(venv) PS C:\Users\Mevin\Desktop\poster> heroku pg:info
=== HEROKU_POSTGRESQL_ROSE_URL (DATABASE_URL)
Plan: Hobby-dev
Status: available
Connections: 0
PG Version: 9.3.3
Created: 2014-03-02 07:22 UTC
Data Size: 7.0 MB
Tables: 9
Rows: 19/10000 (In compliance)
Fork/Follow: Unsupported
Rollback: Unsupported
</code></pre>
<p>So why am I not able to access pg:psql ?</p>
|
<p>Heroku did some changes and it may not be working on some Windows versions. The solution I got was:</p>
<p>1) run the following command: </p>
<pre><code>heroku config:get your_database_url --app your_app_name
</code></pre>
<p>This command will give you the complete URL to your database on amazon (let's say url_to_db_amazon)</p>
<p>2) run the following command: </p>
<pre><code>psql --set "PROMPT1=your_app_name::database_color%R%#" --set "PROMPT2=your_app_name::database_color%R%#" url_to_db_amazon
</code></pre>
<p>or just:</p>
<pre><code>psql url_to_db_amazon
</code></pre>
<p>This worked for me.</p>
|
python|postgresql|heroku
| 1 |
1,902,096 | 54,351,047 |
Test function with lru_cache decorator
|
<p>I'm attempting to test a a method that is memoized through <code>lru_cache</code> (since it's an expensive database call). with <code>pytest-mock</code>.</p>
<p>A simplified version of the code is:</p>
<pre><code>class User:
def __init__(self, file):
# load a file
@lru_cache
def get(self, user_id):
# do expensive call
</code></pre>
<p>Then I'm testing:</p>
<pre><code>class TestUser:
def test_get_is_called(self, mocker):
data = mocker.ANY
user = User(data)
repository.get(user_id)
open_mock = mocker.patch('builtins.open', mocker.mock_open())
open_mock.assert_called_with('/foo')
</code></pre>
<p>But I'm getting the following error:</p>
<pre><code>TypeError: unhashable type: '_ANY'
</code></pre>
<p>This happens because <code>functools.lru_cache</code> needs the keys stored to be <em>hashable</em> i.e. have a method <code>__hash__</code> or <code>__cmp__</code> implemented.</p>
<p>How can I mock such methods in a mocker to make it work?</p>
<p>I've tried</p>
<pre><code>user.__hash__.return_value = 'foo'
</code></pre>
<p>with no luck.</p>
|
<p>For people arriving here trying to work out how to test functions decorated with <code>lru_cache</code> or <code>alru_cache</code>, the answer is to <a href="https://stackoverflow.com/a/37654201/2071807">clear the cache</a> before each test.</p>
<p>This can be done as follows:</p>
<pre><code>def setup_function():
"""
Avoid the `(a)lru_cache` causing tests with identical parameters to interfere
with one another.
"""
my_cached_function.cache_clear()
</code></pre>
|
python|mocking|pytest|functools
| 22 |
1,902,097 | 9,228,821 |
Dot product of a vector in SciPy/NumPy (getting ValueError: objects are not aligned)
|
<p>I just started learning SciPy and am struggling with the most basic features.</p>
<p>Consider the following standard vector:</p>
<pre><code>In [6]: W=array([[1],[2]])
In [7]: print W
[[1]
[2]]
</code></pre>
<p>If I understand it correctly, this should be the SciPy representation of a standard 2x1 mathematical vector, like this:</p>
<pre><code>(1)
(2)
</code></pre>
<p>The dot product of this vector should simply be <code>1*1+2*2=5</code>. However, this does not work in SciPy:</p>
<pre><code>In [16]: dot(W, W)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/home/ingo/<ipython-input-16-961b62a82495> in <module>()
----> 1 dot(W, W)
ValueError: objects are not aligned
</code></pre>
<p>Note that the following works. This should be a vector of the form <code>(1 2)</code> if I am not mistaken.</p>
<pre><code>In [9]: V=array([1,2])
In [10]: print V
[1 2]
In [11]: dot(V, V)
Out[11]: 5
</code></pre>
<p>What is my misconception? What am I doing wrong?</p>
|
<p>The key here is that numpy/scipy honours the shape of arrays when computing dot products. Looking at your first example, <code>W</code> is a 2x1 array:</p>
<pre><code>In [7]: W=array([[1],[2]])
In [8]: print W.shape
------> print(W.shape)
(2, 1)
</code></pre>
<p>it is, therefore, necessary to use the transpose operator to compute the dot (inner) product of W with itself:</p>
<pre><code>In [9]: print dot(W.T,W)
------> print(dot(W.T,W))
[[5]]
In [10]: print np.asscalar(dot(W.T,W))
-------> print(np.asscalar(dot(W.T,W)))
5
</code></pre>
|
python|numpy|scipy
| 16 |
1,902,098 | 47,935,846 |
List supported OpenCV video capture properties in Python
|
<p>I am trying to write a function that automatically determines which set of video capture properties are supported by a particular webcam. This is simple to do with <code>v4l2-ctl</code>, but I don't know how to do it cleanly using OpenCV's built-in functions. Using <code>v4l2-ctl</code>, I would invoke:</p>
<pre><code>$ v4l2-ctl --device <webcam> --list-ctrls
</code></pre>
<p>which yields a different set of camera controls for my laptop's integrated webcam (<code>/dev/video0</code>) and for whatever USB webcam that I plug in. So far in Python OpenCV, the best I've been able to do is:</p>
<pre><code>def list_supported_capture_properties(cap: cv2.VideoCapture):
""" List the properties supported by the capture device.
"""
supported = list()
for attr in dir(cv2):
if attr.startswith('CAP_PROP'):
if cap.get(getattr(cv2, attr)) != -1:
supported.append(attr)
return supported
</code></pre>
<p>When this function is called, OpenCV prints out a lot of error messages like these:</p>
<pre><code>VIDEOIO ERROR: V4L2: Autofocus is not supported by your device
VIDEOIO ERROR: V4L2: getting property #32 is not supported
</code></pre>
<p>If I wrap <code>cap.get</code> in a Python try statement, the videoio errors above are not caught, so it's as if I had no try-except at all. Specializing the except clause to <code>cv2.error</code> as suggested in <a href="https://stackoverflow.com/a/8874487/2738025">this answer</a> doesn't work for me. I could reroute output to dev/null as suggested in <a href="https://stackoverflow.com/a/45669280/2738025">this answer</a>, but this seems more like a band-aid than a cure to me.</p>
<p>So, here are my two questions:</p>
<ol>
<li><p>Is it possible to catch the OpenCV videoio error in Python? How do I do that?</p></li>
<li><p>Is there a better way to get only the list of <em>supported</em> capture properties? Would it be better run <code>v4l2-ctl</code> as a subprocess, then process the text in the output to determine the capture properties?</p></li>
</ol>
|
<p>It's a bit late for the answer, but maybe there are others with the same problem.</p>
<p>That you get different properties is a bug of opencv, which is there since many years. The problem is, that there are two different libraries for v4l2-devices ( v4l2 and libv4l2) . Compiling opencv with libv4l2 leads to these errors.</p>
<p>Question 1: the errors you have seen are not produced by python, but by the underlying opencv c++ code . It seems that hey are directly written to stdout.</p>
<p>Question 2: when you have opencv compiled without libv4l2, then your code should give the exact same list as v4l2-ctl. When working with the corrupted opencv-version
You can not get neither set any of the CAP_PROP parameters.</p>
|
python|opencv
| 0 |
1,902,099 | 47,899,453 |
Python Subprocess wait for a list of subprocess
|
<p>I am using python3 subprocess module to cope with bash script call. I want to control the number of concurrent subprocess when calling the script. </p>
<blockquote>
<p>Popen.wait(timeout=None)
Wait for child process to terminate. Set and return returncode attribute.</p>
</blockquote>
<p>I know that I can call the subprocess.Popen.wait(timeout=None) to wait for child process to terminate. But I was wondering about if I can wait for a list of subprocess.Popen to finish, with that, I can control the number of concurrent processes.</p>
<p>Sample code snippets as following:</p>
<p>Example.py</p>
<pre><code>import subprocess
from itertools import zip_longest
seed = [1, 2, 4, 1, 3, 5, 4, 1]
basepath="/path/to/file/hello.sh"
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
def bash_handler(num):
return subprocess.Popen('bash {0} {1}'.format(basepath, num), shell=True)
for bulk in grouper(seed, 2):
[bash_handler(item).wait() for item in bulk if item is not None]
# This will executed one by one
</code></pre>
<p>hello.sh</p>
<pre><code># Validation goes here.
echo $1
sleep $1
echo "Finish Executed"
</code></pre>
|
<p>when you use communicate(), you don't need to specify the wait for the subprocess to exit. more information can be found here <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow noreferrer">https://docs.python.org/2/library/subprocess.html</a>
other link
<a href="https://stackoverflow.com/questions/16768290/understanding-popen-communicate">Understanding Popen.communicate</a></p>
<p>below changes should work for you</p>
<pre><code>from subprocess import Popen,PIPE
def bash_handler(num):
return subprocess.Popen('bash {0} {1}'.format(basepath, num), shell=True,stdout=PIPE)
for bulk in grouper(seed, 2):
[bash_handler(item).communicate() for item in bulk if item is not None]
</code></pre>
|
python|bash|concurrency|subprocess
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.