title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
Using variable inside setUpClass (class method) - unittest python
39,988,152
<p>I would like to use a variable which I initialize in the subclass to be used in the setUpClass of parent class , here is the code snippet below:</p> <pre><code>class BaseTest(unittest.TestCase): def __init__(cls, arg): unittest.TestCase.__init__(cls, arg) @classmethod def setUpClass(cls): print "Base.setUp()" ,cls.param @classmethod def tearDownClass(cls): print "Base.tearDown()" class TestSomething(BaseTest): def __init__(cls, arg): BaseTest.__init__(cls, arg) cls.param = 'hello' def test_silly(self): print "Test method" self.assertTrue(1+1 == 2) def test_silly1(self): print "Test method" self.assertTrue(1+1 == 2) </code></pre> <p>It gives me this : <code>AttributeError: type object 'TestSomething' has no attribute 'param'</code> , which I understand is true as <code>setUpClass and tearDownClass</code> are class and not instance method, any way to use variable instantiated in the base class to be used in <code>setUpClass of parent class</code>?</p>
0
2016-10-11T23:10:45Z
39,988,745
<p>You need to set <code>cls.param</code> <em>before</em> you call <code>BaseTest.__init__(cls, arg)</code>.</p>
0
2016-10-12T00:27:16Z
[ "python", "python-2.7", "unit-testing", "testing", "python-unittest" ]
How to close an HDF5 using low level Python API?
39,988,211
<p>I was able to modify the cache settings of an HDF5 file by combining both the high and low level Python h5py API as defined in the following Stack Overflow question: <a href="http://stackoverflow.com/questions/14653259/how-to-set-cache-settings-while-using-h5py-high-level-interface/14656421?noredirect=1#comment67138276_14656421">How to set cache settings while using h5py high level interface?</a></p> <p>I am getting an error saying that the h5 file is still open when I try to rename the file. The Python "with" statement with the contextlib does not seem to be closing the file after the HDF5 writing operation is completed and the file is flushed. How can I make sure that the file is closed using either the low-level or high-level API? Could you please provide an example ? </p> <pre><code>import h5py import contextlib import os filename = 'foo_2.h5' propfaid = h5py.h5p.create(h5py.h5p.FILE_ACCESS) settings = list(propfaid.get_cache()) settings[2] *= 5 propfaid.set_cache(*settings) with h5py.File(filename, 'w') as hf: print 'file created' with contextlib.closing(h5py.h5f.open(filename, fapl=propfaid)) as fid: f = h5py.File(fid) f.flush() # f.close() Seems to be working only in Python 3.4.3 but not in 2.7.7 #and the "with contextlib.closing(...) does not work on either version f.close() os.rename(filename, 'foo_2.h5') </code></pre> <p><strong>Additional information:</strong> <br/> <strong>OS: Windows <br/> Python: 2.7.7 <br/> Anaconda Distribution: 2.0.1 <br/> H5py version: 2.3.0</strong></p>
1
2016-10-11T23:16:47Z
39,989,519
<p>I think you are looking for .close()</p> <pre><code>f.close() </code></pre> <p>Although looking closer, I'm not sure why contextlib.closing(...) didn't work.</p> <p>I edited the line involving contextlib to be:</p> <pre><code>with contextlib.closing(h5py.File(filename, fapl=propfaid)) as fid: </code></pre> <p>and removed</p> <pre><code>f = h5py.File(fid) </code></pre> <p>Afterwards, I could check that fid was closed and renaming file worked as expected.</p> <pre><code>print fid &lt;Closed HDF5 file&gt; os.rename(filename, 'foo2.hdf5') </code></pre> <p>No errors and check of directory shows the new name</p>
0
2016-10-12T02:20:12Z
[ "python", "anaconda", "hdf5", "h5py" ]
Searching through a file in Python
39,988,223
<p>Say that I have a file of restaurant names and that I need to search through said file and find a particular string like "Italian". How would the code look if I searched the file for the string and print out the number of restaurants with the same string?</p> <pre><code>f = open("/home/ubuntu/ipynb/NYU_Notes/2-Introduction_to_Python/data/restaurant-names.txt", "r") content = f.read() f.close() lines = content.split("\n") with open("/home/ubuntu/ipynb/NYU_Notes/2-Introduction_to_Python/data/restaurant-names.txt") as f: print ("There are", len(f.readlines()), "restaurants in the dataset") with open("/home/ubuntu/ipynb/NYU_Notes/2-Introduction_to_Python/data/restaurant-names.txt") as f: searchlines = f.readlines() for i, line in enumerate(searchlines): if "GREEK" in line: for l in searchlines[i:i+3]: print (l), print </code></pre>
0
2016-10-11T23:18:33Z
39,988,280
<p>You input the file as a string.<br/> Then use the count method of strings.<br/> Code:</p> <pre><code>#Let the file be taken as a string in s1 print s1.count("italian") </code></pre>
-1
2016-10-11T23:26:15Z
[ "python", "file" ]
Searching through a file in Python
39,988,223
<p>Say that I have a file of restaurant names and that I need to search through said file and find a particular string like "Italian". How would the code look if I searched the file for the string and print out the number of restaurants with the same string?</p> <pre><code>f = open("/home/ubuntu/ipynb/NYU_Notes/2-Introduction_to_Python/data/restaurant-names.txt", "r") content = f.read() f.close() lines = content.split("\n") with open("/home/ubuntu/ipynb/NYU_Notes/2-Introduction_to_Python/data/restaurant-names.txt") as f: print ("There are", len(f.readlines()), "restaurants in the dataset") with open("/home/ubuntu/ipynb/NYU_Notes/2-Introduction_to_Python/data/restaurant-names.txt") as f: searchlines = f.readlines() for i, line in enumerate(searchlines): if "GREEK" in line: for l in searchlines[i:i+3]: print (l), print </code></pre>
0
2016-10-11T23:18:33Z
39,988,411
<p>You could count all the words using a Counter dict and then do lookups for certain words:</p> <pre><code>from collections import Counter from string import punctuation f_name = "/home/ubuntu/ipynb/NYU_Notes/2-Introduction_to_Python/data/restaurant-names.txt" with open(f_name) as f: # sum(1 for _ in f) -&gt; counts lines print ("There are", sum(1 for _ in f), "restaurants in the dataset") # reset file pointer back to the start f.seek(0) # get count of how many times each word appears, at most once per line cn = Counter(word.strip(punctuation).lower() for line in f for word in set(line.split())) print(cn["italian"]) # no keyError if missing, will be 0 </code></pre> <p>we use <code>set(line.split())</code> so if a word appeared twice for a certain restaurant, we would only count it once. That looks for exact matches, if you are also looking to match partials like <code>foo</code> in <code>foobar</code> then it is going to be more complex to create a dataset where you can efficiently lookup multiple words.</p> <p>If you really just want to count one word all you need to do is use <em>sum</em> how many times the substring appears in a line:</p> <pre><code>f_name = "/home/ubuntu/ipynb/NYU_Notes/2-Introduction_to_Python/data/restaurant-names.txt" with open(f_name) as f: print ("There are", sum(1 for _ in f), "restaurants in the dataset") f.seek(0) sub = "italian" count = sum(sub in line.lower() for line in f) </code></pre> <p>If you want exact matches, you would need the split logic again or to use a regex with word boundaries.</p>
2
2016-10-11T23:41:44Z
[ "python", "file" ]
python figure which properties belong to the child class
39,988,258
<p>I have a python class hierarchy as follows:</p> <pre><code>class A: def __init__(self): self.a = 1 self.b = 2 class B(A): def __init__(self): super(B, self).__init__() self.c = 3 </code></pre> <p>Now when I do something like:</p> <pre><code>obj = B() obj.__dict__ </code></pre> <p>I get:</p> <pre><code>{'a': 1, 'b': 2, 'c': 3} </code></pre> <p>is it possible to identify which of these properties belong to the parent class or rather which of these properties are of the child only?</p>
2
2016-10-11T23:22:39Z
39,988,555
<p>For your simple example, you could get the difference in the dict items:</p> <pre><code>print(obj.__dict__.items() - A().__dict__.items()) </code></pre> <p>I suppose we should at least to it without knowing the name of the parent class:</p> <pre><code> print(obj.__dict__.items() - obj.__class__.__bases__[0]().__dict__.items()) </code></pre>
2
2016-10-12T00:01:15Z
[ "python", "class", "python-3.x" ]
(Python) Can I store the functions themselves, but not their value, in a list
39,988,379
<p>As you can see from the code below, I'm adding a series of functions to a list. The result is that each function gets ran and the returned value is added to the list. </p> <pre><code>foo_list = [] foo_list.append(bar.func1(100)) foo_list.append(bar.func2([7,7,7,9])) foo_list.append(bar.func3(r'C:\Users\user\desktop\output')) </code></pre> <p>What I would like to know is, is it possible to have the function stored in the list and then ran when it is iterated upon in a for loop?</p> <p><a href="https://i.stack.imgur.com/MS9ml.png" rel="nofollow"><img src="https://i.stack.imgur.com/MS9ml.png" alt="enter image description here"></a></p>
4
2016-10-11T23:38:26Z
39,988,445
<p>Yeah just use lambda:</p> <pre><code>foo_list = [] foo_list.append(lambda: bar.func1(100)) foo_list.append(lambda: bar.func2([7,7,7,9])) foo_list.append(lambda: bar.func3(r'C:\Users\user\desktop\output')) for foo in foo_list: print(foo()) </code></pre>
4
2016-10-11T23:45:20Z
[ "python", "list" ]
How to call pypdfocr functions to use them in a python script?
39,988,381
<p>Recently I downloaded <a href="https://github.com/virantha/pypdfocr" rel="nofollow">pypdfocr</a>, however, in the documentation there are no examples of how to call pypdfocr as a library, could anybody help me to call it just to convert a single file?. I just found a terminal command:</p> <pre><code>$ pypdfocr filename.pdf </code></pre>
0
2016-10-11T23:38:28Z
39,989,237
<p>If you're looking for the source code, it's normally under the directory site-package of your python installation. What's more, if you're using a IDE (i.e. Pycharm), it would help you find the directory and file. This is extremly useful to find class as well and show you how you can instantiate it, for example : <a href="https://github.com/virantha/pypdfocr/blob/master/pypdfocr/pypdfocr.py" rel="nofollow">https://github.com/virantha/pypdfocr/blob/master/pypdfocr/pypdfocr.py</a> this file has a pypdfocr class type you can re-use and, possibly, do what a command-line would do. </p> <p>In that class, the developper has put a lot of argument to be parsed : </p> <pre><code>def get_options(self, argv): """ Parse the command-line options and set the following object properties: :param argv: usually just sys.argv[1:] :returns: Nothing :ivar debug: Enable logging debug statements :ivar verbose: Enable verbose logging :ivar enable_filing: Whether to enable post-OCR filing of PDFs :ivar pdf_filename: Filename for single conversion mode :ivar watch_dir: Directory to watch for files to convert :ivar config: Dict of the config file :ivar watch: Whether folder watching mode is turned on :ivar enable_evernote: Enable filing to evernote """ p = argparse.ArgumentParser(description = "Convert scanned PDFs into their OCR equivalent. Depends on GhostScript and Tesseract-OCR being installed.", epilog = "PyPDFOCR version %s (Copyright 2013 Virantha Ekanayake)" % __version__, ) p.add_argument('-d', '--debug', action='store_true', default=False, dest='debug', help='Turn on debugging') p.add_argument('-v', '--verbose', action='store_true', default=False, dest='verbose', help='Turn on verbose mode') p.add_argument('-m', '--mail', action='store_true', default=False, dest='mail', help='Send email after conversion') p.add_argument('-l', '--lang', default='eng', dest='lang', help='Language(default eng)') p.add_argument('--preprocess', action='store_true', default=False, dest='preprocess', help='Enable preprocessing. Not really useful now with improved Tesseract 3.04+') p.add_argument('--skip-preprocess', action='store_true', default=False, dest='skip_preprocess', help='DEPRECATED: always skips now.') #--------- # Single or watch mode #-------- single_or_watch_group = p.add_mutually_exclusive_group(required=True) # Positional argument for single file conversion single_or_watch_group.add_argument("pdf_filename", nargs="?", help="Scanned pdf file to OCR") # Watch directory for watch mode single_or_watch_group.add_argument('-w', '--watch', dest='watch_dir', help='Watch given directory and run ocr automatically until terminated') #----------- # Filing options #---------- filing_group = p.add_argument_group(title="Filing optinos") filing_group.add_argument('-f', '--file', action='store_true', default=False, dest='enable_filing', help='Enable filing of converted PDFs') #filing_group.add_argument('-c', '--config', type = argparse.FileType('r'), filing_group.add_argument('-c', '--config', type = lambda x: open_file_with_timeout(p,x), dest='configfile', help='Configuration file for defaults and PDF filing') filing_group.add_argument('-e', '--evernote', action='store_true', default=False, dest='enable_evernote', help='Enable filing to Evernote') filing_group.add_argument('-n', action='store_true', default=False, dest='match_using_filename', help='Use filename to match if contents did not match anything, before filing to default folder') # Add flow option to single mode extract_images,preprocess,ocr,write args = p.parse_args(argv) </code></pre> <p>You can use any of those argument to be passed to it's parser, like this :</p> <pre><code>import pypdfocr obj = pypdfocr.pypdfocr.pypdfocr() obj.get_options([]) # this makes it takes default, but you could add CLI option to it. Other option might be [-v] or [-d,-v] </code></pre> <p>I hope this help you understand in the mean time :)</p>
1
2016-10-12T01:38:41Z
[ "python", "python-2.7", "python-3.x", "pdfbox" ]
Gevent: Using two queues with two consumers without blocking each other at the same time
39,988,398
<p>I have the problem that I need to write values generated by a consumer to disk. I do not want to open a new instance of a file to write every time, so I thought to use a second queue and a other consumer to write to disk from a singe Greenlet. The problem with my code is that the second queue does not get consumed async from the first queue. The first queue finishes first and then the second queue gets consumed. I want to write values to disk at the same time then other values get generated. Thanks for help!</p> <pre><code>#!/usr/bin/python #- * -coding: utf-8 - * - import gevent #pip install gevent from gevent.queue import * import gevent.monkey from timeit import default_timer as timer from time import sleep import cPickle as pickle def save_lineCount(count): with open("count.p", "wb") as f: pickle.dump(count, f) def loader(): for i in range(0,3): q.put(i) def writer(): while True: task = q_w.get() print "writing",task save_lineCount(task) def worker(): while not q.empty(): task = q.get() if task%2: q_w.put(task) print "put",task sleep(10) def asynchronous(): threads = [] threads.append(gevent.spawn(writer)) for i in range(0, 1): threads.append(gevent.spawn(worker)) start = timer() gevent.joinall(threads,raise_error=True) end = timer() #pbar.close() print "\n\nTime passed: " + str(end - start)[:6] q = gevent.queue.Queue() q_w = gevent.queue.Queue() gevent.spawn(loader).join() asynchronous() </code></pre>
0
2016-10-11T23:40:22Z
40,020,322
<p>In general, that approach should work fine. There are some problems with this specific code, though:</p> <ul> <li><p>Calling <code>time.sleep</code> will cause all greenlets to block. You either need to call <code>gevent.sleep</code> or monkey-patch the process in order to have just one greenlet block (I see <code>gevent.monkey</code> imported, but <code>patch_all</code> is not called). I suspect that's the major problem here.</p></li> <li><p>Writing to a file is also synchronous and causes all greenlets to block. You can use <code>FileObjectThread</code> if that's a major bottleneck.</p></li> </ul>
0
2016-10-13T11:56:01Z
[ "python", "multithreading", "queue", "gevent", "greenlets" ]
Can't figure out what's wrong in Pygame app
39,988,416
<p>I'm writing this time reaction test. It is supposed to display the text, wait for a key stroke and start the trials, appending the resulting measure to the file. But it just displays the text and freezes. Damn. I would be very grateful if you could help me point out the issue</p> <pre><code>import pygame import random import time pygame.init() red = (255, 0, 0) light_sea_green = (32, 178, 172) white = (255, 255, 255) black = (0, 0, 0) height, width = pygame.display.Info().current_w,pygame.display.Info().current_h try: screen = pygame.display.set_mode((height, width), pygame.FULLSCREEN) except pygame.error: screen = pygame.display.set_mode((780, 1360), pygame.FULLSCREEN) print("display err") screen.fill(white) pygame.display.flip() pygame.display.set_caption("TRTest") data = open("data.txt", "r+") sid = len([l for l in data.readlines()]) + 1 while True: start = False fnt = pygame.font.Font(None, 28) txtrn = fnt.render("TR, press return", 0, (0, 0, 0)) screen.blit(txtrn, (((height/2) - (txtrn.get_rect().width/2)), ((width/2) - (txtrn.get_rect().height)/2))) pygame.display.flip() while not start: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.KEYDOWN: start == True while start == True: for x in range(3): #3 Trials screen.fill((255, 255, 255)) pygame.draw.line(screen, (0, 0, 0), (height/2, width/2 - 10), (height/2, width/2 + 10), 2) pygame.draw.line(screen, (0, 0, 0), (height/2 - 10, width/2), (height/2 + 10, width/2), 2) pygame.display.flip() pygame.time.delay(random.randint(2000, 8000)) pygame.draw.circle(screen, red, (height/2, width/2), 80) pygame.display.flip() t0 = time.clock() pygame.event.clear() running = True while running: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: t1 = time.clock() tr = (t1 - t0) data.append(round(tr, 3)) running = False elif event.type == pygame.QUIT: pygame.quit() </code></pre>
0
2016-10-11T23:42:12Z
39,988,512
<p>You need <code>=</code> instead of <code>==</code> in code</p> <pre><code>if event.type == pygame.KEYDOWN: start == True # &lt;--- need `=` instead of `==` </code></pre>
1
2016-10-11T23:54:30Z
[ "python", "pygame", "tr" ]
Can't figure out what's wrong in Pygame app
39,988,416
<p>I'm writing this time reaction test. It is supposed to display the text, wait for a key stroke and start the trials, appending the resulting measure to the file. But it just displays the text and freezes. Damn. I would be very grateful if you could help me point out the issue</p> <pre><code>import pygame import random import time pygame.init() red = (255, 0, 0) light_sea_green = (32, 178, 172) white = (255, 255, 255) black = (0, 0, 0) height, width = pygame.display.Info().current_w,pygame.display.Info().current_h try: screen = pygame.display.set_mode((height, width), pygame.FULLSCREEN) except pygame.error: screen = pygame.display.set_mode((780, 1360), pygame.FULLSCREEN) print("display err") screen.fill(white) pygame.display.flip() pygame.display.set_caption("TRTest") data = open("data.txt", "r+") sid = len([l for l in data.readlines()]) + 1 while True: start = False fnt = pygame.font.Font(None, 28) txtrn = fnt.render("TR, press return", 0, (0, 0, 0)) screen.blit(txtrn, (((height/2) - (txtrn.get_rect().width/2)), ((width/2) - (txtrn.get_rect().height)/2))) pygame.display.flip() while not start: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.KEYDOWN: start == True while start == True: for x in range(3): #3 Trials screen.fill((255, 255, 255)) pygame.draw.line(screen, (0, 0, 0), (height/2, width/2 - 10), (height/2, width/2 + 10), 2) pygame.draw.line(screen, (0, 0, 0), (height/2 - 10, width/2), (height/2 + 10, width/2), 2) pygame.display.flip() pygame.time.delay(random.randint(2000, 8000)) pygame.draw.circle(screen, red, (height/2, width/2), 80) pygame.display.flip() t0 = time.clock() pygame.event.clear() running = True while running: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: t1 = time.clock() tr = (t1 - t0) data.append(round(tr, 3)) running = False elif event.type == pygame.QUIT: pygame.quit() </code></pre>
0
2016-10-11T23:42:12Z
39,989,158
<pre><code>while True: start = False </code></pre> <p>This is an infinite loop.</p>
0
2016-10-12T01:28:04Z
[ "python", "pygame", "tr" ]
Converting url encode data from curl to json object in python using requests
39,988,480
<p>What is the best way to convert the below curl post into python request using the requests module:</p> <pre><code>curl -X POST https://api.google.com/gmail --data-urlencode json='{"user": [{"message":"abc123", "subject":"helloworld"}]}' </code></pre> <p>I tried using python requests as below, but it didn't work: </p> <pre><code>payload = {"user": [{"message":"abc123", "subject":"helloworld"}]} url = https://api.google.com/gmail requests.post(url, data=json.dumps(payload),auth=(user, password)) </code></pre> <p>Can anybody help. </p>
0
2016-10-11T23:49:17Z
39,988,758
<p>As the comment mentioned, you should put your <code>url</code> variable string in quotes <code>""</code> first.</p> <p>Otherwise, your question is not clear. What errors are being thrown and/or behavior is happening?</p> <p><a href="http://stackoverflow.com/questions/17936555/how-to-construct-the-curl-command-from-python-requests-module"> New cURL method in Python </a></p>
0
2016-10-12T00:31:00Z
[ "python", "http-post", "python-requests" ]
Find local non-loopback ip address in Python
39,988,525
<p>How can I find a list of local non-loopback IP addresses in Python (and stay platform-independent)?</p>
0
2016-10-11T23:56:51Z
39,988,526
<p>The <a href="https://pypi.python.org/pypi/netifaces" rel="nofollow">netifaces</a> package provides a platform-independent way of getting network interface and address info. The <a href="https://pypi.python.org/pypi/ipaddress" rel="nofollow">ipaddress</a> package (standard in Python3, external in Python2) provides a handy <code>is_loopback</code> method.</p> <p>It's not exactly trivial, but here is some code that worked at least once for me:</p> <pre><code>import netifaces import ipaddress from pprint import pprint def get_local_non_loopback_ipv4_addresses(): for interface in netifaces.interfaces(): # Not all interfaces have an IPv4 address: if netifaces.AF_INET in netifaces.ifaddresses(interface): # Some interfaces have multiple IPv4 addresses: for address_info in netifaces.ifaddresses(interface)[netifaces.AF_INET]: address_object = ipaddress.IPv4Address(unicode(address_info['addr'], 'utf-8')) if not address_object.is_loopback: yield address_info['addr'] pprint(list(get_local_non_loopback_ipv4_addresses())) </code></pre> <p>That <code>address_info</code> variable will also have <code>netmask</code> and <code>broadcast</code> keys you can access for more info.</p> <p>The <code>IPv4Address</code> object also has <code>is_private</code> and <code>is_global</code> methods you can use for similar queries.</p>
0
2016-10-11T23:56:51Z
[ "python" ]
HTTP Error 400 Bad Request (Other similar questions aren't helping me)
39,988,554
<p>None of the other similarly names questions have solved my problem.</p> <p>Why am I getting this error? I copied and pasted this example code from google's github.</p> <pre><code>import pprint from googleapiclient.discovery import build def main(): # Build a service object for interacting with the API. Visit # the Google APIs Console &lt;http://code.google.com/apis/console&gt; # to get an API key for your own application. service = build("customsearch", "v1", developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0") res = service.cse().list( q='lectures', cx='017576662512468239146:omuauf_lfve', ).execute() pprint.pprint(res) if __name__ == '__main__': main() </code></pre> <p><a href="https://github.com/google/google-api-python-client/blob/master/samples/customsearch/main.py" rel="nofollow">Here is where I go the code from</a></p> <p>I am getting this error :</p> <pre><code>Traceback (most recent call last): File "testpython", line 17, in &lt;module&gt; main() File "testpython", line 12, in main cx='017576662512468239146:omuauf_lfve', File "/home/mddrill/.local/lib/python2.7/site-packages/oauth2client/util.py", line 137, in positional_wrapper return wrapped(*args, **kwargs) File "/home/mddrill/.local/lib/python2.7/site-packages/googleapiclient/http.py", line 838, in execute raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: &lt;HttpError 400 when requesting https://www.googleapis.com/customsearch/v1?q=lectures&amp;alt=json&amp;cx=017576662512468239146%3Aomuauf_lfve&amp;key=AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0 returned "Bad Request"&gt; </code></pre>
2
2016-10-12T00:00:54Z
39,988,664
<p>I tried to access that <a href="https://www.googleapis.com/customsearch/v1?q=lectures&amp;alt=json&amp;cx=017576662512468239146%3Aomuauf_lfve&amp;key=AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0" rel="nofollow">bad URL</a> and is says that the reason is "keyExpired". Also the code you put here includes the following documentation: </p> <blockquote> <p>Visit the Google APIs Console <a href="http://code.google.com/apis/console" rel="nofollow">http://code.google.com/apis/console</a> to get an API key for your own application.</p> </blockquote> <p>Try doing as it says. Good luck!</p>
1
2016-10-12T00:16:43Z
[ "python", "google-api", "google-api-python-client" ]
How to pass through a list of queries to a pandas dataframe, and output the list of results?
39,988,589
<p>When selecting rows whose column value <code>column_name</code> equals a scalar, <code>some_value</code>, we use <code>==:</code></p> <pre><code>df.loc[df['column_name'] == some_value] </code></pre> <p>or use <code>.query()</code> </p> <pre><code>df.query('column_name == some_value') </code></pre> <p>In a concrete example:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'Col1': 'what are men to rocks and mountains'.split(), 'Col2': 'the curves of your lips rewrite history.'.split(), 'Col3': np.arange(7), 'Col4': np.arange(7) * 8}) print(df) Col1 Col2 Col3 Col4 0 what the 0 0 1 are curves 1 8 2 men of 2 16 3 to your 3 24 4 rocks lips 4 32 5 and rewrite 5 40 6 mountains history 6 48 </code></pre> <p>A query could be</p> <pre><code>rocks_row = df.loc[df['Col1'] == "rocks"] </code></pre> <p>which outputs</p> <pre><code>print(rocks_row) Col1 Col2 Col3 Col4 4 rocks lips 4 32 </code></pre> <p>I would like to pass through a list of values to query against a dataframe, which outputs a list of "correct queries". </p> <p>The queries to execute would be in a list, e.g.</p> <pre><code>list_match = ['men', 'curves', 'history'] </code></pre> <p>which would output all rows which meet this condition, i.e. </p> <pre><code>matches = pd.concat([df1, df2, df3]) </code></pre> <p>where </p> <pre><code>df1 = df.loc[df['Col1'] == "men"] df2 = df.loc[df['Col1'] == "curves"] df3 = df.loc[df['Col1'] == "history"] </code></pre> <p>My idea would be to create a function that takes in a </p> <pre><code>output = [] def find_queries(dataframe, column, value, output): for scalar in value: query = dataframe.loc[dataframe[column] == scalar]] output.append(query) # append all query results to a list return pd.concat(output) # return concatenated list of dataframes </code></pre> <p>However, this appears to be exceptionally slow, and doesn't actually take advantage of the pandas data structure. What is the "standard" way to pass through a list of queries through a pandas dataframe? </p> <p>EDIT: How does this translate into "more complex" queries in pandas? e.g. <code>where</code> with an HDF5 document? </p> <pre><code>df.to_hdf('test.h5','df',mode='w',format='table',data_columns=['A','B']) pd.read_hdf('test.h5','df') pd.read_hdf('test.h5','df',where='A=["foo","bar"] &amp; B=1') </code></pre>
5
2016-10-12T00:06:20Z
39,989,023
<p>The best way to deal with this is by indexing into the rows using a Boolean series as you would in R.</p> <p>Using your df as an example,</p> <pre><code>In [5]: df.Col1 == "what" Out[5]: 0 True 1 False 2 False 3 False 4 False 5 False 6 False Name: Col1, dtype: bool In [6]: df[df.Col1 == "what"] Out[6]: Col1 Col2 Col3 Col4 0 what the 0 0 </code></pre> <p>Now we combine this with the pandas isin function.</p> <pre><code>In [8]: df[df.Col1.isin(["men","rocks","mountains"])] Out[8]: Col1 Col2 Col3 Col4 2 men of 2 16 4 rocks lips 4 32 6 mountains history. 6 48 </code></pre> <p>To filter on multiple columns we can chain them together with &amp; and | operators like so.</p> <pre><code>In [10]: df[df.Col1.isin(["men","rocks","mountains"]) | df.Col2.isin(["lips","your"])] Out[10]: Col1 Col2 Col3 Col4 2 men of 2 16 3 to your 3 24 4 rocks lips 4 32 6 mountains history. 6 48 In [11]: df[df.Col1.isin(["men","rocks","mountains"]) &amp; df.Col2.isin(["lips","your"])] Out[11]: Col1 Col2 Col3 Col4 4 rocks lips 4 32 </code></pre>
1
2016-10-12T01:09:00Z
[ "python", "python-3.x", "pandas", "dataframe" ]
How to pass through a list of queries to a pandas dataframe, and output the list of results?
39,988,589
<p>When selecting rows whose column value <code>column_name</code> equals a scalar, <code>some_value</code>, we use <code>==:</code></p> <pre><code>df.loc[df['column_name'] == some_value] </code></pre> <p>or use <code>.query()</code> </p> <pre><code>df.query('column_name == some_value') </code></pre> <p>In a concrete example:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'Col1': 'what are men to rocks and mountains'.split(), 'Col2': 'the curves of your lips rewrite history.'.split(), 'Col3': np.arange(7), 'Col4': np.arange(7) * 8}) print(df) Col1 Col2 Col3 Col4 0 what the 0 0 1 are curves 1 8 2 men of 2 16 3 to your 3 24 4 rocks lips 4 32 5 and rewrite 5 40 6 mountains history 6 48 </code></pre> <p>A query could be</p> <pre><code>rocks_row = df.loc[df['Col1'] == "rocks"] </code></pre> <p>which outputs</p> <pre><code>print(rocks_row) Col1 Col2 Col3 Col4 4 rocks lips 4 32 </code></pre> <p>I would like to pass through a list of values to query against a dataframe, which outputs a list of "correct queries". </p> <p>The queries to execute would be in a list, e.g.</p> <pre><code>list_match = ['men', 'curves', 'history'] </code></pre> <p>which would output all rows which meet this condition, i.e. </p> <pre><code>matches = pd.concat([df1, df2, df3]) </code></pre> <p>where </p> <pre><code>df1 = df.loc[df['Col1'] == "men"] df2 = df.loc[df['Col1'] == "curves"] df3 = df.loc[df['Col1'] == "history"] </code></pre> <p>My idea would be to create a function that takes in a </p> <pre><code>output = [] def find_queries(dataframe, column, value, output): for scalar in value: query = dataframe.loc[dataframe[column] == scalar]] output.append(query) # append all query results to a list return pd.concat(output) # return concatenated list of dataframes </code></pre> <p>However, this appears to be exceptionally slow, and doesn't actually take advantage of the pandas data structure. What is the "standard" way to pass through a list of queries through a pandas dataframe? </p> <p>EDIT: How does this translate into "more complex" queries in pandas? e.g. <code>where</code> with an HDF5 document? </p> <pre><code>df.to_hdf('test.h5','df',mode='w',format='table',data_columns=['A','B']) pd.read_hdf('test.h5','df') pd.read_hdf('test.h5','df',where='A=["foo","bar"] &amp; B=1') </code></pre>
5
2016-10-12T00:06:20Z
40,004,375
<p>If I understood your question correctly you can do it either using boolean indexing as <a href="http://stackoverflow.com/a/39989023/5741205">@uhjish has already shown in his answer</a> or using <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-query-method-experimental" rel="nofollow">query()</a> method:</p> <pre><code>In [30]: search_list = ['rocks','mountains'] In [31]: df Out[31]: Col1 Col2 Col3 Col4 0 what the 0 0 1 are curves 1 8 2 men of 2 16 3 to your 3 24 4 rocks lips 4 32 5 and rewrite 5 40 6 mountains history. 6 48 </code></pre> <p><code>.query()</code> method:</p> <pre><code>In [32]: df.query('Col1 in @search_list and Col4 &gt; 40') Out[32]: Col1 Col2 Col3 Col4 6 mountains history. 6 48 In [33]: df.query('Col1 in @search_list') Out[33]: Col1 Col2 Col3 Col4 4 rocks lips 4 32 6 mountains history. 6 48 </code></pre> <p>using boolean indexing:</p> <pre><code>In [34]: df.ix[df.Col1.isin(search_list) &amp; (df.Col4 &gt; 40)] Out[34]: Col1 Col2 Col3 Col4 6 mountains history. 6 48 In [35]: df.ix[df.Col1.isin(search_list)] Out[35]: Col1 Col2 Col3 Col4 4 rocks lips 4 32 6 mountains history. 6 48 </code></pre> <p><strong>UPDATE:</strong> using function:</p> <pre><code>def find_queries(df, qry, debug=0, **parms): if debug: print('[DEBUG]: Query:\t' + qry.format(**parms)) return df.query(qry.format(**parms)) In [31]: find_queries(df, 'Col1 in {Col1} and Col4 &gt; {Col4}', Col1='@search_list', Col4=40) ...: Out[31]: Col1 Col2 Col3 Col4 6 mountains history. 6 48 In [32]: find_queries(df, 'Col1 in {Col1} and Col4 &gt; {Col4}', Col1='@search_list', Col4=10) Out[32]: Col1 Col2 Col3 Col4 4 rocks lips 4 32 6 mountains history. 6 48 </code></pre> <p>including debugging info (print query):</p> <pre><code>In [40]: find_queries(df, 'Col1 in {Col1} and Col4 &gt; {Col4}', Col1='@search_list', Col4=10, debug=1) [DEBUG]: Query: Col1 in @search_list and Col4 &gt; 10 Out[40]: Col1 Col2 Col3 Col4 4 rocks lips 4 32 6 mountains history. 6 48 </code></pre>
1
2016-10-12T17:03:49Z
[ "python", "python-3.x", "pandas", "dataframe" ]
Running Fortran executable within Python script
39,988,621
<p>I am writing a Python script with the following objectives:</p> <ol> <li>Starting from current working directory, change directory to child directory 'A'</li> <li>Make slight adjustments to a fort.4 file</li> <li>Run a Fortran binary file (the syntax of which is <code>../../../../</code> continuing until I hit the folder containing the binary); return to 2. until my particular objective is complete, then</li> <li>Back out of child directory to parent, then enter another child directory and return to 2. until I have iterated through all the folders in question.</li> </ol> <p>The code is coming along well. I am having to rely heavily upon Python's OS module for the directory work. However, I have never had any experience a) making minor adjustments of a file using python and b) running an executable. Could you guys give me some ideas on Python modules, direct me to a similar stack source etc, or perhaps give ways that this can be accomplished? I understand this is a vague question, so please ask if you do not understand what I am asking and I will elaborate. Also, the changes I have to make to this fort.4 file are repetitive in nature; they all happen at the same position in the file.</p> <p>Cheers</p> <p>EDIT:: entire fort.4 file:</p> <pre><code>file_name movie1.dat !name of a general file the binary reads nbr_box ! line3-8 is general info 2 this_box 1 lrdf_bead .true. beadid1 C1 !this is the line I must change beadid2 F4 !This is a second line I must change lrdf_com .false. bin_width 0.04 rcut 7 </code></pre> <p>So really, I need to change "C1" to "C2" for example. The changes are very insignificant to make, but I must emphasize the fact that the main fortran executable reads this fort.4, as well as this movie1.dat file that I have already created. Hope this helps</p>
3
2016-10-12T00:09:33Z
39,988,971
<p>Ok so there is a few important things here, first we need to be able to manage our cwd, for that we will use the os module </p> <pre><code>import os </code></pre> <p>whenever a method operates on a folder it is important to change directories into the folder and back to the parent folder. This can also be achieved with the os module.</p> <pre><code>def operateOnFolder(folder): os.chdir(folder) ... os.chdir("..") </code></pre> <p>Now we need to do some method for each directory, that comes with this,</p> <pre><code>for k in os.listdir(".") if os.path.isdir(k): operateOnFolder(k) </code></pre> <p>Finally in order to operate on some preexisting FORTRAN file we can use the builtin file operators.</p> <pre><code>fileSource = open("someFile.f","r") fileText = fileSource.read() fileSource.close() fileLines = fileText.split("\n") # change a line in the file with -&gt; fileLines[42] = "the 42nd line" fileText = "\n".join(fileLines) fileOutput = open("someFile.f","w") fileOutput.write(fileText) </code></pre> <p>You can create and run your executable <code>output.fx</code> from <code>source.f90</code>::</p> <pre><code>subprocess.call(["gfortran","-o","output.fx","source.f90"])#create subprocess.call(["output.fx"]) #execute </code></pre>
0
2016-10-12T01:03:05Z
[ "python", "fortran" ]
Global connection to 3rd party api Flask
39,988,650
<p>I have a Flask app running on Heroku that connects to the Google Maps API during a request. Something like this:</p> <pre><code>client = geocoders.GoogleV3( client_id=self.config['GM_CLIENT_ID'], secret_key=self.config['GM_SECRET_KEY'] ) client.do_geocoding(...) </code></pre> <p>Right now I am creating a new client for every request. How can I have one connection that persists across multiple requests?</p>
2
2016-10-12T00:14:43Z
39,991,524
<p>Turns out it's as simple as storing the client instance in a global variable.</p>
0
2016-10-12T06:05:20Z
[ "python", "flask" ]
Strange NaN values for loss function (MLP) in TensorFlow
39,988,687
<p>I hope you can help me. I'm implementing a small multilayer perceptron using <strong>TensorFlow</strong> and a few tutorials I found on the internet. The problem is that the net is able to learn something, and by this I mean that I am able to somehow optimize the value of the training error and get a decent accuracy, and that's what I was aiming for. However, I am recording with Tensorboard some strange NaN values for the loss function. Quite a lot actually. Here you can see my latest Tensorboard recording of the loss function output. Please all those triangles followed by discontinuities - those are the NaN values, note also that the general trend of the function is what you would expect it to be. </p> <p><strong>Tensorboard report</strong> <a href="https://i.stack.imgur.com/6oMCH.png" rel="nofollow"><img src="https://i.stack.imgur.com/6oMCH.png" alt="Evolution of my loss function in Tensorboard, those triangles are the NaN values"></a></p> <p>I thought that a high learning rate could be the problem, or maybe a net that's too deep, causing the gradients to explode, so I lowered the learning rate and used a single hidden layer (this is the configuration of the image above, and the code below). Nothing changed, I just caused the learning process to be slower.</p> <p><strong>Tensorflow Code</strong></p> <pre><code>import tensorflow as tf import numpy as np import scipy.io, sys, time from numpy import genfromtxt from random import shuffle #shuffles two related lists #TODO check that the two lists have same size def shuffle_examples(examples, labels): examples_shuffled = [] labels_shuffled = [] indexes = list(range(len(examples))) shuffle(indexes) for i in indexes: examples_shuffled.append(examples[i]) labels_shuffled.append(labels[i]) examples_shuffled = np.asarray(examples_shuffled) labels_shuffled = np.asarray(labels_shuffled) return examples_shuffled, labels_shuffled # Import and transform dataset dataset = scipy.io.mmread(sys.argv[1]) dataset = dataset.astype(np.float32) all_labels = genfromtxt('oh_labels.csv', delimiter=',') num_examples = all_labels.shape[0] dataset, all_labels = shuffle_examples(dataset, all_labels) # Split dataset into training (66%) and test (33%) set training_set_size = 2000 training_set = dataset[0:training_set_size] training_labels = all_labels[0:training_set_size] test_set = dataset[training_set_size:num_examples] test_labels = all_labels[training_set_size:num_examples] test_set, test_labels = shuffle_examples(test_set, test_labels) # Parameters learning_rate = 0.0001 training_epochs = 150 mini_batch_size = 100 total_batch = int(num_examples/mini_batch_size) # Network Parameters n_hidden_1 = 50 # 1st hidden layer of neurons #n_hidden_2 = 16 # 2nd hidden layer of neurons n_input = int(sys.argv[2]) # number of features after LSA n_classes = 2; # Tensorflow Graph input with tf.name_scope("input"): x = tf.placeholder(np.float32, shape=[None, n_input], name="x-data") y = tf.placeholder(np.float32, shape=[None, n_classes], name="y-labels") print("Creating model.") # Create model def multilayer_perceptron(x, weights, biases): with tf.name_scope("h_layer_1"): # First hidden layer with SIGMOID activation layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_1 = tf.nn.sigmoid(layer_1) #with tf.name_scope("h_layer_2"): # Second hidden layer with SIGMOID activation #layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) #layer_2 = tf.nn.sigmoid(layer_2) with tf.name_scope("out_layer"): # Output layer with SIGMOID activation out_layer = tf.add(tf.matmul(layer_1, weights['out']), biases['bout']) out_layer = tf.nn.sigmoid(out_layer) return out_layer # Layer weights with tf.name_scope("weights"): weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1], stddev=0.01, dtype=np.float32)), #'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], stddev=0.05, dtype=np.float32)), 'out': tf.Variable(tf.random_normal([n_hidden_1, n_classes], stddev=0.01, dtype=np.float32)) } # Layer biases with tf.name_scope("biases"): biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1], dtype=np.float32)), #'b2': tf.Variable(tf.random_normal([n_hidden_2], dtype=np.float32)), 'bout': tf.Variable(tf.random_normal([n_classes], dtype=np.float32)) } # Construct model pred = multilayer_perceptron(x, weights, biases) # Define loss and optimizer with tf.name_scope("loss"): cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) with tf.name_scope("adam"): optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Initializing the variables init = tf.initialize_all_variables() # Define summaries tf.scalar_summary("loss", cost) summary_op = tf.merge_all_summaries() print("Model ready.") # Launch the graph with tf.Session() as sess: sess.run(init) board_path = sys.argv[3]+time.strftime("%Y%m%d%H%M%S")+"/" writer = tf.train.SummaryWriter(board_path, graph=tf.get_default_graph()) print("Starting Training.") for epoch in range(training_epochs): training_set, training_labels = shuffle_examples(training_set, training_labels) for i in range(total_batch): # example loading minibatch_x = training_set[i*mini_batch_size:(i+1)*mini_batch_size] minibatch_y = training_labels[i*mini_batch_size:(i+1)*mini_batch_size] # Run optimization op (backprop) and cost op _, summary = sess.run([optimizer, summary_op], feed_dict={x: minibatch_x, y: minibatch_y}) # Write log writer.add_summary(summary, epoch*total_batch+i) print("Optimization Finished!") # Test model test_error = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) accuracy = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(accuracy, np.float32)) test_error, accuracy = sess.run([test_error, accuracy], feed_dict={x: test_set, y: test_labels}) print("Test Error: " + test_error.__str__() + "; Accuracy: " + accuracy.__str__()) print("Tensorboard path: " + board_path) </code></pre>
2
2016-10-12T00:19:31Z
40,043,524
<p>I'll post the solution here just in case someone gets stuck in a similar way. If you see that plot very carefully, all of the NaN values (the triangles) come on a regular basis, like if at the end of every loop something causes the output of the loss function to just go NaN. The problem is that, at every loop, I was giving a mini batch of "empty" examples. The problem lies in how I declared my inner training loop:</p> <pre><code>for i in range(total_batch): </code></pre> <p>Now what we'd like here is to have Tensorflow go through the entire training set, one minibatch at a time. So let's look at how total_batch was declared:</p> <pre><code>total_batch = int(num_examples / mini_batch_size) </code></pre> <p>That is not quite what we'd want to do - as we want to consider the training set <strong>only</strong>. So changing this line to:</p> <pre><code>total_batch = int(training_set_size / mini_batch_size) </code></pre> <p>Fixed the problem. It is to be noted that Tensorflow seemed to ignore those "empty" batches, computing NaN for the loss but not updating the gradients - that's why the trend of the loss was one of a net that's learning something.</p>
0
2016-10-14T12:46:02Z
[ "python", "machine-learning", "tensorflow", "deep-learning", "tensorboard" ]
How should I enforce permission checking when file is reached/downloaded in Django?
39,988,697
<p>I don't know this is a typical thing to do in web application, but what we achieve is that, let's say we have a Person model, inside this model, we have a <code>FileField</code> stores user's photo:</p> <pre><code>class Person(models.Model): photo = models.FileField(upload_to='Person_photo') </code></pre> <p>What I want to achieve is that <em>only</em> the owner can see his or her photo. People who log on a different account or even not log in should not be able to see the photo. Let's assume we have a way to check whether a photo belongs to a certain user or not:</p> <pre><code>def permission(photo_filename, pid): # return True if photo_filename exists and belongs to the person pid </code></pre> <p>We can figure this part out, for example, use permission system provided in Django. Of course from the <code>views.py</code> we can control whatever image we want to show on the page, but for example, we want to block people make attempts to figure out the URLs and get the photo, for example, typing</p> <pre><code>http://some.domain/media/Person_photo/Amy.jpg </code></pre> <p>in URL bar in the browser should <em>only</em> work if she is Amy. What is a good way to do it? Is there a library for this purpose?</p>
2
2016-10-12T00:21:50Z
39,990,827
<p>You can define view for this</p> <p><strong>view.py</strong></p> <pre><code>from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.contrib.auth.decorators import login_required from appname.models import Person @login_required def show_photo(request): person = get_object_or_404(Person, user=request.user) response = HttpResponse(person.photo.read(), content_type="image/jpg") response['Content-Disposition'] = 'filename=photo.jpg' return response </code></pre> <p><strong>urls.py</strong></p> <pre><code>urlpatterns += [ url(r'^photo/$', show_photo), ] </code></pre> <p>Users will only see their photo.</p>
1
2016-10-12T05:00:22Z
[ "python", "django" ]
How to *not* create an instance
39,988,779
<p>I would like to avoid the creation of an instance if the arguments do not match the expected values.<br> I.e. in short: </p> <pre><code>#!/usr/bin/env python3 class Test(object): def __init__(self, reallydoit = True): if reallydoit: self.done = True else: return None make_me = Test() make_me_not = Test(reallydoit=False) </code></pre> <p>I'd like <code>make_me_not</code> to be <code>None</code>, and I thought that <code>return None</code> could do it, but this variable is an instance of <code>Test</code> too:</p> <pre><code>&gt;&gt;&gt; make_me &lt;__main__.Test object at 0x7fd78c732390&gt; &gt;&gt;&gt; make_me_not &lt;__main__.Test object at 0x7fd78c732470&gt; </code></pre> <p>I'm sure there's a way to do this, but my Google-fu failed me so far.<br> Thank you for any help. </p> <p><strong>EDIT:</strong> I would prefer this to be handled silently; the conditional should be interpreted as "Best not create this specific instance" instead of "You are using this class the wrong way". So yes, raising an error and then handling it is a possibility, but I'd prefer making less ruckus.</p>
2
2016-10-12T00:34:44Z
39,988,807
<p>Just <a href="https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement" rel="nofollow">raise</a> an exception in the <a href="https://docs.python.org/3/reference/datamodel.html#object.__init__" rel="nofollow"><em>__init__</em></a> method:</p> <pre><code>class Test(object): def __init__(self, reallydoit = True): if reallydoit: self.done = True else: raise ValueError('Not really doing it') </code></pre> <p>The other approach is to move your code to a <a href="https://docs.python.org/3/reference/datamodel.html#object.__new__" rel="nofollow"><em>__new__</em></a> method:</p> <pre><code>class Test(object): def __new__(cls, reallydoit = True): if reallydoit: return object.__new__(cls) else: return None </code></pre> <p>Lastly, you could move the creation decision into a <a href="https://en.wikipedia.org/wiki/Factory_method_pattern" rel="nofollow">factory function</a>:</p> <pre><code>class Test(object): pass def maybe_test(reallydoit=True): if reallydoit: return Test() return None </code></pre>
7
2016-10-12T00:38:41Z
[ "python", "python-3.x" ]
using defaultdict in a array in python 2.7
39,988,788
<p>I'm trying to create a dictionary where the same key can have different values from an array. In the past i created a dictionary with positions on each list of the list, but I found a bug where the same key can have more than one value and it's breaking the main code. ie.</p> <pre><code>my_array = [['a','b','c'],['a','e','d'],['f','g','h']] my dict = dict([p[0], p[2]] for p in my_array) my dict = {'a': 'c', 'f': 'h'} What I need is: my_dict = {'a': ['c','d'], 'f': 'h'} </code></pre> <p>I have tried with defaultdict but so far I'm getting TypeError Exception. I have tried initializing it as a string defaultdict(str) and a list defaultdict(list) with no success</p> <pre><code>my_dict = defaultdict((my_dict[p[0]].append(p[2])) for p in my_array) or my_dict = defaultdict(([p[0], p[2]]).append(p[2]) for p in a_array) </code></pre> <p>Always getting TypeError exception, suggestions please?</p>
-1
2016-10-12T00:35:38Z
39,988,849
<p>The <code>defaultdict</code> contructor takes a <em>callable</em> that will service as the default value for any undefined key. In your case, the default value is simply a <code>list</code>.</p> <p>This code does what you want:</p> <pre><code>from collections import defaultdict my_dict = defaultdict(list) for p in [['a','b','c'],['a','e','d'],['f','g','h']]: my_dict[p[0]].append(p[2]) my_dict = dict(my_dict) </code></pre>
2
2016-10-12T00:43:30Z
[ "python", "python-2.7" ]
using defaultdict in a array in python 2.7
39,988,788
<p>I'm trying to create a dictionary where the same key can have different values from an array. In the past i created a dictionary with positions on each list of the list, but I found a bug where the same key can have more than one value and it's breaking the main code. ie.</p> <pre><code>my_array = [['a','b','c'],['a','e','d'],['f','g','h']] my dict = dict([p[0], p[2]] for p in my_array) my dict = {'a': 'c', 'f': 'h'} What I need is: my_dict = {'a': ['c','d'], 'f': 'h'} </code></pre> <p>I have tried with defaultdict but so far I'm getting TypeError Exception. I have tried initializing it as a string defaultdict(str) and a list defaultdict(list) with no success</p> <pre><code>my_dict = defaultdict((my_dict[p[0]].append(p[2])) for p in my_array) or my_dict = defaultdict(([p[0], p[2]]).append(p[2]) for p in a_array) </code></pre> <p>Always getting TypeError exception, suggestions please?</p>
-1
2016-10-12T00:35:38Z
39,988,852
<p>You can't do this with a comprehension/generator expression. Instead, try this:</p> <pre><code>my_dict = {} for p in my_array: my_dict.setdefault(p[0], []).append(p[2]) </code></pre> <p>You can also do it with a <code>defaultdict</code> if you insist, but it seems like overkill:</p> <pre><code>my_dict = collections.defaultdict(list) for p in my_array: my_dict[p[0]].append(p[2]) </code></pre> <p>All your values will now be lists, even if they contain only a single item, which doesn't appear to be what you want based on your question. It probably actually is, as it's much easier to deal with values that are always the same type. But if you do want the single values outside of lists, I think the most straightforward way is to post-process after building the dictionary and convert single-item lists back to single values:</p> <pre><code>for k, v in my_dict.iteritems(): # n.b. just .items() in Python 3 if len(v) == 1: my_dict[k] = v[0] </code></pre> <p>Otherwise, you end up having to check the type of each value already in the dictionary when you're adding a new one, and convert the value to a list when you go to add the second one.</p>
2
2016-10-12T00:44:25Z
[ "python", "python-2.7" ]
re.sub correcting slashes in URL
39,988,828
<p>The input is a URL that may contain two or more sucessive slashes. I corrected it with the following two commands, which seems to be quite satisfying readable solution.</p> <p>I wonder if you could achieve the same with only one re.sub() command.</p> <pre><code>url = re.sub("/[/]+", "/", url) # two or more slashes replace with one slash url = re.sub("http:/", "http://", url) # correct one mistake of the previous command </code></pre>
0
2016-10-12T00:40:57Z
39,988,943
<p>Yes you can. Use the negative lookbehind markup <code>?&lt;!</code>:</p> <pre><code>print(re.sub('(?&lt;!http:)//+', '/', 'http://httpbin.org//ip')) # http://httpbin.org/ip </code></pre>
2
2016-10-12T00:58:49Z
[ "python", "regex" ]
Python For Loop Syntax to Java
39,988,862
<pre><code> for j in [c for c in coinValueList if c &lt;= cents]: </code></pre> <p>How would you write this for loop out in java? Is it</p> <pre><code>for(j=0, j &lt;= cents, j++){ for(c=0; c&lt;= cents, j++){ </code></pre> <p>I'm not sure what c and j are supposed to be compared to. CoinValueList = {1,5,10,25} cents = 0 -- it's in its own for loop before these two.</p>
-1
2016-10-12T00:45:31Z
39,988,911
<p>Let's decompose:</p> <pre><code>array = [c for c in coinValueList if c &lt;= cents] # produces an array of coins from coinValueList that are &lt;= cents for j in array: # iterates over array #stuff </code></pre> <p>So we can do that in only one loop, and the java equivalent would be:</p> <pre><code>for(int j=0; j&lt;coinValueList.length; j++) { if(coinValueList[j] &lt;= cents) { #stuff } } </code></pre>
3
2016-10-12T00:53:48Z
[ "java", "python", "for-loop", "syntax" ]
Python For Loop Syntax to Java
39,988,862
<pre><code> for j in [c for c in coinValueList if c &lt;= cents]: </code></pre> <p>How would you write this for loop out in java? Is it</p> <pre><code>for(j=0, j &lt;= cents, j++){ for(c=0; c&lt;= cents, j++){ </code></pre> <p>I'm not sure what c and j are supposed to be compared to. CoinValueList = {1,5,10,25} cents = 0 -- it's in its own for loop before these two.</p>
-1
2016-10-12T00:45:31Z
39,989,180
<p>if you want to translate very literally in Java</p> <pre><code>List&lt;Integer&gt; newList = new ArrayList(); for(Integer c : coinValueList) { if(c &lt;= cents) { newList.append(c); } } for(Integer j : newList) { # do something } </code></pre> <p>but normally you don't need second <code>for</code> loop</p>
0
2016-10-12T01:31:07Z
[ "java", "python", "for-loop", "syntax" ]
Python printing "<built-in method ... object" instead of list
39,988,898
<pre><code>import numpy as np arr = list(map(float,input().split())) print(np.array(arr.reverse)) </code></pre> <p>Why is this printing this instead of the contents of the list?</p> <pre><code># outputs "&lt;built-in method reverse of list object at 0x107eeeec8&gt;" </code></pre>
1
2016-10-12T00:51:36Z
39,988,929
<p>You have two problems. </p> <p>The first problem is that you are not actually <em>calling</em> the reverse method on your array <code>arr</code>.</p> <p>You have this: <code>arr.reverse</code></p> <p>You have to actually call it -> <code>arr.reverse()</code></p> <p>Simple example below: </p> <pre><code>&gt;&gt;&gt; [1,2,3].reverse &lt;built-in method reverse of list object at 0x100662c68&gt; </code></pre> <p>Without calling <code>reverse</code>, the output you get is the uncalled reverse method of the <code>list</code> object. Which is very similar to the output you were getting. </p> <p>The second problem you have is that <code>reverse()</code> method does the reverse in place, which means it performs the reverse on <code>arr</code> (your arr will be reversed) and returns <code>None</code>. So, when you are passing this: </p> <pre><code>np.array(arr.reverse()) </code></pre> <p>You are returning the return of <code>arr.reverse()</code> to your <code>np.array</code> call, which is <code>None</code>.</p> <p>So, fixing those two items, by calling <code>arr.reverse()</code> on its on, and <em>then</em> passing <code>arr</code>, will give you the result you are expecting:</p> <pre><code>import numpy as np arr = list(map(float,input().split())) arr.reverse() res = np.array(arr) print(res) </code></pre> <p>Demo: </p> <pre><code>1 2 3 4 [ 4. 3. 2. 1.] </code></pre>
2
2016-10-12T00:56:17Z
[ "python", "printing" ]
How to get dataframe index from series?
39,988,903
<p>Say I extract a series from a dataframe (like what would happen with an apply function). I'm trying to find the original dataframe index from that series.</p> <pre><code>df=pd.DataFrame({'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]}) x=df.ix[0] x Out[109]: a 1 b 4 c 7 Name: 0, dtype: int64 </code></pre> <p>Notice the "Name: 0" piece at the bottom of the output. How can I get the value '0' from series object x?</p>
3
2016-10-12T00:52:28Z
39,990,744
<p>you access it with the <code>name</code> attribute</p> <pre><code>x.name 0 </code></pre> <p>take these examples</p> <pre><code>for i, row in df.iterrows(): print row.name, i 0 0 1 1 2 2 </code></pre> <p>Notice that the name attribute is the same as the variable <code>i</code> which is supposed to be the row index.</p> <p>It's the same for columns</p> <pre><code>for j, col in df.iteritems(): print col.name, j a a b b c c </code></pre>
2
2016-10-12T04:51:56Z
[ "python", "pandas", "indexing", "dataframe", "series" ]
Setting Django with virtualenvironment on an Apache
39,988,944
<p>I just want to know if you really need to put this code in the <strong>wsgi.py</strong> when you want to deploy in apache with your django virtual environment</p> <pre><code>activate_env=os.path.expanduser("/path/to/venv") execfile(activate_env, dict(__file__=activate_env)) </code></pre> <p>This is not mentioned in the Django docs. However my virtualenv seems not to be used whenever I load my django page on the browser and of course throws a 500 error because my installed packages is not available</p> <p>Here is my apache conf file:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerName ai-labs.co ServerAlias www.ai-labs.co ServerAdmin [email protected] DocumentRoot /var/www/html/ai-labs.co/ ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;Directory /var/www/html/ai-labs.co&gt; Options Indexes FollowSymLinks AllowOverride All Require all granted &lt;/Directory&gt; Alias /static /var/www/html/ai-labs.co/static &lt;Directory /var/www/html/ai-labs.co/static&gt; Require all granted &lt;/Directory&gt; Alias /static /var/www/html/ai-labs.co/media &lt;Directory /var/www/html/ai-labs.co/media&gt; Require all granted &lt;/Directory&gt; &lt;Directory /var/www/html/ai-labs.co/ai_labs_website&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; WSGIDaemonProcess ai-labs.co python-path=/var/www/html/ai-labs.co:/var/www/html/.virtualenvs_copy/ai-labs-website-pure-django/local/lib/python2.7/site-packages WSGIProcessGroup ai-labs.co WSGIScriptAlias / /var/www/html/ai-labs.co/ai_labs_website/wsgi.py process-group=ai-labs.co &lt;/VirtualHost&gt; </code></pre>
0
2016-10-12T00:59:00Z
39,989,515
<p>If you configure mod_wsgi correctly, no you don't. Read:</p> <ul> <li><a href="http://blog.dscpl.com.au/2014/09/using-python-virtual-environments-with.html" rel="nofollow">http://blog.dscpl.com.au/2014/09/using-python-virtual-environments-with.html</a></li> </ul>
0
2016-10-12T02:19:48Z
[ "python", "django", "apache" ]
In SQLAlchemy, how to call a different database tables according to month
39,989,014
<p>In SQLAlchemy, how to call a different database tables according to month. Each month corresponds to a database table. I did this, but there was a problem.</p> <pre><code>Class MyBaseClass (object):      Id = db.Column (db.Integer, primary_key = True) </code></pre> <p>In my interface, this is the case</p> <pre><code>Def test (): Time = request.get_json (). Get ( 'time') Tablename = str (time) # time format: such as 201610 Table_object = type (tablename.title (), (MyBaseClass, db.Model), { '__tablename__': tablename}) </code></pre> <p>The first call to the interface is fine, but if you call it a second time, the following error occurs</p> <pre><code>Specify 'extend_existing = True' to redefine options and columns on an existing Table object. Sqlalchemy.exc.InvalidRequestError: Table 'xxx' is already defined for this MetaData instance. </code></pre> <p>Whether the table can be dynamically built after the table to delete this instance? Because I have to call the second time, will suggest already.</p>
0
2016-10-12T01:07:41Z
40,028,237
<p>I am an SQLAlchemy beginner and just won exactly the same battle with the ORM framework. Your approach of constructing a new type is on target. You should also look at <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html#augmenting-the-base" rel="nofollow">Augmenting the Base</a> manual. Here is <a href="http://stackoverflow.com/questions/39863337/sqlalchemy-orm-with-dynamic-table-schema?noredirect=1#comment67043099_39863337">my solution</a> that combines Base augmentation and dynamic type creation.</p> <p>I have solved this problem, this but this is NOT how I "won" the fight. Here's my advice: SQLAlchemy ORM is designed to make your life easy, but to take advantage of it you have to align your data in line with ORM expectations. This is what I have done instead of fighting it, and am very happy with the end result.</p> <p>If, however, you need to stick with historic design or changing it does not make sense, then using ORM will bring more tears than joy and the easy way out is to switch to <a href="http://docs.sqlalchemy.org/en/latest/core/" rel="nofollow">SQLAlchemy Core</a> which is much more flexible and permissive.</p>
1
2016-10-13T18:19:53Z
[ "python", "mysql", "sqlalchemy" ]
How to remove an item that appears multiple times in a list by Python?
39,989,075
<p>I am a python beginner and I am wondering how to remove an item that appears multiple times in a list by Python. Here is my list: </p> <pre><code>["0101013132","0101410142","0101430144"] </code></pre> <p>The first thing I want to do is to replace all "01" by "1", the second thing is to replace"31","32" by "3" respectively and replace "41","42","43","44" by "4" respectively.</p> <p>I have no idea how to do so. Thank you!</p> <p>Sorry for confusion. What I want is to turn my list into this one: ["11133","11414","11414"]</p>
0
2016-10-12T01:15:35Z
39,989,172
<pre><code>my_list = ["0101013132","0101410142","0101430144"] normalized_list = [] for item in my_list: normalized_list.append(item.replace('01', '1').replace('31', '3').replace('32', '3')) # and so one...) print(normalized_list) </code></pre>
1
2016-10-12T01:30:24Z
[ "python" ]
How to remove an item that appears multiple times in a list by Python?
39,989,075
<p>I am a python beginner and I am wondering how to remove an item that appears multiple times in a list by Python. Here is my list: </p> <pre><code>["0101013132","0101410142","0101430144"] </code></pre> <p>The first thing I want to do is to replace all "01" by "1", the second thing is to replace"31","32" by "3" respectively and replace "41","42","43","44" by "4" respectively.</p> <p>I have no idea how to do so. Thank you!</p> <p>Sorry for confusion. What I want is to turn my list into this one: ["11133","11414","11414"]</p>
0
2016-10-12T01:15:35Z
39,989,216
<pre><code>L = ["0101013132","0101410142","0101430144"] answer = [s[::2].replace('0', '1') for s in L] In [7]: answer Out[7]: ['11133', '11414', '11414'] </code></pre>
0
2016-10-12T01:36:37Z
[ "python" ]
How to remove an item that appears multiple times in a list by Python?
39,989,075
<p>I am a python beginner and I am wondering how to remove an item that appears multiple times in a list by Python. Here is my list: </p> <pre><code>["0101013132","0101410142","0101430144"] </code></pre> <p>The first thing I want to do is to replace all "01" by "1", the second thing is to replace"31","32" by "3" respectively and replace "41","42","43","44" by "4" respectively.</p> <p>I have no idea how to do so. Thank you!</p> <p>Sorry for confusion. What I want is to turn my list into this one: ["11133","11414","11414"]</p>
0
2016-10-12T01:15:35Z
39,989,298
<pre><code>l = ["0101013132","0101410142","0101430144"] [ ''.join( map( lambda x : str(x)[0] ,map( int, map(''.join, zip( *( [iter(s)]*2) ) ) ) ) ) for s in l ] </code></pre>
0
2016-10-12T01:49:05Z
[ "python" ]
Django: Template Does Not Exist Error
39,989,150
<p>In My django app I have a view called 'StatsView' given below:</p> <pre><code>class StatsView(LoginRequiredMixin, View): login_url = '/signin/' def get(self, request, template='app_folder/ad_accounts/pixel_stats.html', *args, **kwargs): #Code return render(request, template, context) </code></pre> <p><code>app/urls.py</code></p> <pre><code>url( r'^ad_accounts/(?P&lt;ad_account_id&gt;[^/]+)/pixel_stats', StatsView.as_view(), name="pixel_stats" ), </code></pre> <p><strong>template</strong> <code>pixel_stats.html</code></p> <pre><code>&lt;p&gt; test&lt;/p&gt; </code></pre> <p>However when I go to <code>localhost:8000/ad_accounts/acctid/pixel_stats/</code> I keep running into a <code>Template DoesNotExist Error</code>. I cant seem to figure out where Im going wrong. Ive added a bunch of URLs and havent run into this issue for any one them.</p> <p>My app structure is as follows:</p> <pre><code>project/ app/ templates/ app_folder/ ad_accounts/ pixel_stats.html views/ ad_accounts/ stats.py </code></pre>
-1
2016-10-12T01:26:50Z
40,009,599
<p>Silly mistake. Solved it by adding a <code>$</code> at the end in my <code>url</code>.</p> <pre><code>url( r'^ad_accounts/(?P&lt;ad_account_id&gt;[^/]+)/pixel_stats/$', StatsView.as_view(), name="pixel_stats" ), </code></pre>
0
2016-10-12T22:49:29Z
[ "python", "django" ]
How to define function arguments partially? Python
39,989,189
<p>If I have a function with some arguments, I can define a duck function like this:</p> <pre><code>&gt;&gt;&gt; def f(x, y=0, z=42): return x + y * z ... &gt;&gt;&gt; f(1,2,3) 7 &gt;&gt;&gt; g = f &gt;&gt;&gt; f(1,2) 85 &gt;&gt;&gt; g(1,2) 85 </code></pre> <p>I've tried to override the arguments partially but this didn't work:</p> <pre><code>&gt;&gt;&gt; g = f(z=23) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: f() takes at least 1 argument (1 given) </code></pre> <p><strong>How do I define function arguments partially for the duck function?</strong> </p>
2
2016-10-12T01:32:21Z
39,989,207
<p>Use <a href="http://yourFile.write(str(self.textEdit.toPlainText()))" rel="nofollow"><code>functools.partial</code></a></p> <pre><code>&gt;&gt;&gt; from functools import partial &gt;&gt;&gt; def f(x, y=0, z=42): return x + y * z ... &gt;&gt;&gt; g = partial(f, z=23) &gt;&gt;&gt; g(1,2) 47 &gt;&gt;&gt; f(1,2,23) 47 </code></pre>
2
2016-10-12T01:34:31Z
[ "python", "function", "arguments", "keyword-argument" ]
How to handle urllib2 socket timeouts?
39,989,350
<p>So the following has worked for other links that have timed out and has continued to the next link in the loop. However for this link I got an error. I am not sure why that is and how to fix it so that when it happens it just browses to the next image.</p> <pre><code>try: image_file = urllib2.urlopen(submission.url, timeout = 5) with open('/home/mona/computer_vision/image_retrieval/images/' + category + '/' + datetime.datetime.now().strftime('%y-%m-%d-%s') + submission.url[-5:], 'wb') as output_image: output_image.write(image_file.read()) except urllib2.URLError as e: print(e) continue </code></pre> <p>The error is:</p> <pre class="lang-none prettyprint-override"><code>[LOG] Done Getting http://i.imgur.com/b6fhEkWh.jpg submission id is: 1skepf [LOG] Getting url: http://www.redbubble.com/people/crtjer/works/11181520-bling-giraffe [LOG] Getting url: http://www.youtube.com/watch?v=Y7iuOZVJhs0 [LOG] Getting url: http://imgur.com/8a62PST [LOG] Getting url: http://www.youtube.com/watch?v=DFZFiFCsTc8 [LOG] Getting url: http://i.imgur.com/QPpOFVv.jpg [LOG] Done Getting http://i.imgur.com/QPpOFVv.jpg submission id is: 1f3amu [LOG] Getting url: http://25.media.tumblr.com/tumblr_lstla7vqK71ql5q9zo1_500.jpg Traceback (most recent call last): File "download.py", line 50, in &lt;module&gt; image_file = urllib2.urlopen(submission.url, timeout = 5) File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen return _opener.open(url, data, timeout) File "/usr/lib/python2.7/urllib2.py", line 404, in open response = self._open(req, data) File "/usr/lib/python2.7/urllib2.py", line 422, in _open '_open', req) File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 1214, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib/python2.7/urllib2.py", line 1187, in do_open r = h.getresponse(buffering=True) File "/usr/lib/python2.7/httplib.py", line 1051, in getresponse response.begin() File "/usr/lib/python2.7/httplib.py", line 415, in begin version, status, reason = self._read_status() File "/usr/lib/python2.7/httplib.py", line 371, in _read_status line = self.fp.readline(_MAXLINE + 1) File "/usr/lib/python2.7/socket.py", line 476, in readline data = self._sock.recv(self._rbufsize) socket.timeout: timed out </code></pre>
2
2016-10-12T01:55:47Z
39,989,399
<p>Explicitly catch the timeout exception: <a href="https://docs.python.org/3/library/socket.html#socket.timeout" rel="nofollow">https://docs.python.org/3/library/socket.html#socket.timeout</a></p> <pre><code>try: image_file = urllib2.urlopen(submission.url, timeout = 5) except urllib2.URLError as e: print(e) continue except socket.Timeouterror: print("timed out") # Your timeout handling code here... else: with open('/home/mona/computer_vision/image_retrieval/images/'+category+'/' + datetime.datetime.now().strftime('%y-%m-%d-%s') + submission.url[-5:], 'wb') as output_image: output_image.write(image_file.read()) </code></pre> <p>OP: Thanks! I had these thanks to your suggestion and my problem was solved for Python2.7:</p> <pre><code>except socket.timeout as e: print(e) continue except socket.error as e: print(e) continue </code></pre>
2
2016-10-12T02:02:51Z
[ "python", "exception", "urllib2", "urllib", "continue" ]
Converting the contents of a while loop into a function
39,989,381
<pre><code>#Initialization name=0 count=0 totalpr=0.0 #Load name=input("Enter stock name OR -999 to Quit: ") while name!='-999': count=count+1 shares=int(input("Enter number of shares: ")) pp=float(input("Enter purchase price: ")) sp=float(input("Enter selling price: ")) commission=float(input("Enter commission: ")) #Calculations amount_paid=shares*pp commission_paid_purchase=amount_paid*commission amount_sold=shares*sp commission_paid_sale=amount_sold*commission profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase) totalpr=totalpr+profit_loss #Output print("\nStock Name:", name) print("Amount paid for the stock: $", format(amount_paid, '10,.2f')) print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f')) print("Amount the stock sold for: $", format(amount_sold, '10,.2f')) print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f')) print("Profit (or loss if negative): $", format(profit_loss, '10,.2f')) name=input("\nEnter stock name OR -999 to Quit: ") print("Total Profit is $", format(totalpr, '10,.2f')) def main() load() #to input the values calc() print() </code></pre> <p>As you can see, I don't know how to convert the contents of paragraph "#Calculations" into a function so that it can be called at the bottom. The same goes for "#Load" (I want all the inputs in there somehow, even though there is a while loop in between it). And also for the "#Output" otherwise known as "print()" I would like it to be converted to a function as well. </p> <p>I've got the bottom part down right, but I don't know how to edit my code so that it fits neatly into the form of a function. The code itself is fine, I just need to find a way to convert to functions and then call it. I've got the calling part down, so I'm working backwards in a sense. </p>
0
2016-10-12T02:00:19Z
39,989,573
<p>This is one way to convert inside of while loop to a function and then use the main function to call the function as many times as you like.</p> <p>You can break this code down further to a print function. Just use return statement for that. </p> <pre><code>def calculate(shares,pp,sp,commission,name): totalpr = 0 amount_paid=int(shares)*float(pp) commission_paid_purchase=float(amount_paid*commission) amount_sold=int(shares)*float(sp) commission_paid_sale=float(amount_sold*commission) profit_loss=float(amount_sold - commission_paid_sale) -float(amount_paid + commission_paid_purchase) totalpr=totalpr+profit_loss print("\nStock Name:", name) print("Amount paid for the stock: $", format(amount_paid, '10,.2f')) print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f')) print("Amount the stock sold for: $", format(amount_sold, '10,.2f')) print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f')) print("Profit (or loss if negative): $", format(profit_loss, '10,.2f')) print("Total Profit is $", format(totalpr, '10,.2f')) def main(): name = input("Enter stock:") while name != '-999': calculate(5,1.22,11.33,11.44,name) name = input("Enter stock:") main() </code></pre>
1
2016-10-12T02:29:05Z
[ "python", "function", "python-3.x", "while-loop" ]
Converting the contents of a while loop into a function
39,989,381
<pre><code>#Initialization name=0 count=0 totalpr=0.0 #Load name=input("Enter stock name OR -999 to Quit: ") while name!='-999': count=count+1 shares=int(input("Enter number of shares: ")) pp=float(input("Enter purchase price: ")) sp=float(input("Enter selling price: ")) commission=float(input("Enter commission: ")) #Calculations amount_paid=shares*pp commission_paid_purchase=amount_paid*commission amount_sold=shares*sp commission_paid_sale=amount_sold*commission profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase) totalpr=totalpr+profit_loss #Output print("\nStock Name:", name) print("Amount paid for the stock: $", format(amount_paid, '10,.2f')) print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f')) print("Amount the stock sold for: $", format(amount_sold, '10,.2f')) print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f')) print("Profit (or loss if negative): $", format(profit_loss, '10,.2f')) name=input("\nEnter stock name OR -999 to Quit: ") print("Total Profit is $", format(totalpr, '10,.2f')) def main() load() #to input the values calc() print() </code></pre> <p>As you can see, I don't know how to convert the contents of paragraph "#Calculations" into a function so that it can be called at the bottom. The same goes for "#Load" (I want all the inputs in there somehow, even though there is a while loop in between it). And also for the "#Output" otherwise known as "print()" I would like it to be converted to a function as well. </p> <p>I've got the bottom part down right, but I don't know how to edit my code so that it fits neatly into the form of a function. The code itself is fine, I just need to find a way to convert to functions and then call it. I've got the calling part down, so I'm working backwards in a sense. </p>
0
2016-10-12T02:00:19Z
39,994,563
<p>It doesn't make sense for your few lines of code, as it blows up things unnecessarily, but here you go:</p> <pre><code>def load(): shares=int(input("Enter number of shares: ")) pp=float(input("Enter purchase price: ")) sp=float(input("Enter selling price: ")) commission=float(input("Enter commission: ")) return shares, pp, sp, commission def calc(totalpr): amount_paid=shares*pp commission_paid_purchase=amount_paid*commission amount_sold=shares*sp commission_paid_sale=amount_sold*commission profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase) totalpr+=profit_loss return commission_paid_purchase, amount_paid, amount_sold, commission_paid_sale, profit_loss, totalpr def output(): print("\nStock Name:", name) print("Amount paid for the stock: $", format(amount_paid, '10,.2f')) print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f')) print("Amount the stock sold for: $", format(amount_sold, '10,.2f')) print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f')) print("Profit (or loss if negative): $", format(profit_loss, '10,.2f')) if __name__ == "__main__": #Initialization name=0 count=0 totalpr=0.0 name=input("Enter stock name OR -999 to Quit: ") while name!='-999': count+=1 #Load shares, pp, sp, commission = load() #Calculations commission_paid_purchase, amount_paid, amount_sold, commission_paid_sale, profit_loss, totalpr = calc(totalpr) #Output output() name=input("\nEnter stock name OR -999 to Quit: ") print("Total Profit is $", format(totalpr, '10,.2f')) </code></pre> <p>Note that variables that are defined within the scope of the while loop are automatically visible by functions that a called from within that loop.</p>
0
2016-10-12T09:01:49Z
[ "python", "function", "python-3.x", "while-loop" ]
'int' object is not subscriptable in my code
39,989,384
<p>I'm trying to write a program in Python that will compare two 4-digit numbers, one given by the player and one generated by the computer, and tell the player how many cows and bulls they get - cows being matching numbers in the wrong places and bulls being matching numbers in the right places. I keep getting an <code>'int' object is not subscriptable</code> error every time I try it. I know that means I need to make the int <code>guess</code> a string, but even when I try to do that it gives me the same error in the same place. Any pointers?</p> <pre><code>def how_many_bulls(answer,guess): ''' Returns the number of bulls the guess earns when the secret number is the answer. ''' bulls = 0 if guess[0] == answer[0]: bulls = bulls+1 if guess[1] == answer[1]: bulls = bulls+1 if guess[2] == answer[2]: bulls = bulls+1 if guess[3] == answer[3]: bulls = bulls+1 return bulls </code></pre> <p>Sorry if I've formatted anything wrong - my first time using the site.</p>
2
2016-10-12T02:00:34Z
39,989,467
<p>You can make the guess a list:</p> <pre><code>guess = [1,2,3,4] </code></pre>
1
2016-10-12T02:12:46Z
[ "python" ]
'int' object is not subscriptable in my code
39,989,384
<p>I'm trying to write a program in Python that will compare two 4-digit numbers, one given by the player and one generated by the computer, and tell the player how many cows and bulls they get - cows being matching numbers in the wrong places and bulls being matching numbers in the right places. I keep getting an <code>'int' object is not subscriptable</code> error every time I try it. I know that means I need to make the int <code>guess</code> a string, but even when I try to do that it gives me the same error in the same place. Any pointers?</p> <pre><code>def how_many_bulls(answer,guess): ''' Returns the number of bulls the guess earns when the secret number is the answer. ''' bulls = 0 if guess[0] == answer[0]: bulls = bulls+1 if guess[1] == answer[1]: bulls = bulls+1 if guess[2] == answer[2]: bulls = bulls+1 if guess[3] == answer[3]: bulls = bulls+1 return bulls </code></pre> <p>Sorry if I've formatted anything wrong - my first time using the site.</p>
2
2016-10-12T02:00:34Z
39,989,535
<p>You should convert to string both <code>answer</code> and <code>guess</code>.</p> <p>(Or access their digits in any other way, there are many)</p>
2
2016-10-12T02:23:03Z
[ "python" ]
how to pass the text entered in entry box in tkinter from one function to another?
39,989,385
<p>I m tying to pass the entery box text from one function to another but it gives me error that the variable itself is not defined.Here is my code.</p> <pre><code>from Tkinter import * def mhello(): mtext=ment.get() print mtext def main(): root=Tk() ment=StringVar() root.title('Test') mlabel=Label(root,text='Enter Text').pack() mentry=Entry(root,textvariable=ment).pack() mbutton=Button(root,text='Click Me',command=mhello).pack() if __name__ == '__main__': main() </code></pre> <p>it gives the error as:</p> <pre><code>Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1489, in __call__ return self.func(*args) File "pygui.py", line 3, in mhello mtext=ment.get() NameError: global name 'ment' is not defined </code></pre>
-1
2016-10-12T02:00:44Z
39,989,453
<p>First off you have a variable scope issue, variables defined in functions are local to those functions so <code>ment</code> is defined in <code>main</code> but not in <code>mhello</code>. Either pass the variable in to <code>mhello</code> or make <code>ment</code> a global. So we can pass in the variable like this:</p> <pre><code>def mhello(var): mtext=var.get() print(mtext) </code></pre> <p>Then we need to call this from our button:</p> <pre><code>mbutton=Button(root, text='Click Me', command=lambda: mhello(ment)).pack() </code></pre> <p>And we need to actually call the <code>mainloop</code> for the code to run properly:</p> <pre><code>root.mainloop() </code></pre> <p>Without that no GUI will be run.</p> <p>On a design level I usually create classes to store the variables that are in the same parts of the GUI to avoid needing to pass a lot of parameters around.</p>
0
2016-10-12T02:10:57Z
[ "python", "python-2.7", "tkinter" ]
About Truthiness and the Booleans True and False
39,989,478
<p>My environment is : ubuntu 16.04 &amp; python 2.7.12.</p> <p>I read the documentation and found out that <code>''</code>, <code>()</code>, <code>[]</code>, <code>{}</code>, and <code>None</code> are all considered <code>False</code> by default.</p> <p>But I don't understand what's going on in the examples below:</p> <pre class="lang-none prettyprint-override"><code>Python 2.7.12 (default, Jul 1 2016, 15:12:24) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; a='' &gt;&gt;&gt; a==False False &gt;&gt;&gt; a==True False &gt;&gt;&gt; a=bool(a) &gt;&gt;&gt; a==False True &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; a="abcdefg" &gt;&gt;&gt; a==True False &gt;&gt;&gt; a==False False &gt;&gt;&gt; a=bool(a) &gt;&gt;&gt; a==True True &gt;&gt;&gt; </code></pre> <p>I want get the right result and it appears I must use the <code>bool()</code> function to do so. Is that correct and why?</p>
2
2016-10-12T02:14:22Z
39,989,511
<p>It's not that those values <em>are equal to</em> <code>False</code>, it's that they <em>behave</em> as false when used in a boolean context.</p> <p>It's certainly proper to cast to <code>bool</code> if you absolutely need a value of <code>True</code> or <code>False</code>, but in most cases it's not necessary.</p>
2
2016-10-12T02:18:59Z
[ "python" ]
About Truthiness and the Booleans True and False
39,989,478
<p>My environment is : ubuntu 16.04 &amp; python 2.7.12.</p> <p>I read the documentation and found out that <code>''</code>, <code>()</code>, <code>[]</code>, <code>{}</code>, and <code>None</code> are all considered <code>False</code> by default.</p> <p>But I don't understand what's going on in the examples below:</p> <pre class="lang-none prettyprint-override"><code>Python 2.7.12 (default, Jul 1 2016, 15:12:24) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; a='' &gt;&gt;&gt; a==False False &gt;&gt;&gt; a==True False &gt;&gt;&gt; a=bool(a) &gt;&gt;&gt; a==False True &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; a="abcdefg" &gt;&gt;&gt; a==True False &gt;&gt;&gt; a==False False &gt;&gt;&gt; a=bool(a) &gt;&gt;&gt; a==True True &gt;&gt;&gt; </code></pre> <p>I want get the right result and it appears I must use the <code>bool()</code> function to do so. Is that correct and why?</p>
2
2016-10-12T02:14:22Z
39,989,513
<p>The <a href="https://docs.python.org/2/library/stdtypes.html" rel="nofollow">docs</a> say:</p> <blockquote> <p>Any object can be tested for truth value, for use <strong>in an if or while condition or as operand of the Boolean operations</strong> below.</p> </blockquote> <p>In other words, this works for <code>a = ''</code>:</p> <pre><code>if a: print "this won't print" </code></pre> <p>But <code>a</code> is still not <em>equal to</em> <code>False</code>.</p>
1
2016-10-12T02:19:38Z
[ "python" ]
Django forms security, model form vs forms
39,989,487
<p>I'm learning django little by little I realized that I have some way to make a form, modelforms, forms and basic html with 'action= to view'.</p> <p>If we talk bout security, what is the best option, I asked that because I have create a form to update data un db, do it with modelform it's very easy but I have follow the queryset rules to do it because I did not found a way to update data with a form made by forms, so I have two questions, if there any best way to make what I made in the next code but following forms, instead to do it?.</p> <pre><code>def update_info(request, pk): if request.method == "POST": name = request.POST['name_form'] company = request.POST['company_form'] detail = Data.objects.get(pk=pk) Data.filter(pk=pk).update(name=name, company=company) return HttpResponse('Name: %s Company: %s' % (name,company)) </code></pre> <p>This code works fine but If you guy see there is not a way or maybe I do not know how to clean the form if form is nos post like, something like this.</p> <p><strong>This method work with form or modelform</strong></p> <pre><code>else: form = my_form() </code></pre> <p>Aso the question is, how can I can the form if this is not a form made with model form.</p> <p>and </p> <p>Is there a way to use my form made with .fomrs, to update instead to make it in html ?</p> <p>Because it work but I need to set a new view in the "action" form. Thank you !</p>
0
2016-10-12T02:15:56Z
39,990,379
<p>It will be safer to validate input by forms validation instead of making a direct query. That's also one of the main purpose of django form too. And here's the reference of <a href="https://docs.djangoproject.com/en/1.10/topics/forms/" rel="nofollow">django forms</a>.</p> <p>Back to your code and question I guess the following code can help you.</p> <p>Pick one solution below and put this into your forms.py:</p> <pre><code>from django import forms #sol 1 class MyNewForm(forms.Form): name = forms.CharField(label='name', max_length=100) company = forms.CharField(label='company', max_length=100) #sol 2 class MyNewForm(forms.ModelForm): model = MyModel fields = ["name", "company"] </code></pre> <p>And then edit your views.py:</p> <pre><code># path to your forms.py from .forms import * def update_info(request, pk): if request.method == "POST": form = MyNewForm(request.POST) detail = Data.objects.get(pk=pk) if form.is_valid(): cleaned_data = form.cleaned_data Data.filter(pk=pk).update(name=cleaned_data["name"], company=cleaned_data["company"]) return HttpResponse('Name: %s Company: %s' % (cleaned_data["name"], cleaned_data["company"])) else: return HttpResponse('Form Validation Error!') </code></pre>
0
2016-10-12T04:10:30Z
[ "python", "django", "forms" ]
hash() returning different values on different OSs
39,989,534
<p>When python builtin <code>hash()</code> is just wired cross-platform. I have an app use builtin <code>hash()</code> for <code>'test'</code>. Both systems are 64bit, python 2.7.12</p> <p>windows:</p> <pre><code>&gt;&gt;&gt; hash('test') 1308370872 </code></pre> <p>linux:</p> <pre><code>&gt;&gt;&gt; hash('test') 2314058222102390712 </code></pre> <p>Why is this?</p>
0
2016-10-12T02:22:59Z
40,014,604
<p>There are no guarantees about the value <code>hash</code> returns in Python. It appears that you're using a 32-bit Windows Python (that's a guess), and that you're using a 64-bit python on linux (again, a guess). IIRC (and I haven't checked), The default <code>hash(item)</code> returns the address of <code>item</code> as its hash value.</p> <p>If you want to have values you can compare across operating systems, look at <a href="https://docs.python.org/3.5/library/hashlib.html?highlight=hashlib" rel="nofollow">hashlib</a>.</p>
1
2016-10-13T07:17:00Z
[ "python", "python-2.7", "hash", "python-internals" ]
cx_Freeze - Building exe - Windows 64bit - Invalid Syntex
39,989,546
<p>Trying to build a exe file but am having an error I don't understand. I followed a tutorial so unless it had bad instructions I don't see what is wrong. <a href="https://i.stack.imgur.com/NjGai.png" rel="nofollow">cmd print screen</a></p> <p>-Code-</p> <pre><code>import cx_Freeze executables = [cx_Freeze.Executable('Wedgie la Apple.py')] cx_Freeze.setup( name='Wedgie la Apple' options={'build_exe':{'packages':['pygame'],'incude_files':['apple.png','appleIcon.png','grass.png','intro.png','rock.png','snakeBody.png','snakeHead.png','intro.wav','select.wav','music1.wav','music2.wav','music3.wav','music4.wav','nom_nom_nom1.wav','nom_nom_nom2.wav','nom_nom_nom3.wav','death_3.wav','death_4.wav','death_6.wav']}}, description = 'Wedgie la Apple - Snake Game' executables = executables ) </code></pre>
0
2016-10-12T02:24:56Z
39,993,519
<p>You are missing a <code>,</code>between keywords - like <code>name='Wedgie la Apple',</code></p> <p>Example function:</p> <pre><code>&gt;&gt;&gt; def a(a="abc", b="cef"): ... print(a, b) </code></pre> <p>Wrong:</p> <pre><code>&gt;&gt;&gt; a(a="abcdef" b="feggsef") File "&lt;stdin&gt;", line 1 a(a="abcdef" b="feggsef") ^ SyntaxError: invalid syntax </code></pre> <p>Working:</p> <pre><code>&gt;&gt;&gt; a(a="abcdef", b="feggsef") abcdef feggsef </code></pre>
0
2016-10-12T08:03:51Z
[ "python", "python-3.x", "cx-freeze" ]
Organize a text file and covert it to CSV
39,989,583
<p>I have a text file similar to this:</p> <p>What is the best way of organizing this txt file so that I can convert it to a CSV file later? Ideally, I would like to have a table at the end with a row for each sequence and its measurements (each measurement in a separate column)</p> <p>I am new to python and text editing, any help is appreciated.</p> <pre><code>AlmostGood = GoodTextFile.readlines() AlmostGood ['a score=298 EG2=6.4e-70 E=1.3e-83\n', 's read1067_2d 42 1073 + 1205 TTTTCTAAATTGTAATTTTTATTGGAAAA-CAAA-TATACAACTTGGAAT--GGATTTCCGAGGCAAAATTGTGCCATAAGCAGATTTTAAGTGGCTAAACAA---AGTTTAAA-AGC-AAGTAACAATAAAGAGAAAATGGGTTTCTGGTACAGGACCAGCAGTACAAAATAGTGTACGAGTGACCTGGATAA-TACACCCGTTTCGGCAATAGTGCAATTTAAGT\n', 's read39_complement 38 1007 + 1149 TTTTTTATAGT-TACTTTTTCTTAGAAACTCAAACTA-ACTGGTCGCAGTCCGGTTTTGCG-G--AAAATTGTGACGGTA-TTCATGTTCTTGCCATCATTGT-AG-AATTC\n', '\n', 'a score=294 EG2=9.1e-69 E=3.1e-82\n', 's read62_2d 20 1142 + 1186 AGCAGTGGTATCAATGCAGAGATGATTTTTTAAATTGGATTTTTTGATGGAA---CAAA-TATACAACTTGAA-TG-GATTTT\n', 's read39_complement 14 1098 + 1149 AGCAATCTTGT-AACCCCGATATGGTTTTTTATAGTT-ACTTTTTCTTAGAAACTCAAACTA'] </code></pre>
0
2016-10-12T02:30:16Z
39,989,859
<p>The quickest way would be to use a regular expression. However, as someone new to Python, please don't get overwhelmed.</p> <pre><code>import re matchSequence = [] matchMeasurements = [] for item in AlmostGood: matchSequence.append(re.match([a], item)) matchMeasurements.append(re.match([s], item)) </code></pre> <p>I can't really test this at the moment, but theoretically it should search through each line in your text, which you've parsed, and sort the two types into separate lists based on the first letter. The strings with newlines should be left out entirely. <a href="https://docs.python.org/2/library/re.html" rel="nofollow">Here's the regular expression documentation for Python.</a></p>
0
2016-10-12T03:04:45Z
[ "python", "csv" ]
Reverse of bytes to Hex program to convert Hex to bytes
39,989,595
<p>I am trying to write the reverse of the below program to get the bytes from the HEX value that i have. Finding it hard to do it. Any help?</p> <pre><code>private static String bytesToHex(byte[] bytes) { char[] hexChars = new char [bytes.length *2]; for (int i=0; i&lt; bytes.length; i++) { int v = bytes[i] &amp; 0xFF; hexChars[i*2] = HEX_ARRAY[v &gt;&gt;&gt;4]; hexChars[i*2 + 1] = HEX_ARRAY[v &amp; 0x0F]; } return new String(hexChars); } </code></pre> <p>Consider HEX_ARRAY as char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();</p> <p>I would prefer to do this python but even Java should be ok</p>
0
2016-10-12T02:32:09Z
39,991,515
<p>Thanks for the help everyone. I resolved this by using </p> <pre><code>import binascii </code></pre> <p><code>binascii.hexlify('data')</code></p> <p>For the JAVA code I found the answer here: <a href="https://github.com/EverythingMe/inbloom/blob/master/java/src/main/java/me/everything/inbloom/BinAscii.java" rel="nofollow">https://github.com/EverythingMe/inbloom/blob/master/java/src/main/java/me/everything/inbloom/BinAscii.java</a></p>
0
2016-10-12T06:04:52Z
[ "java", "python", "hex", "byte" ]
Python counting multiple modes in a list
39,989,608
<p>This is a simple function but it is giving me a hard time. I'm trying to calculate the mode in a list, and if there are > 1 modes (with the same frequency), then they need to be displayed. </p> <pre><code>def compute_mode(numbers): mode = 0 count = 0 maxcount = 0 for number in numbers: count = numbers.count(number) if count &gt;= maxcount: maxcount = count mode = number print("Mode: ", mode, "Count: ", maxcount) </code></pre> <p>Function call:</p> <pre><code>print(compute_mode([0,1,3,5,7,3,0])) </code></pre> <p>Output:</p> <pre><code>Mode: 0 Count: 2 Mode: 3 Count: 2 Mode: 3 Count: 2 Mode: 0 Count: 2 </code></pre> <p>I can't seem to make the function not repeat the last two lines. I'm not sure why it is repeating again for 0 and 3.</p> <p>Any ideas?</p>
-1
2016-10-12T02:33:30Z
39,989,643
<p>Its repeating those lines, simply because you have 2 of those numbers in your list.</p> <p>Your function doesn't track if its already seen a number, in order to update a counter for it.</p> <p>To count things, use the appropriately named <code>Counter</code> from the <code>collections</code> module:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; Counter([0,1,3,5,7,3,0]).most_common() [(0, 2), (3, 2), (1, 1), (5, 1), (7, 1)] </code></pre> <p>Or, the other way to do this is to keep track of a number you have already seen, and just update its counter in a dictionary (which is similar to how <code>Counter</code> works), using a <code>defaultdict</code>:</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; d = defaultdict(int) &gt;&gt;&gt; for i in [0,1,3,5,7,3,0]: ... d[i] += 1 ... &gt;&gt;&gt; d defaultdict(&lt;class 'int'&gt;, {0: 2, 1: 1, 3: 2, 5: 1, 7: 1}) &gt;&gt;&gt; for item, count in d.items(): ... print('Mode: {} Count: {}'.format(item, count)) ... Mode: 0 Count: 2 Mode: 1 Count: 1 Mode: 3 Count: 2 Mode: 5 Count: 1 Mode: 7 Count: 1 </code></pre>
2
2016-10-12T02:37:47Z
[ "python", "list" ]
Python counting multiple modes in a list
39,989,608
<p>This is a simple function but it is giving me a hard time. I'm trying to calculate the mode in a list, and if there are > 1 modes (with the same frequency), then they need to be displayed. </p> <pre><code>def compute_mode(numbers): mode = 0 count = 0 maxcount = 0 for number in numbers: count = numbers.count(number) if count &gt;= maxcount: maxcount = count mode = number print("Mode: ", mode, "Count: ", maxcount) </code></pre> <p>Function call:</p> <pre><code>print(compute_mode([0,1,3,5,7,3,0])) </code></pre> <p>Output:</p> <pre><code>Mode: 0 Count: 2 Mode: 3 Count: 2 Mode: 3 Count: 2 Mode: 0 Count: 2 </code></pre> <p>I can't seem to make the function not repeat the last two lines. I'm not sure why it is repeating again for 0 and 3.</p> <p>Any ideas?</p>
-1
2016-10-12T02:33:30Z
39,989,693
<p>The reason you get the modes twice is that your for-loop loops over every element in the list. Therefore, when it encounters the second instance of a previously seen element, it prints it out again.</p> <p>In other news, your function will fail for a different reason - try removing the first <code>0</code> and see what happens.</p> <p>This is how I would fix it:</p> <pre><code>from collections import Counter def compute_mode(numbers): counts = Counter(numbers) maxcount = max(counts.values()) for num,count in counts: if count == maxcount: print(num, count) </code></pre> <p>If you want to do all the heavy lifting yourself:</p> <pre><code>def compute_mode(numbers): counts = {} maxcount = 0 for number in numbers: if number not in counts: counts[number] = 0 counts[number] += 1 if counts[number] &gt; maxcount: maxcount = counts[number] for number, count in counts.items(): if count == maxcount: print(number, count) </code></pre>
2
2016-10-12T02:43:18Z
[ "python", "list" ]
Steps to integrate Python with Android
39,989,612
<p>I need to integrate my python code with my android application. I am new to this type of integration so please tell me all the steps to do so. I am currently creating an appliaction that just tells the geological information about the name of place you entered. My python code takes the place name as input , traverses json and outputs the cordinates and other information. Further I will develope it track a mobile phone through geolocation. Now I have to integrate this with my Android app. Please tell me steps so that I can understand it easily. Thankyou</p>
-1
2016-10-12T02:33:58Z
39,989,651
<p>Have you checked out <a href="http://www.jython.org/archive/21/docs/whatis.html" rel="nofollow">Jython</a>? It generally integrates Python and Java. You could actually do all of this in Java, if you wanted to do that as well.</p>
0
2016-10-12T02:38:19Z
[ "java", "android", "python", "geolocation" ]
Pandas time series resampling
39,989,679
<p>I have a list of voyages with a start and end date and the earnings for that voyage. I want to calculate the monthly earnings, but I am not sure how I can do that using Pandas:</p> <pre><code>'2016-02-28 07:30:00', '2016-04-30 00:00:00', '600000' '2016-05-18 10:30:00', '2016-07-12 02:19:00', '700000' </code></pre> <p>The way I manually do this is calculating how many days of the voyage is in each respective month and multiply by earnings/total length of voyage.</p>
2
2016-10-12T02:41:43Z
39,991,788
<p>You need check how many hours is in each date range - in each row. So use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>DataFrame.apply</code></a> with custom function, where <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.groupby.html" rel="nofollow"><code>groupby</code></a> by <code>months</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html" rel="nofollow"><code>date_range</code></a> and aggreagate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow"><code>size</code></a>.</p> <pre><code>print (df) start end price 0 2016-02-28 07:30:00 2016-04-30 00:00:00 600000 1 2016-05-18 10:30:00 2016-07-12 02:19:00 700000 print (df.dtypes) start datetime64[ns] end datetime64[ns] price int64 dtype: object def f(x): rng = pd.date_range(x.start, x.end, freq='H') return rng.to_series().groupby([rng.month]).size() df1 = df.apply(f, axis=1) print (df1) 2 3 4 5 6 7 0 41.0 744.0 696.0 NaN NaN NaN 1 NaN NaN NaN 326.0 720.0 266.0 </code></pre> <p>Then get <code>price_per_hour</code> by divide column <code>price</code> by <code>sum</code> of all hours:</p> <pre><code>price_per_hour = df.price / df1.sum(axis=1) print (price_per_hour) 0 405.131668 1 533.536585 dtype: float64 </code></pre> <p>And last multiple by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mul.html" rel="nofollow"><code>mul</code></a> all hours in each <code>month</code>:</p> <pre><code>print (df1.mul(price_per_hour, axis=0)) 2 3 4 5 6 \ 0 16610.398379 301417.960837 281971.640783 NaN NaN 1 NaN NaN NaN 173932.926829 384146.341463 7 0 NaN 1 141920.731707 #check sum - it is correctly price print (df1.mul(price_per_hour, axis=0).sum(axis=1)) 0 600000.0 1 700000.0 dtype: float64 </code></pre> <hr> <p>You can also count <code>prices</code> per <code>days</code> - change <code>freq='h'</code> to <code>freq='D'</code>, but I think it is less accurate:</p> <pre><code>def f(x): rng = pd.date_range(x.start, x.end, freq='D') return rng.to_series().groupby([rng.month]).size() df1 = df.apply(f, axis=1) print (df1) 2 3 4 5 6 7 0 2.0 31.0 29.0 NaN NaN NaN 1 NaN NaN NaN 14.0 30.0 11.0 price_per_hour = df.price / df1.sum(axis=1) print (price_per_hour) 0 9677.419355 1 12727.272727 dtype: float64 print (df1.mul(price_per_hour, axis=0)) 2 3 4 5 6 7 0 19354.83871 300000.0 280645.16129 NaN NaN NaN 1 NaN NaN NaN 178181.818182 381818.181818 140000.0 0 600000.0 1 700000.0 dtype: float64 print (df1.mul(price_per_hour, axis=0).sum(axis=1)) 0 600000.0 1 700000.0 dtype: float64 </code></pre> <p>Another solution with reshaping by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a>, groupby and resample <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow"><code>resample</code></a> - also need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.groupby.html" rel="nofollow"><code>groupby</code></a> by <code>months</code> and aggreagate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow"><code>size</code></a>:</p> <pre><code>df['count'] = df.index df1 = pd.melt(df, id_vars=['price', 'count'], value_name='dates') print (df1) price count variable dates 0 600000 0 start 2016-02-28 07:30:00 1 700000 1 start 2016-05-18 10:30:00 2 600000 0 end 2016-04-30 00:00:00 3 700000 1 end 2016-07-12 02:19:00 df2 = df1.set_index('dates').groupby('count').resample('D').size() print (df2) count dates 0 2016-02-28 1 2016-02-29 0 2016-03-01 0 2016-03-02 0 2016-03-03 0 2016-03-04 0 2016-03-05 0 2016-03-06 0 2016-03-07 0 2016-03-08 0 2016-03-09 0 2016-03-10 0 2016-03-11 0 2016-03-12 0 ... ... </code></pre> <pre><code>print (df2.index.get_level_values('dates').month) [2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7] df3 = df2.groupby([df2.index.get_level_values('count'), df2.index.get_level_values('dates').month]).size().unstack() print (df3) 2 3 4 5 6 7 count 0 2.0 31.0 30.0 NaN NaN NaN 1 NaN NaN NaN 14.0 30.0 12.0 price_per_hour = df.price / df3.sum(axis=1) print (price_per_hour) 0 9523.809524 1 12500.000000 dtype: float64 print (df3.mul(price_per_hour, axis=0)) 2 3 4 5 6 \ count 0 19047.619048 295238.095238 285714.285714 NaN NaN 1 NaN NaN NaN 175000.0 375000.0 7 count 0 NaN 1 150000.0 print (df3.mul(price_per_hour, axis=0).sum(axis=1)) count 0 600000.0 1 700000.0 dtype: float64 </code></pre>
2
2016-10-12T06:24:08Z
[ "python", "pandas", "time-series", "date-range" ]
How can I get the google search snippets using Python?
39,989,680
<p>I am now trying the python module google which only return the url from the search result. And I want to have the snippets as information as well, how could I do that?(Since the google web search API is deprecated)</p>
1
2016-10-12T02:41:49Z
39,989,752
<p>I think you're going to have to extract your own snippets by opening and reading the url in the search result.</p>
0
2016-10-12T02:50:13Z
[ "python" ]
from Flask import Flask ImportError: No module named Flask
39,989,696
<p>I am following the tutorial <a href="https://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-python-flask-and-mysql--cms-22972" rel="nofollow">here</a>.</p> <p>My file looks like this:</p> <pre><code>from flask import Flask app = Flask(__name__) @app.route("/") def main(): return "Welcome!" if __name__ == "__main__": app.run() </code></pre> <p>I run <code>python app.py</code> and get the following:</p> <pre><code>Traceback (most recent call last): File "app.py", line 1, in &lt;module&gt; from flask import Flask ImportError: No module named Flask </code></pre> <p>I do have flask installed. I was thinking it's a $PATH issue. I don't really know where to begin as far as troubleshooting goes.</p> <p><code>which flask</code> gives me: <code>/usr/local/bin/flask</code></p> <p><code>which python</code> gives me: <code>/usr/bin/python</code></p> <p>Any help is much appreciated, there are other similar issues out there but those solutions have not helped. Happy to answer any questions. Thank you.</p> <p><strong>Answers to questions:</strong></p> <p><strong>Q.</strong> <em>Which Python version?</em> <strong>A.</strong> Python 2.7.10 </p> <p><strong>Q.</strong> <em>How did you install Flask?</em> <strong>A.</strong> pip install flask</p>
-1
2016-10-12T02:43:33Z
39,990,311
<p>I needed to do the following and the tutorial didn't really go into depth on how to install flask properly.</p> <p>You must do the following in full. <a href="http://flask.pocoo.org/docs/0.11/installation/#" rel="nofollow">http://flask.pocoo.org/docs/0.11/installation/#</a></p> <p>Thanks for the responses.</p>
0
2016-10-12T04:02:18Z
[ "python", "flask", "filepath" ]
Python2.7: Why isn't python reading any of my paths with open(filename)?
39,989,717
<p>So in "Learn python the hard way", at exercise 15, you learn how to make a program open a file. Here's my code, and I typed <code>python ex15.py ex15.txt</code> at the command prompt. I haven't had any other problems with the program so far:</p> <pre><code>from sys import argv script, filename = argv txt = open(ex15.txt) print "Here's your file: %r" % ex15.txt print txt.read() print "type the filename again: " again = raw_input("&gt; ") again2 = open(again) print again2.read() </code></pre> <p>and here's the error message:</p> <pre><code>Traceback (most recent call last): File "ex15.py", line 5, in &lt;module&gt; txt = open("ex15.txt") IOError: [Errno 2] No such file or directory: 'ex15.txt' </code></pre> <p>I immediately suspected the problem was the file wasn't in the right place (the ex15.txt) and put it in the <code>Python27</code> folder in Windows. Then after doing some internet research of the problem, I tried putting it in the working directory of cmd, and also the <code>scripts</code> folder in <code>Python27</code>, and also tried including the full pathname for the original file location (Documents), and I always get the same error message.</p> <p>What am I (or my computer) missing here? the path to the script is <code>C:\Python27</code>, the directory of the prompt is <code>C:\Users\Customer</code>, and I have already stated all the locations of the text file, it is still in every one of those folders. The python program is indeed included in PATH. </p>
-1
2016-10-12T02:45:51Z
39,989,748
<p>The file needs to be in the same folder you are running your script</p> <p>If you are running at<code>C:/myscript.py</code>, you file needs to be at <code>C:/</code> as well. </p> <p>Ex: </p> <pre><code>&gt;&gt; cd C: &gt;&gt; dir ex15.txt myscript.py &gt;&gt; python myscript.py ex15.txt Here's your file: 'ex15.txt' Something that is in your text file type the filename again: &gt; ex15.txt Something that is in your text file </code></pre> <p>Also, your code seems to be wrong. You need to use "ex15.txt", not ex15.txt without quotes. Otherwise it will be interpreted as a variable, not as a string.</p> <p>See the code below:</p> <pre><code>from sys import argv script, filename = argv txt = open("ex15.txt") print "Here's your file: %r" % "ex15.txt" print txt.read() print "type the filename again: " again = raw_input("&gt; ") again2 = open(again) print again2.read() </code></pre>
1
2016-10-12T02:49:53Z
[ "python", "path" ]
NoneType error when opening file
39,989,776
<p>So I've been trying to figure out why it's giving me this error. If I put this:</p> <pre><code>def open_file(): fp = open("ABC.txt") return fp file = open_file() count = 1 for line in file: if count == 9: line9 = line if count == 43: line43 = line #blahblahblah more programming </code></pre> <p>This works, but this gives me NoneType object is not iterable:</p> <pre><code>def open_file(): while True: file = input("Enter a file name: ") try: open(file) break except FileNotFoundError: print("Error. Please try again.") print() file = open_file() count = 1 for line in file: #here is where I get the error if count == 9: line9 = line if count == 43: line43 = line </code></pre> <p>I think it's just some silly mistake but I can't seem to find it. Thanks for your time!</p>
0
2016-10-12T02:51:42Z
39,989,798
<p>Your <code>open_file</code> function has no <code>return</code> statement, so it returns <code>None</code>. You should try something like</p> <pre><code>def open_file(): while True: file = input("Enter a file name: ") try: return open(file) except FileNotFoundError: print("Error. Please try again.") print() </code></pre>
2
2016-10-12T02:55:13Z
[ "python", "nonetype" ]
Sort and group a list of dictionaries
39,989,777
<p>How can I sort and group this list of dictionaries into a nested dictionary which I want to return via an API as JSON.</p> <p>Source Data (list of permissions):</p> <pre><code>[{ 'can_create': True, 'can_read': True, 'module_name': 'ModuleOne', 'module_id': 1, 'role_id': 1, 'end_point_id': 1, 'can_update': True, 'end_point_name': 'entity', 'can_delete': True, }, { 'can_create': True, 'can_read': True, 'module_name': 'ModuleTwo', 'module_id': 2, 'role_id': 1, 'end_point_id': 4, 'can_update': True, 'end_point_name': 'financial-outlay', 'can_delete': True, },{ 'can_create': True, 'can_read': True, 'module_name': 'ModuleOne', 'module_id': 1, 'role_id': 1, 'end_point_id': 2, 'can_update': True, 'end_point_name': 'management-type', 'can_delete': True, }, { 'can_create': True, 'can_read': True, 'module_name': 'ModuleOne', 'module_id': 1, 'role_id': 1, 'end_point_id': 3, 'can_update': True, 'end_point_name': 'ownership-type', 'can_delete': False, }, { 'can_create': True, 'can_read': True, 'module_name': 'ModuleTwo', 'module_id': 2, 'role_id': 1, 'end_point_id': 5, 'can_update': True, 'end_point_name': 'exposure', 'can_delete': True, }] </code></pre> <p>I want to transform that into a nested dicitonary object for return with an API as JSON. Here's the expected output:</p> <pre><code>{ "role_id": 1, "modules": [{ "module_id": 1, "module_name": "ModuleOne", "permissions": [{ "end_point_id": 1, "end_point_name": "entity", "can_create": False, "can_read": True, "can_write": True, "can_delete": True }, { "end_point_id": 2, "end_point_name": "management-type", "can_create": False, "can_read": True, "can_write": True, "can_delete": True }, { "end_point_id": 3, "end_point_name": "ownership-type", "can_create": False, "can_read": True, "can_write": True, "can_delete": True }, ] }, { "module_id": 2, "module_name": "ModuleTwo", "permissions": [{ "end_point_id": 4, "end_point_name": "financial-outlay", "can_create": False, "can_read": True, "can_write": True, "can_delete": True }, { "end_point_id": 5, "end_point_name": "exposure", "can_create": False, "can_read": True, "can_write": True, "can_delete": True }, ] }, ] } </code></pre> <p>It looked trivial until I spent more time that I would expect trying to bend my mind around it. I've attempted so many options with non of them working. Here's the last attempt.</p> <pre><code># Get user role user_roles = get_user_roles() # List of roles e.g. [{'role_id':1, role_name: 'role_one'}, {'role_id':2, role_name: 'role_two'}] for role in user_roles: role_id = role['role_id'] role_name = role['role_name'] # Fetch Role Permissions role_permissions = get_role_permissions(role_id) # List of permissions as seen above sorted_role_permissions = sorted(role_permissions, key=itemgetter('module_id')) # sort dictionaries in list by 'module_id' modules_list = [] permissions_list = [] previous_module_id = 0 is_first_loop = True for role_permission in sorted_role_permissions: module_id = role_permission['module_id'] module_name = role_permission['module_name'] end_point_id = role_permission['end_point_id'] end_point_name = role_permission['end_point_name'] if is_first_loop: print(0) is_first_loop = False previous_module_id = module_id print('end_point_name 0 {}'.format(end_point_name)) permissions = {'end_point_id': end_point_id, 'end_point_name': end_point_name, 'can_create': role_permission['can_create'], 'can_read': role_permission['can_read'], 'can_update': role_permission['can_update'], 'can_delete': role_permission['can_delete'] } permissions_list.append(permissions) if len(sorted_role_permissions) == 1: # If there is only one permission in the role, end the loop modules_dict = {'module_id': module_id, 'module_name': module_name, 'permissions': permissions_list} modules_list.append(modules_dict) break else: if module_id == previous_module_id: # As long as the current module_id and the previous_module_id are the same, add to the same list print(1) permissions = {'end_point_id': end_point_id, 'end_point_name': end_point_name, 'can_create': role_permission['can_create'], 'can_read': role_permission['can_read'], 'can_update': role_permission['can_update'], 'can_delete': role_permission['can_delete'] } permissions_list.append(permissions) else: print(2) modules_dict = {'module_id': module_id, 'module_name': module_name, 'permissions': permissions_list} modules_list.append(modules_dict) permissions_list = [] permissions = {'end_point_id': end_point_id, 'end_point_name': end_point_name, 'can_create': role_permission['can_create'], 'can_read': role_permission['can_read'], 'can_update': role_permission['can_update'], 'can_delete': role_permission['can_delete'] } permissions_list.append(permissions) previous_module_id = module_id if modules_list: roles.append({'role_id': role_id, 'role_name': role_name, 'modules': modules_list}) </code></pre>
3
2016-10-12T02:52:13Z
39,990,811
<p>TADA!</p> <pre><code>from itertools import groupby def group_by_remove(permissions, id_key, groups_key, name_key=None): """ @type permissions: C{list} of C{dict} of C{str} to C{object} @param id_key: A string that represents the name of the id key, like "role_id" or "module_id" @param groups_key: A string that represents the name of the key of the groups like "modules" or "permissions" @param name_key: A string that represents the name of the key of names like "module_name" (can also be None for no names' key) """ result = [] permissions_key = lambda permission: permission[id_key] # Must sort for groupby to work properly sorted_permissions = sorted(permissions, key=permissions_key) for key, groups in groupby(sorted_permissions, permissions_key): key_result = {} groups = list(groups) key_result[id_key] = key if name_key is not None: key_result[name_key] = groups[0][name_key] key_result[groups_key] = [{k: v for k, v in group.iteritems() if k != id_key and (name_key is None or k != name_key)} for group in groups] result.append(key_result) return result def change_format(initial): """ @type initial: C{list} @rtype: C{dict} of C{str} to C{list} of C{dict} of C{str} to C{object} """ roles_group = group_by_remove(initial, "role_id", "modules")[0] roles_group["modules"] = group_by_remove(roles_group["modules"], "module_id", "permissions", "module_name") return roles_group change_format(role_permissions) </code></pre> <p>Enjoy :)</p>
2
2016-10-12T04:58:28Z
[ "python", "list", "python-3.x", "dictionary" ]
Sort and group a list of dictionaries
39,989,777
<p>How can I sort and group this list of dictionaries into a nested dictionary which I want to return via an API as JSON.</p> <p>Source Data (list of permissions):</p> <pre><code>[{ 'can_create': True, 'can_read': True, 'module_name': 'ModuleOne', 'module_id': 1, 'role_id': 1, 'end_point_id': 1, 'can_update': True, 'end_point_name': 'entity', 'can_delete': True, }, { 'can_create': True, 'can_read': True, 'module_name': 'ModuleTwo', 'module_id': 2, 'role_id': 1, 'end_point_id': 4, 'can_update': True, 'end_point_name': 'financial-outlay', 'can_delete': True, },{ 'can_create': True, 'can_read': True, 'module_name': 'ModuleOne', 'module_id': 1, 'role_id': 1, 'end_point_id': 2, 'can_update': True, 'end_point_name': 'management-type', 'can_delete': True, }, { 'can_create': True, 'can_read': True, 'module_name': 'ModuleOne', 'module_id': 1, 'role_id': 1, 'end_point_id': 3, 'can_update': True, 'end_point_name': 'ownership-type', 'can_delete': False, }, { 'can_create': True, 'can_read': True, 'module_name': 'ModuleTwo', 'module_id': 2, 'role_id': 1, 'end_point_id': 5, 'can_update': True, 'end_point_name': 'exposure', 'can_delete': True, }] </code></pre> <p>I want to transform that into a nested dicitonary object for return with an API as JSON. Here's the expected output:</p> <pre><code>{ "role_id": 1, "modules": [{ "module_id": 1, "module_name": "ModuleOne", "permissions": [{ "end_point_id": 1, "end_point_name": "entity", "can_create": False, "can_read": True, "can_write": True, "can_delete": True }, { "end_point_id": 2, "end_point_name": "management-type", "can_create": False, "can_read": True, "can_write": True, "can_delete": True }, { "end_point_id": 3, "end_point_name": "ownership-type", "can_create": False, "can_read": True, "can_write": True, "can_delete": True }, ] }, { "module_id": 2, "module_name": "ModuleTwo", "permissions": [{ "end_point_id": 4, "end_point_name": "financial-outlay", "can_create": False, "can_read": True, "can_write": True, "can_delete": True }, { "end_point_id": 5, "end_point_name": "exposure", "can_create": False, "can_read": True, "can_write": True, "can_delete": True }, ] }, ] } </code></pre> <p>It looked trivial until I spent more time that I would expect trying to bend my mind around it. I've attempted so many options with non of them working. Here's the last attempt.</p> <pre><code># Get user role user_roles = get_user_roles() # List of roles e.g. [{'role_id':1, role_name: 'role_one'}, {'role_id':2, role_name: 'role_two'}] for role in user_roles: role_id = role['role_id'] role_name = role['role_name'] # Fetch Role Permissions role_permissions = get_role_permissions(role_id) # List of permissions as seen above sorted_role_permissions = sorted(role_permissions, key=itemgetter('module_id')) # sort dictionaries in list by 'module_id' modules_list = [] permissions_list = [] previous_module_id = 0 is_first_loop = True for role_permission in sorted_role_permissions: module_id = role_permission['module_id'] module_name = role_permission['module_name'] end_point_id = role_permission['end_point_id'] end_point_name = role_permission['end_point_name'] if is_first_loop: print(0) is_first_loop = False previous_module_id = module_id print('end_point_name 0 {}'.format(end_point_name)) permissions = {'end_point_id': end_point_id, 'end_point_name': end_point_name, 'can_create': role_permission['can_create'], 'can_read': role_permission['can_read'], 'can_update': role_permission['can_update'], 'can_delete': role_permission['can_delete'] } permissions_list.append(permissions) if len(sorted_role_permissions) == 1: # If there is only one permission in the role, end the loop modules_dict = {'module_id': module_id, 'module_name': module_name, 'permissions': permissions_list} modules_list.append(modules_dict) break else: if module_id == previous_module_id: # As long as the current module_id and the previous_module_id are the same, add to the same list print(1) permissions = {'end_point_id': end_point_id, 'end_point_name': end_point_name, 'can_create': role_permission['can_create'], 'can_read': role_permission['can_read'], 'can_update': role_permission['can_update'], 'can_delete': role_permission['can_delete'] } permissions_list.append(permissions) else: print(2) modules_dict = {'module_id': module_id, 'module_name': module_name, 'permissions': permissions_list} modules_list.append(modules_dict) permissions_list = [] permissions = {'end_point_id': end_point_id, 'end_point_name': end_point_name, 'can_create': role_permission['can_create'], 'can_read': role_permission['can_read'], 'can_update': role_permission['can_update'], 'can_delete': role_permission['can_delete'] } permissions_list.append(permissions) previous_module_id = module_id if modules_list: roles.append({'role_id': role_id, 'role_name': role_name, 'modules': modules_list}) </code></pre>
3
2016-10-12T02:52:13Z
39,991,951
<p>PyFunctional is pretty good at list manipulation.</p> <pre><code>from pprint import pprint from functional import seq input = [...] # taken from your example output =( seq(input) # convert regular python list to Sequence object # group by role_id .map(lambda e: (e.pop('role_id'), e)).group_by_key() # start building role dict .map(lambda role_modules: { "role_id": role_modules[0], "modules": seq(role_modules[1]) # group by (module_id, module_name) .map(lambda e: ( (e.pop('module_id'), e.pop('module_name')), e) ).group_by_key() # start building module/permissions dict .map(lambda module_permissions: { "module_id": module_permissions[0][0], "module_name": module_permissions[0][1], "permissions": module_permissions[1] }) # sort by module_id, convert Seq obj to regular list .sorted(key=lambda m:m['module_id']).to_list() }) # sort by role_id, convert Seq obj to regular list .sorted(key=lambda r:r['role_id']).to_list() ) pprint(output) </code></pre> <p><strong>RESULT</strong></p> <pre><code>[{'modules': [{'module_id': 1, 'module_name': 'ModuleOne', 'permissions': [{'can_create': True, 'can_delete': True, 'can_read': True, 'can_update': True, 'end_point_id': 1, 'end_point_name': 'entity'}, {'can_create': True, 'can_delete': True, 'can_read': True, 'can_update': True, 'end_point_id': 2, 'end_point_name': 'management-type'}, {'can_create': True, 'can_delete': False, 'can_read': True, 'can_update': True, 'end_point_id': 3, 'end_point_name': 'ownership-type'}]}, {'module_id': 2, 'module_name': 'ModuleTwo', 'permissions': [{'can_create': True, 'can_delete': True, 'can_read': True, 'can_update': True, 'end_point_id': 4, 'end_point_name': 'financial-outlay'}, {'can_create': True, 'can_delete': True, 'can_read': True, 'can_update': True, 'end_point_id': 5, 'end_point_name': 'exposure'}]}], 'role_id': 1}] </code></pre>
1
2016-10-12T06:35:32Z
[ "python", "list", "python-3.x", "dictionary" ]
I don't know how to through one queryset type to manytomany relations
39,989,787
<p>I want to use Django to write a blog system.But the question is I can't get tags queryset from articles queryset.</p> <p>models:</p> <pre><code>class Article(models.Model): ... tags = models.ManyToManyField(Tags,related_name='tags') author = models.ForeignKey( User,on_delete=models.CASCADE,to_field="username", ) ... class Tags(models.Model): tag_name = models.CharField(max_length=20) def __str__(self): return self.tag_name class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,to_field='username',) ... </code></pre> <p>views:</p> <pre><code>.... def get_context_data(self,**kwargs): user=self.request.user object_list=Article.objects.all().filter(author=self.request.user.username).order_by(F('created').desc())[:100] kwargs['tags']=??? # I want to get a tags queryset related to object_list return super(UserIndexView,self).get_context_data(**kwargs) </code></pre>
-1
2016-10-12T02:52:51Z
39,990,118
<p>You are using <code>related_name</code> wrong. <code>related_name</code> is the name for the reversed relationship. It should be:</p> <pre><code>tags = models.ManyToManyField(Tags,related_name='articles') </code></pre> <p>So the simple answer to your question is use:</p> <pre><code>[article.tags.all() for article in object_list] </code></pre> <p>But this is not efficient since it issues 100 separate queries to the DB. A better way to do this would be:</p> <pre><code>Tags.objects.filter(articles__author=self.request.user.username) </code></pre> <p>(Note the use of the <code>related_name</code> property)</p> <p>But I've omitted the interesting part of only getting tags related to the 100 newest articles of the user. To do this, I think the best way is to first get the date of the 100th article, and then filter accordingly:</p> <pre><code>ordered_articles = Article.objects.filter(author=self.request.user.username).order_by(F('created').desc() try: date_limit = ordered_articles[100].created return Tags.objects.filter(articles__author=self.request.user.username, articles__created__lt=date_limit) except IndexError: return Tags.objects.filter(articles__author=self.request.user.username) </code></pre> <p>(Answer not tested, sorry)</p> <p>Also, call your model <code>Tag</code> instead of <code>Tags</code>.</p>
0
2016-10-12T03:37:52Z
[ "python", "django", "many-to-many", "django-queryset" ]
Not matching the output with the correct output
39,989,837
<p><a href="https://i.stack.imgur.com/AjdiD.png" rel="nofollow"><img src="https://i.stack.imgur.com/AjdiD.png" alt="enter image description here"></a> </p> <pre><code>def interpret(result : [None]) -&gt; str: s = '' s = s + 'Start state = ' + result[0] +'\n ' for x in result[1:-1]: s += ' Input = ' + x[0]+ '; new possible states = ' + str(sorted(x[1])) + '\n ' s = s + ' Input = ' + x[0]+ '; new possible states = ' + str(sorted(result[-1][1])) + '\n' s = s + 'Stop state(s) = ' + str(sorted(result[-1][1])) return s evaluated: Start state = start Input = 1; new possible states = ['start'] Input = 0; new possible states = ['near', 'start'] Input = 1; new possible states = ['end', 'start'] Input = 1; new possible states = ['start'] Input = 0; new possible states = ['near', 'start'] Input = 0; new possible states = ['end', 'start'] Stop state(s) = ['end', 'start'] == Start state = start Input = 1; new possible states = ['start'] Input = 0; new possible states = ['near', 'start'] Input = 1; new possible states = ['end', 'start'] Input = 1; new possible states = ['start'] Input = 0; new possible states = ['near', 'start'] Input = 1; new possible states = ['end', 'start'] Stop state(s) = ['end', 'start'] </code></pre> <p>31 *Error: Failed <code>ndfa.interpret(i) == "Start state = start\n Input = 1; new possible states = ['start']\n Input = 0; new possible states = ['near', 'start']\n Input = 1; new possible states = ['end', 'start']\n Input = 1; new possible states = ['start']\n Input = 0; new possible states = ['near', 'start']\n Input = 1; new possible states = ['end', 'start']\nStop state(s) = ['end', 'start']\n"</code></p> <p>The function takes a list and returns a string. I need to return the string in the correct format. It seems to me that the output I get is the same as the correct output, but it give me an error. Can someone tell me why it is not correct? Many thanks</p> <p>by the way the input is <code>['start', ('1', {'start'}), ('0', {'start', 'near'}), ('1', {'end', 'start'}), ('1', {'start'}), ('0', {'start', 'near'}), ('1', {'end', 'start'})]</code></p> <p>and the correct output is '"Start state = start\n Input = 1; new possible states = ['start']\n Input = 0; new possible states = ['near', 'start']\n Input = 1; new possible states = ['end', 'start']\n Input = 1; new possible states = ['start']\n Input = 0; new possible states = ['near', 'start']\n Input = 1; new possible states = ['end', 'start']\nStop state(s) = ['end', 'start']\n"`</p> <p>I added a picture to show the result I got.</p>
-2
2016-10-12T02:59:42Z
39,992,159
<p>I've changed the 6th line of the function from <code>x[0]</code> to <code>result[-1][0]</code>, which seems to work:</p> <pre><code>def interpret(result : [None]) -&gt; str: s = '' s = s + 'Start state = ' + result[0] +'\n ' for x in result[1:-1]: s += ' Input = ' + x[0]+ '; new possible states = ' + str(sorted(x[1])) + '\n ' s += ' Input = ' + result[-1][0] + '; new possible states = ' + str(sorted(result[-1][1])) + '\n' s += 'Stop state(s) = ' + str(sorted(result[-1][1])) return s </code></pre>
0
2016-10-12T06:48:47Z
[ "python" ]
TypeError: 'NoneType' object is not iterable when trying to check for a None value
39,989,880
<p>This is the error I receive:</p> <pre class="lang-none prettyprint-override"><code>line 16, in main definition, data = get_name () TypeError: 'NoneType' object is not iterable </code></pre> <p>I check for <code>None</code> type here:</p> <pre><code>definition = get_word (name, gender) if definition is None: print ("\"" + non_lower + "\"", "not found.") else: return definition </code></pre> <p>Here is the code which will return <code>None</code> if the search term is not found:</p> <pre><code>if x and new_line is not None: return new_line, x </code></pre> <p>I am returning 2 values but it is returning one value and when I try to check that value for a <code>None</code> I get the error. If there anyway to check the variable for <code>None</code> correctly so if nothing is returned I can present a message?</p>
0
2016-10-12T03:06:50Z
39,991,520
<p>You have a double negative in the part that is returning <code>None</code> for the check later. Maybe try this:</p> <pre><code>if x and new_line: return new_line, x else: return None, None </code></pre> <p>Then when checking for <code>None</code> don't actually check for <code>None</code>, check the variable is something other than <code>None</code>, then catch <code>None</code> with the else statement?</p> <pre><code>if definition: return definition else: print ("\"" + non_lower + "\"", "not found.") </code></pre>
0
2016-10-12T06:05:09Z
[ "python", "typeerror", "nonetype" ]
How to set selenium to process the next url when the current one loads more than 30 seconds?
39,989,894
<p>I want to know what to put into exception condition. I'm currently using the pass statement, but I'm not sure whether it does exactly what I want it to do. The reason why I want to implement this is because some webpages takes more than 30 seconds to load completely, like: taobao.com. My code is as followed:</p> <pre><code>from selenium import webdriver from time import sleep from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import WebDriverException profile = webdriver.FirefoxProfile() profile.add_extension(extension = '/Users/wayne/Desktop/fourthparty/extension/fourthparty.xpi') driver = webdriver.Firefox(profile) def scan(cutoff): with open('top-1m.csv', 'r') as f: for num, url in enumerate(f): if (num == 500): return url = url.split(',')[1] driver.get('http://www.' + url) sleep(30) try: driver.set_page_load_timeout(30) except TimeoutException: pass if __name__ == "__main__": scan(500) </code></pre>
0
2016-10-12T03:08:36Z
39,990,433
<p>You do the <code>set_page_load_timeout</code> once, usually shortly after instantiating the driver. You should then wrap the <code>driver.get</code> in the try except, like so:</p> <pre><code>from __future__ import print_function from selenium import webdriver from time import sleep from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import TimeoutException profile = webdriver.FirefoxProfile() profile.add_extension(extension = '/Users/wayne/Desktop/fourthparty/extension/fourthparty.xpi') driver = webdriver.Firefox(profile) driver.set_page_load_timeout(30) def scan(cutoff): with open('top-1m.csv', 'r') as f: for num, url in enumerate(f): if (num == 500): return url = url.split(',')[1] try: driver.get('http://www.' + url) except TimeoutException: print("Caught and handled slow page timeout exception") # Do something here I guess? if __name__ == "__main__": scan(500) </code></pre>
0
2016-10-12T04:15:21Z
[ "python", "selenium" ]
How to set selenium to process the next url when the current one loads more than 30 seconds?
39,989,894
<p>I want to know what to put into exception condition. I'm currently using the pass statement, but I'm not sure whether it does exactly what I want it to do. The reason why I want to implement this is because some webpages takes more than 30 seconds to load completely, like: taobao.com. My code is as followed:</p> <pre><code>from selenium import webdriver from time import sleep from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import WebDriverException profile = webdriver.FirefoxProfile() profile.add_extension(extension = '/Users/wayne/Desktop/fourthparty/extension/fourthparty.xpi') driver = webdriver.Firefox(profile) def scan(cutoff): with open('top-1m.csv', 'r') as f: for num, url in enumerate(f): if (num == 500): return url = url.split(',')[1] driver.get('http://www.' + url) sleep(30) try: driver.set_page_load_timeout(30) except TimeoutException: pass if __name__ == "__main__": scan(500) </code></pre>
0
2016-10-12T03:08:36Z
40,032,310
<p>Here is the new program that gets the next url if the current one has loaded for more than 30 seconds. It may not look as a typical Python program since I'm used to Java. from selenium import webdriver from time import sleep from selenium.common.exceptions import TimeoutException import csv</p> <pre><code>profile = webdriver.FirefoxProfile() profile.add_extension(extension = '/Users/wayne/Desktop/fourthparty-master/extension/fourthparty-jetpack.1.13.2.xpi') driver = webdriver.Firefox(profile) with open('top-1m.csv', 'r') as f: reader = csv.reader(f) fList = list(reader) def crawl(cutoff): for i in range(0, cutoff): try: driver.set_page_load_timeout(30) getURL(i) except: pass def getURL(num): url = 'http://www.' + fList[num][1] driver.get(url) sleep(30) if __name__ == "__main__": crawl(10) </code></pre>
0
2016-10-13T22:54:06Z
[ "python", "selenium" ]
Cannot find text by xpath (scrapy)
39,990,035
<p>I try to use xpath to get the date from the example listed below. </p> <pre><code>&lt;node&gt; &lt;table&gt; &lt;td&gt; &lt;font style="font-size:14px"&gt;http://www.aaa.com&lt;/font&gt; &amp;nbsp;&amp;nbsp;2016-10-11 17:14:11 &lt;/td&gt; &lt;/table&gt; &lt;/node&gt; </code></pre> <p>I used code looks like: </p> <pre><code>response.xpath('/node/table/td/text()[2]').extract() </code></pre> <p>However it does not work. I expect it will return u'[&nbsp;&nbsp;2016-10-11 17:14:11], but it return []. Can anyone help me?</p>
0
2016-10-12T03:27:20Z
39,990,364
<p>you can try following xpath</p> <pre><code>response.xpath('/node/table/td/font/following-sibling::text()[1]').extract() </code></pre>
0
2016-10-12T04:09:11Z
[ "python", "html", "xpath", "scrapy" ]
While-loop: UnboundLocalError: local variable referenced before assignment
39,990,133
<p>I'm using python 3.5.</p> <p>So I'm trying to create a function that takes x and y as positive float input, and then computes and returns R = x - N * y, where N is the largest integer, so that x > N * y.</p> <p>I made this function:</p> <pre><code>def floatme(x,y): N = 1 while x &lt;= N * y: R = x - N * y N = N+1 return R </code></pre> <p>but then I receive the following error, when running my function:</p> <p>UnboundLocalError: local variable 'R' referenced before assignment</p> <p>I searched around and found that this happens when an assigned variable in the function, is already assigned outside of it. But this is not the case for my function, so I do not understand why Python is complaining?</p>
0
2016-10-12T03:39:26Z
39,990,145
<p><code>R</code> is defined inside the <code>while</code> loop. If the condition of the <code>while</code> loop is not true initially, its body never executes and <code>R</code> is never defined. Then it is an error to try to <code>return R</code>.</p> <p>To solve the problem, initialize <code>R</code> to something before entering the loop.</p> <p>If not entering the loop is an error condition, i.e. the caller should not be passing in values that cause the problem to begin with, then catch the <code>UnboundLocalError</code> using a <code>try</code>/<code>except</code> structure and raise a more appropriate exception (such as <code>ValueError</code>).</p>
2
2016-10-12T03:41:31Z
[ "python", "python-3.x" ]
Python internal frame
39,990,151
<p>Is there any tkinter widget or window manager to realize internal frame (something like <a href="http://www.herongyang.com/Swing/JInternalFrame-Test.jpg" rel="nofollow">java internal frame</a>)? Have done some search but couldn't see any discussion on python support of internal frame. </p>
0
2016-10-12T03:41:54Z
39,998,402
<p>No, there is nothing pre-built, but tkinter has all of the fundamental building blocks to implement it. The embedded windows are just frames, and you can place them in a containing frame with <code>place</code>. You can add your own border, and add mouse bindings to allow the user to move the windows around.</p> <p>For what it's worth, usability experts long ago decided this type of UI isn't very user friendly.</p>
0
2016-10-12T12:16:34Z
[ "python", "tkinter", "tk" ]
Sorting strings with numbers in Python
39,990,260
<p>I have this string: </p> <pre><code>string = '9x3420aAbD8' </code></pre> <p>How can I turn string into:</p> <pre><code>'023489ADabx' </code></pre> <p>What function would I use?</p>
2
2016-10-12T03:55:40Z
39,990,302
<p>You can just use the built-in function <a href="https://docs.python.org/3.5/library/functions.html#sorted" rel="nofollow"><code>sorted</code></a> to sort the string lexographically. It takes in an iterable, sorts each element, then returns a sorted list. Per the documentation:</p> <blockquote> <p><code>sorted(iterable[, key][, reverse])</code></p> <p>Return a new sorted list from the items in <em>iterable</em>.</p> </blockquote> <p>You can apply that like so:</p> <pre><code>&gt;&gt;&gt; ''.join(sorted(string)) '023489ADabx' </code></pre> <p>Since <code>sorted</code> returns a list, like so:</p> <pre><code>&gt;&gt;&gt; sorted(string) ['0', '2', '3', '4', '8', '9', 'A', 'D', 'a', 'b', 'x'] </code></pre> <p>Just join them together to create the desired string.</p>
3
2016-10-12T04:00:15Z
[ "python", "string", "sorting" ]
Sorting strings with numbers in Python
39,990,260
<p>I have this string: </p> <pre><code>string = '9x3420aAbD8' </code></pre> <p>How can I turn string into:</p> <pre><code>'023489ADabx' </code></pre> <p>What function would I use?</p>
2
2016-10-12T03:55:40Z
39,990,314
<p>You can use the <code>sorted()</code> function to sort the string, but this will return a list</p> <pre><code>sorted(string) ['0', '2', '3', '4', '8', '9', 'A', 'D', 'a', 'b', 'x'] </code></pre> <p>to turn this back into a string you just have to join it, which is commonly done using <code>''.join()</code></p> <p>So, all together:</p> <pre><code>sorted_string = ''.join(sorted(string)) </code></pre>
1
2016-10-12T04:02:43Z
[ "python", "string", "sorting" ]
Too high latency while trying to manipulate sound arrays using sounddevice in python
39,990,274
<p>Few days ago, I have installed <a href="http://python-sounddevice.readthedocs.io/en/0.3.5/" rel="nofollow">a sounddevice</a> library in Python 2.7.5. I'm trying to make a sound array and add some effects to it immediately after I push a key on my MIDI controller. But I get a huge delay of 0.1 to 0.2 second which makes my code useless:</p> <pre><code>import numpy as np import sounddevice as sd import time import math #we're making a sound array with a 5 seconds length noisy sound and playing it: duration=5 framerate = 44100 array=0.02*np.random.uniform(-1, 1, framerate*duration) sd.play(array, framerate) t=time.time() while(True): signal=raw_input("push ENTER to hear a beep") start_iter=int(framerate*(time.time()-t)) end_iter=min(start_iter+framerate/4, len(array)) #we're trying to change our data array and play a beep signal of 0.25 second after each ENTER press instantly for i in range(start_iter, end_iter): array[i]=0.05*math.sin(440*2*math.pi*i/44100.) if end_iter==len(array): break #safe exit of a process after 5 seconds has passed </code></pre> <p>To keep it simple, my sound array is just a noisy sound and my effect consists of a 440Hz beep. I used raw_input() here (type "input()" in Python 3.x) instead of MIDI inputs which could be possible using Pygame library. My code works but each time we press ENTER we will hear a short delay before beep signal. Is it possible to eliminate it? If not, any other libraries allowing to play a sound stream with no delays live?</p>
0
2016-10-12T03:57:16Z
40,031,816
<p>You can specify the desired latency with <a href="http://python-sounddevice.readthedocs.io/en/latest/#sounddevice.default.latency" rel="nofollow">sounddevice.default.latency</a>. Note however, that this is a <em>suggested</em> latency, the actual latency may be different, depending on the hardware and probably also on the host API. You can get an estimate of the actual latency with <a href="http://python-sounddevice.readthedocs.io/en/latest/#sounddevice.Stream.latency" rel="nofollow">sounddevice.Stream.latency</a>.</p> <p>By default, the <code>sounddevice</code> module uses PortAudio's <em>high</em> latency setting in the hope to provide more robust behavior. You can switch it to PortAudio's <em>low</em> setting, or you can try whatever numeric value (in seconds) you want.</p> <pre><code>import sounddevice as sd sd.default.latency = 'low' </code></pre> <p>Alternatively, you can of course also use the <code>latency</code> argument of <code>play()</code> etc.</p> <p>If you want to have more control over the time, you might want to write your own custom callback function. There you can use the <code>time</code> argument, and outside of the callback function you can use <a href="http://python-sounddevice.readthedocs.io/en/latest/#sounddevice.Stream.time" rel="nofollow">sounddevice.Stream.time</a>.</p> <p>You can also try to start a stream without using the <code>callback</code> argument and then use <a href="http://python-sounddevice.readthedocs.io/en/latest/#sounddevice.Stream.write" rel="nofollow">sounddevice.Stream.write()</a> on it. I don't know what that will do to the latency, but it might be worth a try.</p> <p>Regarding other libraries, since you seem to be using PyGame already, you might also use it for the audio output. It might or might not have a different latency.</p> <p>BTW, I don't know if your code is thread-safe since you are manipulating the array while the callback gives the memory addresses to PortAudio. It's probably not a good idea to implement it like this.</p>
0
2016-10-13T22:06:21Z
[ "python", "numpy", "low-latency", "python-sounddevice" ]
Create custom date range, 22 hours a day python
39,990,287
<p>I'm working with pandas and want to create a month-long custom date range where the week starts on Sunday night at 6pm and ends Friday afternoon at 4pm. And each day has 22 hours, so for example Sunday at 6pm to Monday at 4pm, Monday 6pm to Tuesday 4pm, etc. </p> <p>I tried <code>day_range = pd.date_range(datetime(2016,9,12,18),datetime.now(),freq='H')</code> but that always gives me in 24 hours.</p> <p>Any suggestions?</p>
4
2016-10-12T03:58:17Z
39,990,804
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#custom-business-hour" rel="nofollow"><code>Custom Business Hour</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html" rel="nofollow"><code>date_range</code></a>:</p> <pre><code>cbh = pd.offsets.CustomBusinessHour(start='06:00', end='16:00', weekmask='Mon Tue Wed Thu Fri Sat') print (cbh) &lt;CustomBusinessHour: CBH=06:00-16:00&gt; day_range = pd.date_range(pd.datetime(2016,9,12,18),pd.datetime.now(),freq=cbh) print (day_range) DatetimeIndex(['2016-09-13 06:00:00', '2016-09-13 07:00:00', '2016-09-13 08:00:00', '2016-09-13 09:00:00', '2016-09-13 10:00:00', '2016-09-13 11:00:00', '2016-09-13 12:00:00', '2016-09-13 13:00:00', '2016-09-13 14:00:00', '2016-09-13 15:00:00', ... '2016-10-11 08:00:00', '2016-10-11 09:00:00', '2016-10-11 10:00:00', '2016-10-11 11:00:00', '2016-10-11 12:00:00', '2016-10-11 13:00:00', '2016-10-11 14:00:00', '2016-10-11 15:00:00', '2016-10-12 06:00:00', '2016-10-12 07:00:00'], dtype='datetime64[ns]', length=252, freq='CBH') </code></pre> <p>Test - it omit <code>Sunday</code>:</p> <pre><code>day_range = pd.date_range(pd.datetime(2016,9,12,18),pd.datetime.now(),freq=cbh)[45:] print (day_range) DatetimeIndex(['2016-09-17 11:00:00', '2016-09-17 12:00:00', '2016-09-17 13:00:00', '2016-09-17 14:00:00', '2016-09-17 15:00:00', '2016-09-19 06:00:00', '2016-09-19 07:00:00', '2016-09-19 08:00:00', '2016-09-19 09:00:00', '2016-09-19 10:00:00', ... '2016-10-11 08:00:00', '2016-10-11 09:00:00', '2016-10-11 10:00:00', '2016-10-11 11:00:00', '2016-10-11 12:00:00', '2016-10-11 13:00:00', '2016-10-11 14:00:00', '2016-10-11 15:00:00', '2016-10-12 06:00:00', '2016-10-12 07:00:00'], dtype='datetime64[ns]', length=207, freq='CBH') </code></pre>
2
2016-10-12T04:58:09Z
[ "python", "datetime", "pandas", "date-range", "hour" ]
Where is my below python code failing?
39,990,370
<p>if the function call is like: backwardsPrime(9900, 10000) then output should be [9923, 9931, 9941, 9967]. Backwards Read Primes are primes that when read backwards in base 10 (from right to left) are a different prime. It is one of the kata in Codewars and on submitting the below solution, I am getting the following error: </p> <p>Traceback: in File "./frameworks/python/cw-2.py", line 28, in assert_equals expect(actual == expected, message, allow_raise) File "./frameworks/python/cw-2.py", line 18, in expect raise AssertException(message) cw-2.AssertException: [1095047, 1095209, 1095319] should equal [1095047, 1095209, 1095319, 1095403]</p> <pre><code>import math def isPrime(num): #flag = True rt = math.floor(math.sqrt(num)) for i in range(2,int(rt)+1): if num % i == 0: return False else: return True def Reverse_Integer(Number): Reverse = 0 while(Number &gt; 0): Reminder = Number %10 Reverse = (Reverse *10) + Reminder Number = Number //10 return Reverse def backwardsPrime(start, stop): s = list() for i in range(start,stop): if i&gt;9 and i != Reverse_Integer(i): if isPrime(i) and isPrime(Reverse_Integer(i)): s.append(i) else: continue return s </code></pre> <p>The Codewars have their own test functions. Sample test case below:</p> <p>a = [9923, 9931, 9941, 9967]</p> <p>test.assert_equals(backwardsPrime(9900, 10000), a) </p>
0
2016-10-12T04:09:44Z
39,990,466
<p>Looks like your code passes the test when run manually. Maybe they range to scan over is set wrong on the test causing it to miss the last one?</p> <pre><code> backwardsPrime(1095000, 1095405) [1095047, 1095209, 1095319, 1095403] </code></pre> <p>e.g. the second parameter is set to <code>1095400</code> or something.</p>
0
2016-10-12T04:20:02Z
[ "python", "primes" ]
Python select data return boolean true-false and DELETE value true
39,990,459
<p><strong>I made a program transaction.and if error,it should report position error. NOW I want to select value TRUE and DELETE value TRUE</strong></p> <pre><code>#!/usr/bin/python import mysql.connector conn = mysql.connector.connect(host="lll",user="ppp",passwd="ppp",db="ppp") cursor = conn.cursor() cursor.execute("SELECT(case when user1 = '1' THEN 'true' ELSE 'false' END) AS IsEmtpy from dt") print(cursor.fetchall()) try: if true: cursor.execute("DELETE FROM dt WHERE user1='1'") print "DELETE SUCESS" else: print "DELETE ERROR" conn.commit() except Exception as e: conn.rollback() conn.close() </code></pre> <p>result : </p> <pre><code>File "./splinsert.py", line 13 if true: ^ IndentationError: expected an indented block </code></pre>
0
2016-10-12T04:18:55Z
39,990,877
<p>This error is related to inconsistent indentation. Python relies on indentation to determine when "code blocks" start and stop. <a href="http://www.diveintopython.net/getting_to_know_python/indenting_code.html" rel="nofollow">Take a look at this for more details</a>.</p> <p>Try something like this:</p> <pre><code>#!/usr/bin/python import mysql.connector conn = mysql.connector.connect(host="lll",user="ppp",passwd="ppp",db="ppp") cursor = conn.cursor() cursor.execute("SELECT(case when user1 = '1' THEN 'true' ELSE 'false' END) AS IsEmtpy from dt") print(cursor.fetchall()) try: if True: cursor.execute("DELETE FROM dt WHERE user1='1'") print "DELETE SUCESS" else: print "DELETE ERROR" conn.commit() except Exception as e: conn.rollback() conn.close() </code></pre>
2
2016-10-12T05:06:17Z
[ "python", "mysql" ]
Recover Binary Tree
39,990,483
<p>For <a href="https://leetcode.com/problems/recover-binary-search-tree/" rel="nofollow" title="this">this</a> question on leet code, this code is passing all the test cases. </p> <pre><code>class Solution(object): def recoverTree(self, root): self.first = None self.second = None self.prev = TreeNode(float('-inf')) self.traverse(root) temp = self.first.val self.first.val = self.second.val self.second.val = temp def traverse(self, root): if not root: return self.traverse(root.left) if not self.first and self.prev.val &gt;= root.val: self.first = self.prev if self.first and self.prev.val &gt;= root.val: self.second = root self.prev = root self.traverse(root.right) </code></pre> <p>I have a question about one part of this code.</p> <pre><code>if not self.first and self.prev.val &gt;= root.val: self.first = self.prev if self.first and self.prev.val &gt;= root.val: self.second = root </code></pre> <p>In this snippet, wont the second condition always be true after the first one has been set. So, you coud write it as:</p> <pre><code>def not self.first and self.prev.val &gt;= root.val: self.first = self.prev self.second = root </code></pre> <p>But if I try this, I will not pass the test cases. Why is it the case? It seem like if we accept the condition for first if statement, and assign self.first, condition for second if statement will always be true. But in reality this seems not to be the case. Can someone please explain whats happening here?</p>
0
2016-10-12T04:22:14Z
39,990,584
<p>The code is different because you still want to run <code>self.second = root</code>. You want to run this line whether <code>self.first</code> was <code>true</code> or <code>false</code> <em>before</em> you started playing with it.</p> <p>Likely there is a test in which <code>self.first</code> is <code>true</code> and the expected outcome is that <code>self.second == root</code>.</p>
0
2016-10-12T04:33:43Z
[ "python", "if-statement", "recursion", "binary-search-tree", "traversal" ]
Remake for-loop to numpy broadcast
39,990,603
<p>I'm trying to code LSB steganography method via numpy arrays. I got code which makes the bool index mask, wich will give those bits of red channel, which need to xor with 1.</p> <pre><code>import numpy as np from scipy.misc import imread import matplotlib.pyplot as plt message = 'Hello, World!' message_bits = np.array(map(bool, map(int, (''.join(map('{:b}'.format, bytearray(message)))))), dtype=np.bool) img = imread('screenshot.png') xor_mask = np.zeros_like(img, dtype=np.bool) ind = 0 for j, line in enumerate(xor_mask): for i, column in enumerate(line): if ind &lt; len(message_bits): xor_mask[j, i, 0] = message_bits[ind] ind += 1 else: break else: continue break img[xor_mask] ^= 1 </code></pre> <p>Is there more compact way to construct the xor_mask? Maybe through numpy broadcast</p> <p>UPD: Reduced my for-loop to this:</p> <pre><code>for j, line in enumerate(xor_mask): if ind &lt; len(message_bits): xor_mask[j, :, 0] = message_bits[ind] ind += len(xor_mask[j]) else: break </code></pre>
0
2016-10-12T04:36:08Z
39,990,747
<p>If you pad <code>message_bits</code> to have as many elements as pixels in <code>xor_mask</code> then it gets simple:</p> <pre><code>xor_mask = np.zeros_like(img, dtype=np.bool) xor_mask[:, :, 0] = np.reshape(message_bits, xor_mask.shape[:2]) </code></pre> <p>Another way, without padding:</p> <pre><code>xor_mask[:, :, 0].flat[:len(message_bits)] = message_bits </code></pre>
1
2016-10-12T04:52:13Z
[ "python", "numpy", "optimization", "scipy", "steganography" ]
Function not calling properly
39,990,604
<pre><code>def main(): def load(): name=0 count=0 totalpr=0 name=input("Enter stock name OR -999 to Quit: ") while name != '-999': count=count+1 shares=int(input("Enter number of shares: ")) pp=float(input("Enter purchase price: ")) sp=float(input("Enter selling price: ")) commission=float(input("Enter commission: ")) name = input("Enter stock name OR -999 to Quit: ") def calc(): amount_paid=shares*pp commission_paid_purchase=amount_paid*commission amount_sold=shares*sp commission_paid_sale=amount_sold*commission profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase) totalpr=totalpr+profit_loss def print(): print("\nStock Name:", name) print("Amount paid for the stock: $", format(amount_paid, '10,.2f')) print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f')) print("Amount the stock sold for: $", format(amount_sold, '10,.2f')) print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f')) print("Profit (or loss if negative): $", format(profit_loss, '10,.2f')) print("Total Profit is $", format(totalpr, '10,.2f')) return main() load() #to input the values calc() print() </code></pre> <p>I'm not sure what I'm doing wrong: </p> <p>Should I be putting in variable names into <code>def load():</code>, <code>def calc():</code> and <code>def print():</code>? </p> <p>As I run it now, it says <code>"load"</code> is not defined. How would I go about defining <code>load</code>? And for that matter, if I didn't define <code>def calc():</code> and <code>def print():</code> how do I define those? </p> <p>I do properly call them at the end of the code, in the order that I'd like to call them -- <code>load</code>, <code>calc</code>, and then <code>print</code>. </p> <p>Is my "<code>return main()</code>" the right thing to do? I don't know, I Just want this code to run properly without error that's all. I'm under the impression that I'm just missing a few things. Any help would be appreciated. </p>
-2
2016-10-12T04:36:11Z
39,990,636
<p>yikes.<br> your first mistake: calling a function in another function. Maybe you meant to do </p> <pre><code>class Main: def load(self): #do a thing </code></pre> <p>then you'd have to do </p> <pre><code>main = Main() main.load() </code></pre> <p>your second mistake was defining a new a print() function that uses print functions, as one already exists. Rename it, as that will cause a huge error</p>
0
2016-10-12T04:40:15Z
[ "python", "function", "python-3.x", "calling-convention" ]
Function not calling properly
39,990,604
<pre><code>def main(): def load(): name=0 count=0 totalpr=0 name=input("Enter stock name OR -999 to Quit: ") while name != '-999': count=count+1 shares=int(input("Enter number of shares: ")) pp=float(input("Enter purchase price: ")) sp=float(input("Enter selling price: ")) commission=float(input("Enter commission: ")) name = input("Enter stock name OR -999 to Quit: ") def calc(): amount_paid=shares*pp commission_paid_purchase=amount_paid*commission amount_sold=shares*sp commission_paid_sale=amount_sold*commission profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase) totalpr=totalpr+profit_loss def print(): print("\nStock Name:", name) print("Amount paid for the stock: $", format(amount_paid, '10,.2f')) print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f')) print("Amount the stock sold for: $", format(amount_sold, '10,.2f')) print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f')) print("Profit (or loss if negative): $", format(profit_loss, '10,.2f')) print("Total Profit is $", format(totalpr, '10,.2f')) return main() load() #to input the values calc() print() </code></pre> <p>I'm not sure what I'm doing wrong: </p> <p>Should I be putting in variable names into <code>def load():</code>, <code>def calc():</code> and <code>def print():</code>? </p> <p>As I run it now, it says <code>"load"</code> is not defined. How would I go about defining <code>load</code>? And for that matter, if I didn't define <code>def calc():</code> and <code>def print():</code> how do I define those? </p> <p>I do properly call them at the end of the code, in the order that I'd like to call them -- <code>load</code>, <code>calc</code>, and then <code>print</code>. </p> <p>Is my "<code>return main()</code>" the right thing to do? I don't know, I Just want this code to run properly without error that's all. I'm under the impression that I'm just missing a few things. Any help would be appreciated. </p>
-2
2016-10-12T04:36:11Z
39,990,637
<p>You are defining <code>load()</code> inside the scope of <code>main()</code>. This means you cannot use the function outside of <code>main()</code>.</p> <p>The easy solution is that you should put your function defines for load, calc, and print outside of the definition of <code>main()</code> (btw, call it something else like <code>print_stock info</code>, print is already a function!) </p> <p>You also do not need to <code>return main()</code>. I am unsure what you are trying to do, but it is not necessary at all.</p>
1
2016-10-12T04:40:52Z
[ "python", "function", "python-3.x", "calling-convention" ]
Function not calling properly
39,990,604
<pre><code>def main(): def load(): name=0 count=0 totalpr=0 name=input("Enter stock name OR -999 to Quit: ") while name != '-999': count=count+1 shares=int(input("Enter number of shares: ")) pp=float(input("Enter purchase price: ")) sp=float(input("Enter selling price: ")) commission=float(input("Enter commission: ")) name = input("Enter stock name OR -999 to Quit: ") def calc(): amount_paid=shares*pp commission_paid_purchase=amount_paid*commission amount_sold=shares*sp commission_paid_sale=amount_sold*commission profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase) totalpr=totalpr+profit_loss def print(): print("\nStock Name:", name) print("Amount paid for the stock: $", format(amount_paid, '10,.2f')) print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f')) print("Amount the stock sold for: $", format(amount_sold, '10,.2f')) print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f')) print("Profit (or loss if negative): $", format(profit_loss, '10,.2f')) print("Total Profit is $", format(totalpr, '10,.2f')) return main() load() #to input the values calc() print() </code></pre> <p>I'm not sure what I'm doing wrong: </p> <p>Should I be putting in variable names into <code>def load():</code>, <code>def calc():</code> and <code>def print():</code>? </p> <p>As I run it now, it says <code>"load"</code> is not defined. How would I go about defining <code>load</code>? And for that matter, if I didn't define <code>def calc():</code> and <code>def print():</code> how do I define those? </p> <p>I do properly call them at the end of the code, in the order that I'd like to call them -- <code>load</code>, <code>calc</code>, and then <code>print</code>. </p> <p>Is my "<code>return main()</code>" the right thing to do? I don't know, I Just want this code to run properly without error that's all. I'm under the impression that I'm just missing a few things. Any help would be appreciated. </p>
-2
2016-10-12T04:36:11Z
39,991,017
<p>This is a minimal working example to illustrate how one can solve what you are trying to do.</p> <pre><code># helper for interpreting input import ast #: initial starting values thing, count, cost, total = 'Nothing', 0, 0, 0 # define all functions at module indentation def get_user_input(): global thing, count, cost # write to the GLOBAL names thing, count and cost thing = input('What have you?') # ask for a string count = ast.literal_eval(input('How much do you have?')) # ask for a string and interpret it: "3.2" =&gt; float cost = ast.literal_eval(input('How much does each cost?')) def compute(): global total # write to global name total total = count * cost # can read from global names def pretty_print(): # not named print! we still need print to print! print("You have", count, thing) print("At", cost, "each, that makes", total, "in total") # call functions at module indentation get_user_input() # ducks, 3, 42 compute() pretty_print() # You have 3 ducks # At 42 each, that makes 126 in total </code></pre> <p>One thing to warn you about: working with global variables is generally a bad idea. For a small script it's fine, but you've already messed up the basics - globals are tricky, so avoid them whenever possible. If you just want to run these commands, do not write them as functions, execute them directly. Basically, leave away the <code>def ...</code> and <code>global ...</code> lines and put everything on the same indentation, then remove the last three lines.</p> <p>If you really want to store and print multiple things, you need to use containers. Just assigning to a value in a loop, e.g. <code>thing = input('What have you?')</code>, will leave it at the last value entered. Instead, you need a container like a <code>list</code>. You can then <code>append</code> additional values to it.</p> <pre><code>container = [] # [] is a list literal for _ in range(3): # non-infinite loop next_thing = ast.literal_eval(input('Place your order...\n')) container.append(next_thing) print("You ordered", container) </code></pre>
0
2016-10-12T05:20:31Z
[ "python", "function", "python-3.x", "calling-convention" ]
Function not calling properly
39,990,604
<pre><code>def main(): def load(): name=0 count=0 totalpr=0 name=input("Enter stock name OR -999 to Quit: ") while name != '-999': count=count+1 shares=int(input("Enter number of shares: ")) pp=float(input("Enter purchase price: ")) sp=float(input("Enter selling price: ")) commission=float(input("Enter commission: ")) name = input("Enter stock name OR -999 to Quit: ") def calc(): amount_paid=shares*pp commission_paid_purchase=amount_paid*commission amount_sold=shares*sp commission_paid_sale=amount_sold*commission profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase) totalpr=totalpr+profit_loss def print(): print("\nStock Name:", name) print("Amount paid for the stock: $", format(amount_paid, '10,.2f')) print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f')) print("Amount the stock sold for: $", format(amount_sold, '10,.2f')) print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f')) print("Profit (or loss if negative): $", format(profit_loss, '10,.2f')) print("Total Profit is $", format(totalpr, '10,.2f')) return main() load() #to input the values calc() print() </code></pre> <p>I'm not sure what I'm doing wrong: </p> <p>Should I be putting in variable names into <code>def load():</code>, <code>def calc():</code> and <code>def print():</code>? </p> <p>As I run it now, it says <code>"load"</code> is not defined. How would I go about defining <code>load</code>? And for that matter, if I didn't define <code>def calc():</code> and <code>def print():</code> how do I define those? </p> <p>I do properly call them at the end of the code, in the order that I'd like to call them -- <code>load</code>, <code>calc</code>, and then <code>print</code>. </p> <p>Is my "<code>return main()</code>" the right thing to do? I don't know, I Just want this code to run properly without error that's all. I'm under the impression that I'm just missing a few things. Any help would be appreciated. </p>
-2
2016-10-12T04:36:11Z
40,010,852
<pre><code>def load(): global name global count global shares global pp global sp global commission name=input("Enter stock name OR -999 to Quit: ") count =0 while name != '-999': count=count+1 shares=int(input("Enter number of shares: ")) pp=float(input("Enter purchase price: ")) sp=float(input("Enter selling price: ")) commission=float(input("Enter commission: ")) calc() display() name=input("\nEnter stock name OR -999 to Quit: ") def calc(): global amount_paid global amount_sold global profit_loss global commission_paid_sale global commission_paid_purchase global totalpr totalpr=0 amount_paid=shares*pp commission_paid_purchase=amount_paid*commission amount_sold=shares*sp commission_paid_sale=amount_sold*commission profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase) totalpr=totalpr+profit_loss def display(): print("\nStock Name:", name) print("Amount paid for the stock: $", format(amount_paid, '10,.2f')) print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f')) print("Amount the stock sold for: $", format(amount_sold, '10,.2f')) print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f')) print("Profit (or loss if negative): $", format(profit_loss, '10,.2f')) def main(): load() main() print("\nTotal Profit is $", format(totalpr, '10,.2f')) </code></pre>
0
2016-10-13T01:27:49Z
[ "python", "function", "python-3.x", "calling-convention" ]
Regex match (\w+) to capture single words delimited by ||| - Python
39,990,657
<p>I am trying to match if there's singe word followed by <code>\s|||\s</code> and then another single word followed by <code>\s|||\s</code> so I'm using this regex:</p> <pre><code>single_word_regex = r'(\w+)+\s\|\|\|\s(\w+)\s\|\|\|\s.*' </code></pre> <p>And when I tried to match this string, the regex matching hangs or take minutes (possibly going into some sort of "deep loop")</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; import time &gt;&gt;&gt; single_word_regex = r'(\w+)+\s\|\|\|\s(\w+)\s\|\|\|\s.*' &gt;&gt;&gt; x = u'amornratchatchawansawangwong ||| amornratchatchawansawangwong . ||| 0.594819 0.5 0.594819 0.25 ||| 0-0 0-1 ||| 1 1 1 ||| |||' &gt;&gt;&gt; z = u'amor 我 ||| amor . i ||| 0.594819 0.0585231 0.594819 0.0489472 ||| 0-0 0-1 1-2 ||| 2 2 2 ||| |||' &gt;&gt;&gt; y = u'amor ||| amor ||| 0.396546 0.0833347 0.29741 0.08 ||| 0-0 0-1 ||| 3 4 2 ||| |||' &gt;&gt;&gt; re.match(single_word_regex, z, re.U) &gt;&gt;&gt; re.match(single_word_regex, y, re.U) &lt;_sre.SRE_Match object at 0x105b879c0&gt; &gt;&gt;&gt; start = time.time(); re.match(single_word_regex, y, re.U); print time.time() - start 9.60826873779e-05 &gt;&gt;&gt; start = time.time(); re.match(single_word_regex, x, re.U); print time.time() - start # It hangs... </code></pre> <p><strong>Why is it taking that long?</strong></p> <p>Is there a better/simpler regex to capture this condition<code>len(x.split(' ||| ')[0].split()) == 1 == len(x.split(' ||| ').split())</code>?</p>
3
2016-10-12T04:42:41Z
39,992,585
<p>Note that by itself, a <code>r'(\w+)+'</code> pattern will not cause the <a href="http://www.regular-expressions.info/catastrophic.html" rel="nofollow">catastrophic backtracking</a>, it will only be "evil" inside a longer expression and especially when it is placed next to the start of the pattern since in case subsequent subpatterns fail the engine backtracks to this one, and as the 1+ quantifier inside is again quantified with <code>+</code>, that creates a huge amount of possible variations to try before failing. You may have a look at <a href="https://regex101.com/r/6ZOhPi/1" rel="nofollow">your regex demo</a> and click the <em>regex debugger</em> on the left to see example regex engine behavior.</p> <p>The current regex can be written as </p> <pre><code>r'^(\w+)\s\|{3}\s(\w+)\s\|{3}\s(.*)' </code></pre> <p>See the <a href="https://regex101.com/r/8amfjD/2" rel="nofollow">regex demo</a> where there will be a match if you remove space and <code>.</code> in the second field.</p> <p><strong>Details</strong>:</p> <ul> <li><code>^</code> - start of string (not necessary with <code>re.match</code>)</li> <li><code>(\w+)</code> - (Group 1) 1+ letters/digits/underscores</li> <li><code>\s</code> - a whitespace</li> <li><code>\|{3}</code> - 3 pipe symbols</li> <li><code>\s(\w+)\s\|{3}\s</code> - see above (<code>(\w+)</code> creates Group 2)</li> <li><code>(.*)</code> - (Group 3) any 0+ characters other than linebreak characters.</li> </ul>
3
2016-10-12T07:13:03Z
[ "python", "regex", "loops", "hang" ]
In Django, how do I get a file path for an uploaded file when uploading?
39,990,659
<p>I am trying to add some validation for user uploaded files. This requires running through a custom script I made called "sumpin", which only takes a filepath as a variable and sends back JSON data that will verify. Everything inside my script is working independently, putting it together where the error occurs.<br></p> <p>Since this is file validation, I decided to expand my file_extension validator that was already working. </p> <p>models.py</p> <pre><code>from allauthdemo.fileuploadapp.slic3rcheck import sumpin def user_directory_path_files(instance, filename): return os.path.join('uploads', str(instance.objectid), filename) def validate_file_extension(value): ext = os.path.splitext(value.name)[1] valid_extensions = ['.stl','.STL'] if not ext in valid_extensions: raise ValidationError(u'Please upload a .stl file type only') data = sumpin(value.path) print (data) class subfiles(models.Model): STL = models.FileField(_('STL Upload'), upload_to=user_directory_path_files, validators=[validate_file_extension]) </code></pre> <p>The error that I get is that the path (value.path) is not valid.<br><br> This is the incorrect path because the upload_to tag must change this at a later point. This may be obvious, but I also need to have the file at the filepath location when my script is called. So essentially my questions are...</p> <ol> <li>How can pass the "upload_to" path into my validator to run through my custom script?</li> <li>Is there a better method to deal with uploaded files, like in the main class with a "save" or "clean" function? </li> </ol>
1
2016-10-12T04:42:52Z
40,048,519
<p>I've found my own answer, but I'll post it here in case someone runs across this issue in the future.</p> <p>I was incorrect, a validator wouldn't actually download the file. I need to use a file upload handler, which is shown below.</p> <pre><code>import os from django.core.files.storage import default_storage from allauthdemo.fileuploadapp.slic3rcheck import sumpin def handle_uploaded_file(f): with open(default_storage.path('tmp/'+f.name), 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) data = sumpin(default_storage.path('tmp/'+f.name)) os.remove(default_storage.path('tmp/'+f.name)) return data </code></pre> <p>then I call this inside my views.py.</p> <pre><code>from allauthdemo.fileuploadapp.uploadhandler import handle_uploaded_file @login_required def STLupload(request): # Handle file upload if request.method == 'POST': formA = ObjectUp(request.POST, request.FILES) if formA is_valid(): data = handle_uploaded_file(request.FILES['STL']) </code></pre> <p>This will return whatever I called to return within handle_upload_file, which worked perfect for my issues. Hopefully someone will find this useful the future.</p>
0
2016-10-14T17:07:47Z
[ "python", "django", "validation" ]
Hierarchical Clustering using Python on Correlation Coefficient
39,990,706
<p>I have the data in 50 by 50 Matrix that represents the 50 Journals with their correlation. Now, I am trying to plot the graph showing on which clusters those 50 Journals fall based on the data. </p> <p>1) I prefer to use complete-linkage or Ward's method to do the clusters. 2) I am stuck at where to begin the clustering as the documentation in scikit-learn is too technical for me 3) Could you please help me to give a kick-start? </p> <p>Thank you very much in advance...</p> <p>My all data falls between 0 and 1 as it is correlation coefficients.</p> <p>Example of Data Sample (50*50):</p> <p>data = [[ 1. 0.49319094 0.58838586 ..., 0.11433441 0.6450184 0.60842821]</p> <p>[ 0.49319094 1. 0.39311674 ..., -0.00795401 0.42944597 0.68855177]</p> <p>[ 0.58838586 0.39311674 1. ..., 0.39785574 0.864322 0.68910632]</p> <p>..., </p> <p>[ 0.11433441 -0.00795401 0.39785574 ..., 1. 0.38623474 0.34228516]</p> <p>[ 0.6450184 0.42944597 0.864322 ..., 0.38623474 1. 0.65408474]</p> <p>[ 0.60842821 0.68855177 0.68910632 ..., 0.34228516 0.65408474 1. ]]</p>
-2
2016-10-12T04:47:27Z
39,991,533
<p>Python expects <em>distances</em>, i.e. low values are better.</p> <p>Ward is designed for squared Euclidean, so while it may work with correlation, the support from theory may be weak. Complete linkage will be supported.</p> <p>What about negative correlations - how do you want to treat them?</p> <p>I believe I know three popular transformations:</p> <ol> <li><code>1 - p**2</code> (depending on the implementation, this may be a good choice with Ward because of the square)</li> <li><code>1 - abs(p)</code></li> <li><code>1 - p</code> (This will treat negative correlations as bad!)</li> </ol> <p>Make sure to set your metric to <code>precomputed</code>. And get used to reading sklearn documentation. It is one of the least technical you will find, so you better become more technical yourself then.</p>
0
2016-10-12T06:05:59Z
[ "python", "scikit-learn", "cluster-analysis", "correlation", "hierarchical-clustering" ]
Storing user values in a Python list using a for loop
39,990,718
<p>This is my Code for Asking user to input the number of cities and should allow only that number of cities to enter Requirement is to use For Loop</p> <pre><code>global number_of_cities global city global li global container li = [] number_of_cities = int(raw_input("Enter Number of Cities --&gt;")) for city in range(number_of_cities): city = (raw_input("Enter City Name --&gt;")) li = city print li[] </code></pre>
0
2016-10-12T04:48:56Z
39,991,119
<p>Assuming you want a list of the cities in <code>li</code> you can do the following:</p> <pre><code>li = [] number_of_cities = int(raw_input("Enter Number of Cities --&gt;")) for city in range(number_of_cities): li.append(raw_input("Enter City Name --&gt;")) print(li) </code></pre> <p>No need for the <code>global</code> in front of the variables and no need to define the other variables at the beginning, only the empty list. </p> <p>Actually this is a nice example for learning list comprehension, e.g. </p> <pre><code>n = int(raw_input("Enter Number of Cities: ")) li = [raw_input('City Name: ') for city in range(n)] print(li) </code></pre> <p>This gives:</p> <pre><code>&gt;&gt;&gt; n = int(raw_input("Enter Number of Cities: ")) Enter Number of Cities: 4 &gt;&gt;&gt; li = [raw_input('City Name: ') for city in range(n)] City Name: London City Name: Paris City Name: Dubai City Name: Sidney &gt;&gt;&gt; print(li) ['London', 'Paris', 'Dubai', 'Sidney'] </code></pre>
1
2016-10-12T05:31:19Z
[ "python" ]
Storing user values in a Python list using a for loop
39,990,718
<p>This is my Code for Asking user to input the number of cities and should allow only that number of cities to enter Requirement is to use For Loop</p> <pre><code>global number_of_cities global city global li global container li = [] number_of_cities = int(raw_input("Enter Number of Cities --&gt;")) for city in range(number_of_cities): city = (raw_input("Enter City Name --&gt;")) li = city print li[] </code></pre>
0
2016-10-12T04:48:56Z
39,991,351
<p>Instead of </p> <pre><code>li = city </code></pre> <p>Use</p> <pre><code>li.append(city) </code></pre> <p>Hope thi helps.</p>
0
2016-10-12T05:51:36Z
[ "python" ]
Efficient algorithm to find the count of numbers that are divisible by a number without a remainder in a range
39,990,753
<p>Let's say I have two numbers: 6 and 11 and I am trying to find how many numbers between this range are divisible by 2 (3, in this case).</p> <p>I have this simple code right now:</p> <pre><code>def get_count(a, b, m): count = 0 for i in range(a, b + 1): if i % m == 0: count += 1 return count </code></pre> <p>Its order of growth is linear, O(N), I believe. </p> <p>I was wondering if there is a faster algorithm with a constant O(1) performance, or a mathematical formula. </p> <p>I don't expect a direct answer. The name of such an algorithm would be awesome.</p> <p>Thank you. </p>
0
2016-10-12T04:52:55Z
39,990,818
<p><code>((b - b%m) - a)//m+1</code> seems to work for me. I doubt it has a name. Another formula that seems to work is <code>(b//m) - ((a-1)//m)</code>.</p> <p>Sample python3 program:</p> <pre><code>def get_count(a, b, m): return (((b - (b % m)) - a) // m) + 1 for i in range(5, 8): for j in range(10, 13): print(get_count(i, j, 2), end=" ") print() </code></pre>
1
2016-10-12T04:59:26Z
[ "python", "algorithm", "performance" ]
Efficient algorithm to find the count of numbers that are divisible by a number without a remainder in a range
39,990,753
<p>Let's say I have two numbers: 6 and 11 and I am trying to find how many numbers between this range are divisible by 2 (3, in this case).</p> <p>I have this simple code right now:</p> <pre><code>def get_count(a, b, m): count = 0 for i in range(a, b + 1): if i % m == 0: count += 1 return count </code></pre> <p>Its order of growth is linear, O(N), I believe. </p> <p>I was wondering if there is a faster algorithm with a constant O(1) performance, or a mathematical formula. </p> <p>I don't expect a direct answer. The name of such an algorithm would be awesome.</p> <p>Thank you. </p>
0
2016-10-12T04:52:55Z
39,990,876
<p>To find the count of all numbers between 0 and n that are divisible by two. you can use the bitwise operation called right shift;</p> <pre><code>c = a &gt;&gt; 1; </code></pre> <p>10 >> 1 is equivalent to floor(10/2)</p> <p>You can subtract the two resultant numbers and get numbers between any range.</p> <p>This will work in O(1). Hope this helps.</p>
-1
2016-10-12T05:06:16Z
[ "python", "algorithm", "performance" ]
Efficient algorithm to find the count of numbers that are divisible by a number without a remainder in a range
39,990,753
<p>Let's say I have two numbers: 6 and 11 and I am trying to find how many numbers between this range are divisible by 2 (3, in this case).</p> <p>I have this simple code right now:</p> <pre><code>def get_count(a, b, m): count = 0 for i in range(a, b + 1): if i % m == 0: count += 1 return count </code></pre> <p>Its order of growth is linear, O(N), I believe. </p> <p>I was wondering if there is a faster algorithm with a constant O(1) performance, or a mathematical formula. </p> <p>I don't expect a direct answer. The name of such an algorithm would be awesome.</p> <p>Thank you. </p>
0
2016-10-12T04:52:55Z
39,991,665
<p>You are counting even numbers. Let's write <code>o</code> for odd, <code>E</code> for even.</p> <p>If the sequence has an even count of numbers, it is either <code>oEoE...oE</code> or <code>EoEo...Eo</code>, i.e. one half of numbers is always even. If there is odd count of numbers, you can check the first number (or last one) separately and the rest is the known case discussed first.</p> <pre><code>def count_even(start, end): # assert start &lt;= end len = end - start len2, r = divmod(len, 2) if r and start % 2 == 0: len2 += 1 return len2 </code></pre>
0
2016-10-12T06:15:40Z
[ "python", "algorithm", "performance" ]
gunicorn "configuration cannot be imported"
39,990,844
<p>I'm migrating a project that has been on Heroku to a DO droplet. Install went smoothly, and everything is working well when I <code>python manage.py runserver 0.0.0.0:8000</code>.</p> <p>I'm now setting up gunicorn using these instructions: <a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-14-04" rel="nofollow">https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-14-04</a></p> <p>I activate the virtual environment, and then try <code>--bind 0.0.0.0:3666 myproject.wsgi:application</code>. I get the following error:</p> <pre><code>Traceback (most recent call last): File "/var/www/myproject/venv/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 515, in spawn_worker worker.init_process() File "/var/www/myproject/venv/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 122, in init_process self.load_wsgi() File "/var/www/myproject/venv/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 130, in load_wsgi self.wsgi = self.app.wsgi() File "/var/www/myproject/venv/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/var/www/myproject/venv/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/var/www/myproject/venv/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/var/www/myproject/venv/local/lib/python2.7/site-packages/gunicorn/util.py", line 357, in import_app __import__(module) File "/var/www/myproject/myproject/wsgi.py", line 6, in &lt;module&gt; from configurations.wsgi import get_wsgi_application File "/var/www/myproject/venv/local/lib/python2.7/site-packages/configurations/wsgi.py", line 3, in &lt;module&gt; importer.install() File "/var/www/myproject/venv/local/lib/python2.7/site-packages/configurations/importer.py", line 54, in install importer = ConfigurationImporter(check_options=check_options) File "/var/www/myproject/venv/local/lib/python2.7/site-packages/configurations/importer.py", line 73, in __init__ self.validate() File "/var/www/myproject/venv/local/lib/python2.7/site-packages/configurations/importer.py", line 122, in validate raise ImproperlyConfigured(self.error_msg.format(self.namevar)) ImproperlyConfigured: Configuration cannot be imported, environment variable DJANGO_CONFIGURATION is undefined. </code></pre> <p>My <code>wsgi.py</code> looks like this:</p> <pre><code># -*- coding: utf-8 -*- import os from configurations.wsgi import get_wsgi_application application = get_wsgi_application() </code></pre> <p>I didn't set up the project initially, so I'm not sure what is different, or where to look.</p>
3
2016-10-12T05:02:48Z
39,991,082
<p>Use this link and Set the DJANGO_CONFIGURATION environment variable to the name of the class you just created, e.g. in bash:</p> <p>export DJANGO_CONFIGURATION=Dev </p> <p><a href="https://github.com/jazzband/django-configurations" rel="nofollow">Read further here.</a></p> <p><a href="https://django-configurations.readthedocs.io/en/stable/" rel="nofollow">And/or here.</a></p>
1
2016-10-12T05:27:23Z
[ "python", "django", "gunicorn" ]
Not able to execute pip commands even though pip is installed and added to PATH
39,990,890
<p>I already have pip installed and added the corresponding path to my path,however I dont seem to be able to execute any pip commands(see below),what am I missing?</p> <pre><code>C:\Python27\Lib\site-packages\pip&gt;get-pip.py You are using pip version 6.0.6, however version 8.1.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. Requirement already up-to-date: pip in c:\python27\lib\site-packages C:\Python27\Lib\site-packages\pip&gt;pip install subprocess32 'pip' is not recognized as an internal or external command, operable program or batch file. </code></pre>
0
2016-10-12T05:07:51Z
39,990,930
<p>You have <code>pip</code> installed but you don't have any command named <code>pip</code>.</p> <p>try <code>python -m pip</code></p>
0
2016-10-12T05:12:49Z
[ "python", "pip" ]
Debugging python segmentation faults in garbage collection
39,990,934
<p>I'm faced with segmentation faults (SIGSEGV) which occur during garbage collection in cPython. I've also had one instance where a process was killed with SIGBUS. My own code is mostly python and a little bit of very high level Cython. I'm most certainly not - deliberately and explicitly - fooling around with pointers or writing to memory directly.</p> <hr> <p>Example backtraces from coredumps (extracted with gdb):</p> <pre><code>#0 0x00007f8b0ac29471 in subtype_dealloc (self=&lt;Task at remote 0x7f8afc0466d8&gt;) at /usr/src/debug/Python-3.5.1/Objects/typeobject.c:1182 #1 0x00007f8b0abe8947 in method_dealloc (im=0x7f8afc883e08) at /usr/src/debug/Python-3.5.1/Objects/classobject.c:198 #2 0x00007f8b0ac285a9 in clear_slots (type=type@entry=0x560219f0fa88, self=self@entry=&lt;Handle at remote 0x7f8afc035948&gt;) at /usr/src/debug/Python-3.5.1/Objects/typeobject.c:1044 #3 0x00007f8b0ac29506 in subtype_dealloc (self=&lt;Handle at remote 0x7f8afc035948&gt;) at /usr/src/debug/Python-3.5.1/Objects/typeobject.c:1200 #4 0x00007f8b0ac8caad in PyEval_EvalFrameEx ( f=f@entry=Frame 0x56021a01ff08, for file /usr/lib64/python3.5/asyncio/base_events.py, line 1239, in _run_once (self=&lt;_UnixSelectorEventLoop(_coroutine_wrapper_set=False, _current_handle=None, _ready=&lt;collections.deque at remote 0x7f8afd39a250&gt;, _closed=False, _task_factory=None, _selector=&lt;EpollSelector(_map=&lt;_SelectorMapping(_selector=&lt;...&gt;) at remote 0x7f8afc868748&gt;, _epoll=&lt;select.epoll at remote 0x7f8b0b1b8e58&gt;, _fd_to_key={4: &lt;SelectorKey at remote 0x7f8afcac8a98&gt;, 6: &lt;SelectorKey at remote 0x7f8afcac8e08&gt;, 7: &lt;SelectorKey at remote 0x7f8afcac8e60&gt;, 8: &lt;SelectorKey at remote 0x7f8afc873048&gt;, 9: &lt;SelectorKey at remote 0x7f8afc873830&gt;, 10: &lt;SelectorKey at remote 0x7f8afc873af0&gt;, 11: &lt;SelectorKey at remote 0x7f8afc87b620&gt;, 12: &lt;SelectorKey at remote 0x7f8afc87b7d8&gt;, 13: &lt;SelectorKey at remote 0x7f8afc889af0&gt;, 14: &lt;SelectorKey at remote 0x7f8afc884678&gt;, 15: &lt;SelectorKey at remote 0x7f8afc025eb8&gt;, 16: &lt;SelectorKey at remote 0x7f8afc889db0&gt;, 17: &lt;SelectorKey at remote 0x7f8afc01a258&gt;, 18: &lt;SelectorKey at remote 0x7f8afc...(truncated), throwflag=throwflag@entry=0) at /usr/src/debug/Python-3.5.1/Python/ceval.c:1414 </code></pre> <p>During the sweep (I think):</p> <pre><code>#1 0x00007f0a0624c63f in visit_decref (op=, data=&lt;optimized out&gt;) at /usr/src/debug/Python-3.5.1/Modules/gcmodule.c:373 #2 0x00007f0a0624b813 in subtract_refs (containers=&lt;optimized out&gt;) at /usr/src/debug/Python-3.5.1/Modules/gcmodule.c:398 #3 collect (generation=generation@entry=2, n_collected=n_collected@entry=0x7f09d75708c8, n_uncollectable=n_uncollectable@entry=0x7f09d75708d0, nofail=nofail@entry=0) at /usr/src/debug/Python-3.5.1/Modules/gcmodule.c:951 </code></pre> <p>And also once during malloc:</p> <pre><code>#0 _PyObject_Malloc (ctx=0x0, nbytes=56) at /usr/src/debug/Python-3.4.3/Objects/obmalloc.c:1159 1159 if ((pool-&gt;freeblock = *(block **)bp) != NULL) { (gdb) bt #0 _PyObject_Malloc (ctx=0x0, nbytes=56) at /usr/src/debug/Python-3.4.3/Objects/obmalloc.c:1159 </code></pre> <p>And the SIGBUS trace (looks like it happened while cPython was recovering from another error):</p> <pre><code>#0 malloc_printerr (ar_ptr=0x100101f0100101a, ptr=0x7f067955da60 &lt;generations+32&gt;, str=0x7f06785a2b8c "free(): invalid size", action=3) at malloc.c:5009 5009 set_arena_corrupt (ar_ptr); (gdb) bt #0 malloc_printerr (ar_ptr=0x100101f0100101a, ptr=0x7f067955da60 &lt;generations+32&gt;, str=0x7f06785a2b8c "free(): invalid size", action=3) at malloc.c:5009 #1 _int_free (av=0x100101f0100101a, p=&lt;optimized out&gt;, have_lock=0) at malloc.c:3842 Python Exception &lt;type 'exceptions.RuntimeError'&gt; Type does not have a target.: </code></pre> <hr> <p>These back traces are from Fedora 24 with Python 3.5.1 and some from Centos 7 with Python 3.4.3. So I'm ruling out issues like:</p> <ul> <li>bad memory (could be, but quite a coincidence that my laptop and a (virtual) server exhibit the same issue and show no otherwise work fine).</li> <li>Issues in the OS or cPython or the combination thereof.</li> </ul> <p>So - as usual - it must be something in my own code. It's a mixture of threaded code for some concurrency of (computational) 'tasks' and a thread running an asyncio loop. The code base has other 'workloads' which run fine. Differences in the code which is 'serving' this 'workload' which stand out to me are that I use (threading.RLock) locks quite a bit to serialize some requests and I'm serializing and writing to disk.</p> <p>Any suggestions on how to find a root cause would be highly appreciated!</p> <p>Things I've tried:</p> <ul> <li>Stripping down the external dependencies used to the bare minimum (which was cloudpickle): no difference</li> <li>Dumping counts of all object types as seen by the garbage collector before and after explicit collection and seeing if there were types of objects tracked just before a crash and weren't in the 'successful' garbage collections: there weren't.</li> <li>Going through core dumps with GDB: not really consistent regarding the C nor the Python backtraces.</li> <li>Running with MALLOC_CHECK_=2: I don't see any error messages other than that a process has exited with exit code -11.</li> </ul> <hr> <h2>Edit 1</h2> <p>Got something: <a href="https://gist.github.com/frensjan/dc9bc784229fec844403c9d9528ada66" rel="nofollow">https://gist.github.com/frensjan/dc9bc784229fec844403c9d9528ada66</a> </p> <p>Most notably:</p> <pre><code>==19072== Invalid write of size 8 ==19072== at 0x47A3B7: subtype_dealloc (typeobject.c:1157) ==19072== by 0x4E0696: PyEval_EvalFrameEx (ceval.c:1388) ==19072== by 0x58917B: gen_send_ex (genobject.c:104) ==19072== by 0x58917B: _PyGen_Send (genobject.c:158) ... ==19072== by 0x4E2A6A: call_function (ceval.c:4262) ==19072== by 0x4E2A6A: PyEval_EvalFrameEx (ceval.c:2838) ==19072== Address 0x8 is not stack'd, malloc'd or (recently) free'd </code></pre> <p>and</p> <pre><code>==19072== Process terminating with default action of signal 11 (SIGSEGV): dumping core ==19072== Access not within mapped region at address 0x8 ==19072== at 0x47A3B7: subtype_dealloc (typeobject.c:1157) ==19072== by 0x4E0696: PyEval_EvalFrameEx (ceval.c:1388) ==19072== by 0x58917B: gen_send_ex (genobject.c:104) ==19072== by 0x58917B: _PyGen_Send (genobject.c:158) </code></pre> <p>But the errors valgrind found point to the same locations as the coredumps I got earlier, nowhere near my code ... not really sure what to do with this. </p> <p>Environment: Python 3.4.5+ built with <code>./configure --without-pymalloc</code> on Centos 7. Ran python with <code>valgrind --tool=memcheck --dsymutil=yes --track-origins=yes --show-leak-kinds=all --trace-children=yes python ...</code></p> <p>Any help is much appreciated!</p>
1
2016-10-12T05:13:02Z
40,038,616
<p>I am rather confident that issue I ran across is due to <a href="https://bugs.python.org/issue26617" rel="nofollow">issue 26617</a> in CPython which is fixed in <a href="https://github.com/python/cpython/commit/7bfa6f2bfe1b14eec0e9e036866f7acd52d1c8ee" rel="nofollow">7bfa6f2</a>.</p> <p>I've check this by reproducing the issue (running into SIGSEGV) with a build of the commit just <em>before 7bfa6f2</em> and not being able to reproduce it with a build of commit <em>7bfa6f2</em>.</p>
1
2016-10-14T08:34:35Z
[ "python", "c", "multithreading", "garbage-collection", "memory-corruption" ]
python: ValueError: I/O operation on closed file
39,990,999
<p>My code:</p> <pre><code>with open('pass.txt') as f: credentials = dict([x.strip().split(':') for x in f.readlines()]) # Created a dictionary with username:password items name_input = input('Please Enter username: ') if name_input in credentials: # Check if username is in the credentials dictionary name_input = input('Please Enter new username: ') f.write(name_input) f.write(":") pass_input = input('Please Enter password: ') f.write(pass_input) f.write("\n") f.close() print('Registered') </code></pre> <p>I am getting this error: </p> <pre><code>Traceback (most recent call last): File "silwon.py", line 146, in &lt;module&gt; f.write(name_input) ValueError: I/O operation on closed file. </code></pre> <p>also how to use sys.exit after the user enters the same username 3 times?</p>
1
2016-10-12T05:19:27Z
39,991,503
<p>Every file operation in Python is done on a file opened in a certain mode. The mode must be specified as an argument to the open function, and it determines the operations that can be done on the file, and the initial location of the file pointer.</p> <p>In your code, you have opened the file without any argument other than the name to the open function. When the mode isn't specified, the file is opened in the default mode - read-only, or <code>'r'</code>. This places the file pointer at the beginning of the file and enables you to sequentially scan the contents of the file, and read them into variables in your program. To be able to write data into the file, you must specify a mode for opening the file which enables writing data into the file. A suitable mode for this can be chose from two options, <code>'w'</code> or <code>'w+'</code> and <code>'a'</code> or <code>'a+'</code>. </p> <p><code>'w'</code> opens the file and gives access to the user only to write data into the file, not to read from it. It also places the pointer at the beginning of the file and overwrites any existing data. <code>'w+'</code> is almost the same, the only difference being that you can read from the file as well.</p> <p><code>'a'</code> opens the file for writing, and places the file pointer at the end of the file, so you don't overwrite the contents of the file. <code>'a+'</code> extends the functionality of <code>'a'</code> to allow reading from the file as well.</p> <p>Use an appropriate mode of opening the file to suit your requirement, and execute it by modifying the open command to <code>open('pass.txt', &lt;mode&gt;)</code>.</p>
3
2016-10-12T06:03:54Z
[ "python", "python-3.4" ]
In python, how do you check if a string has both uppercase and lowercase letters
39,991,064
<p>I've looked at the other post similar to my question, <a href="http://stackoverflow.com/questions/36380351/password-check-python-3">Password check- Python 3</a>, except my question involves checking if the password contains both uppercase and lower case questions. My code is the following, but when executed it fails to recognize that both lower and upper case letters are in the password, it only recognizes one type. How would I get it to recognize both types? Also is there an easier way to have the code check if all of those values occur without having to make functions for each individual step?</p> <pre><code>def Get_Password(): return input("Enter your desired password: ") def Count_Digits(password): return sum(character.isdigit() for character in password) def Valid_password_length(password): if len(password) &gt;= 10: return ('step1' == True) else: return ('step1' == False, print("Invalid password: too short")) def Valid_password_characters(password): if password.isalnum(): return ('step2' == True) else: return ('step2' == False, print("Invalid password: illegal character detected")) def Valid_password_numdigit(password): if Count_Digits(password) &gt;= 2: return ('step3' == True) else: return ('step3' == False, print("Invalid password: Must have at least 2 digits")) def Valid_password_lowercase(password): for i in (password): if i.islower() == True: return ('step4' == True) else: return ('step4' == False, print("Invalid password: No lowercase characters detected")) def Valid_password_uppercase(password): for i in (password): if i.isupper() == True: return ('step5' == True) else: return ('step5' == False, print("Invalid password: No uppercase characters detected")) def password_checker(): password = Get_Password() Valid_password_length(password) Valid_password_characters(password) Valid_password_numdigit(password) Valid_password_lowercase(password) Valid_password_uppercase(password) if 'step1' and 'step2' and 'step3' and 'step4' and 'step5' == True: print("Congratulations! This password is valid") password_checker() </code></pre>
1
2016-10-12T05:26:03Z
39,991,194
<pre><code>import sys def Valid_password_mixed_case(password): letters = set(password) mixed = any(letter.islower() for letter in letters) and any(letter.isupper() for letter in letters) if not mixed: print("Invalid password: Mixed case characters not detected", file=sys.stderr) return mixed </code></pre> <p>A complete solution:</p> <pre><code>import sys def Get_Password(): return input("Enter your desired password: ") def Count_Digits(password): return sum(1 for character in password if character.isdigit()) def Valid_password_length(password): correct_length = len(password) &gt;= 10 if not correct_length: print("Invalid password: too short", file=sys.stderr) return correct_length def Valid_password_characters(password): correct_characters = password.isalnum() if not correct_characters: print("Invalid password: illegal character detected", file=sys.stderr) return correct_characters def Valid_password_numdigit(password): sufficient_digits = Count_Digits(password) &gt;= 2 if not sufficient_digits: print("Invalid password: Must have at least 2 digits", file=sys.stderr) return sufficient_digits def Valid_password_mixed_case(password): letters = set(password) lower = any(letter.islower() for letter in letters) upper = any(letter.isupper() for letter in letters) if not upper: print("Invalid password: No uppercase characters detected", file=sys.stderr) if not lower: print("Invalid password: No lowercase characters detected", file=sys.stderr) return lower and upper def password_checker(): password = Get_Password() if Valid_password_length(password) and \ Valid_password_characters(password) and \ Valid_password_numdigit(password) and \ Valid_password_mixed_case(password): print("Congratulations! This password is valid") password_checker() </code></pre>
0
2016-10-12T05:36:48Z
[ "python", "string" ]
In python, how do you check if a string has both uppercase and lowercase letters
39,991,064
<p>I've looked at the other post similar to my question, <a href="http://stackoverflow.com/questions/36380351/password-check-python-3">Password check- Python 3</a>, except my question involves checking if the password contains both uppercase and lower case questions. My code is the following, but when executed it fails to recognize that both lower and upper case letters are in the password, it only recognizes one type. How would I get it to recognize both types? Also is there an easier way to have the code check if all of those values occur without having to make functions for each individual step?</p> <pre><code>def Get_Password(): return input("Enter your desired password: ") def Count_Digits(password): return sum(character.isdigit() for character in password) def Valid_password_length(password): if len(password) &gt;= 10: return ('step1' == True) else: return ('step1' == False, print("Invalid password: too short")) def Valid_password_characters(password): if password.isalnum(): return ('step2' == True) else: return ('step2' == False, print("Invalid password: illegal character detected")) def Valid_password_numdigit(password): if Count_Digits(password) &gt;= 2: return ('step3' == True) else: return ('step3' == False, print("Invalid password: Must have at least 2 digits")) def Valid_password_lowercase(password): for i in (password): if i.islower() == True: return ('step4' == True) else: return ('step4' == False, print("Invalid password: No lowercase characters detected")) def Valid_password_uppercase(password): for i in (password): if i.isupper() == True: return ('step5' == True) else: return ('step5' == False, print("Invalid password: No uppercase characters detected")) def password_checker(): password = Get_Password() Valid_password_length(password) Valid_password_characters(password) Valid_password_numdigit(password) Valid_password_lowercase(password) Valid_password_uppercase(password) if 'step1' and 'step2' and 'step3' and 'step4' and 'step5' == True: print("Congratulations! This password is valid") password_checker() </code></pre>
1
2016-10-12T05:26:03Z
39,991,240
<p>Your question is simple to answer. You are returning things of the form <code>return('steps' == True)</code> which is always going to return false. So just replace those with <code>return True</code> or <code>return False</code>.</p> <p>Assuming you fix the above, your looping is also buggy. You only want to return false after you have looped through the entire string. Consider the password: <code>ABCd</code>. This contains a lowercase character but your check lowercase method would return false because the first letter is uppercase. You want to look through every character in password and if none of those are lowercase, then return false.</p> <p>If you want a neater way to do it, <a href="http://stackoverflow.com/a/39991194/5718020">cdlane's answer</a> is a nice pythonic way.</p>
0
2016-10-12T05:40:45Z
[ "python", "string" ]
In python, how do you check if a string has both uppercase and lowercase letters
39,991,064
<p>I've looked at the other post similar to my question, <a href="http://stackoverflow.com/questions/36380351/password-check-python-3">Password check- Python 3</a>, except my question involves checking if the password contains both uppercase and lower case questions. My code is the following, but when executed it fails to recognize that both lower and upper case letters are in the password, it only recognizes one type. How would I get it to recognize both types? Also is there an easier way to have the code check if all of those values occur without having to make functions for each individual step?</p> <pre><code>def Get_Password(): return input("Enter your desired password: ") def Count_Digits(password): return sum(character.isdigit() for character in password) def Valid_password_length(password): if len(password) &gt;= 10: return ('step1' == True) else: return ('step1' == False, print("Invalid password: too short")) def Valid_password_characters(password): if password.isalnum(): return ('step2' == True) else: return ('step2' == False, print("Invalid password: illegal character detected")) def Valid_password_numdigit(password): if Count_Digits(password) &gt;= 2: return ('step3' == True) else: return ('step3' == False, print("Invalid password: Must have at least 2 digits")) def Valid_password_lowercase(password): for i in (password): if i.islower() == True: return ('step4' == True) else: return ('step4' == False, print("Invalid password: No lowercase characters detected")) def Valid_password_uppercase(password): for i in (password): if i.isupper() == True: return ('step5' == True) else: return ('step5' == False, print("Invalid password: No uppercase characters detected")) def password_checker(): password = Get_Password() Valid_password_length(password) Valid_password_characters(password) Valid_password_numdigit(password) Valid_password_lowercase(password) Valid_password_uppercase(password) if 'step1' and 'step2' and 'step3' and 'step4' and 'step5' == True: print("Congratulations! This password is valid") password_checker() </code></pre>
1
2016-10-12T05:26:03Z
39,991,634
<p>You could use regular expression : </p> <p>i.e. : </p> <pre><code>def Valid_mixed_password(password): lower = re.compile(r'.*[a-z]+') # Compile to match lowercase upper = re.compile(r'.*[A-Z]+') # Compile to match uppercase if lower.match(password) and upper.match(password): # if the password contains both (lowercase and uppercase letters) then return True return True else: # Else, the password does not contains uppercase and lowercase letters then return False return False &gt;&gt;&gt; print Valid_mixed_password("hello") False &gt;&gt;&gt; print Valid_mixed_password("HELLO") False &gt;&gt;&gt; print Valid_mixed_password("HellO") True &gt;&gt;&gt; print Valid_mixed_password("heLLo") True </code></pre> <p>Hope it helps. </p>
-1
2016-10-12T06:13:07Z
[ "python", "string" ]
How to do first migration in flask?
39,991,316
<p>I am working on an new project which is already developed in Flask and I have no knowledge of Flask. My company gave the project to me because I have Django experience.</p> <p>This is the structure of the project:</p> <pre><code>models -db.py -model1.py -model2.py - .. static - .. templates - .. myapp.py </code></pre> <p><code>myapp.py</code> contains all config files and server init code with all other functionality such as that for home page and sign up page.</p> <p>When I run <code>myapp.py</code> it runs OK, but the tables are not created automatically (I found that first migration has to be done). I have no idea how to do it.</p> <p>The project makes use of postgresql and SQLAlchemy form flask_sqlalchemy Modules.</p> <p><code>db.py</code> file: </p> <pre><code>from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() </code></pre> <p>All models have <code>from db import db</code></p> <p><code>myapp</code> file:</p> <pre><code># =================================================================== # SQL ALCHEMY # =================================================================== if (SERVER_MODE == RUN_MODE.PRODUCTION): app.config['SQLALCHEMY_DATABASE_URI'] = ( os.environ["DATABASE_URL"] ) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False else: app.config['SQLALCHEMY_DATABASE_URI'] = ( 'postgresql://' + 'creathiveswebapp:creathives' + '@' + 'localhost/cl_creathives_pgdb' ) app.config['SQLALCHEMY_ECHO'] = False app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db.init_app(app) </code></pre> <p>and </p> <pre><code>... # =================================================================== # START SERVER # =================================================================== if __name__ == "__main__": port = int(os.environ.get('PORT', 5000)) if (SERVER_MODE == RUN_MODE.PRODUCTION): # TODO: Turn off debug app.run(host='0.0.0.0', port=port, debug=True) else: app.run(host='0.0.0.0') </code></pre> <p>How do I make first migration to create the tables.</p>
1
2016-10-12T05:48:21Z
39,991,363
<p>Use this command :</p> <pre><code> python manage.py db migrate </code></pre> <p>And for database migration settings,Try something like this :</p> <pre><code> import os from flask.ext.script import Manager from flask.ext.migrate import Migrate, MigrateCommand from app import app, db app.config.from_object(os.environ['APP_SETTINGS']) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run() </code></pre> <p>For further knowledge,<a href="https://realpython.com/blog/python/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/" rel="nofollow">Read from here.</a></p>
1
2016-10-12T05:52:18Z
[ "python", "flask", "flask-sqlalchemy" ]
overwrite attribute as function Django
39,991,320
<p>I have <code>class A(models.Model)</code> with attr <code>name</code>. I use it in template and view as <code>obj_a.name</code>. I need overwrite <code>name</code> attr as function and when I write <code>obj_a.name</code> I would get response from function <code>getName</code>. How can I do it in <code>Django</code> and <code>Python</code> ? In <code>Laravel PHP</code> it is <code>$this-&gt;getNameAttribute()</code> and I can overwrite returning <code>name</code> from object. <code>Name</code> is only example and I want use it with almost all attr given class.</p> <pre><code>class Item(caching.base.CachingMixin, models.Model): _name = models.CharField(_('Name'), max_length=100, db_column="name", help_text=_('Item name')) @property def name(self): return self._name @name.setter def name(self, value): self._name = value </code></pre>
-2
2016-10-12T05:48:49Z
39,991,460
<p>You can achieve this behavior with <a href="https://docs.python.org/2/library/functions.html#property" rel="nofollow"><code>property</code></a>.</p> <pre><code>class A(models.Model): _name = Field() @property def name(self): return self._name </code></pre>
3
2016-10-12T05:59:50Z
[ "python", "django", "object", "django-models", "attributes" ]
overwrite attribute as function Django
39,991,320
<p>I have <code>class A(models.Model)</code> with attr <code>name</code>. I use it in template and view as <code>obj_a.name</code>. I need overwrite <code>name</code> attr as function and when I write <code>obj_a.name</code> I would get response from function <code>getName</code>. How can I do it in <code>Django</code> and <code>Python</code> ? In <code>Laravel PHP</code> it is <code>$this-&gt;getNameAttribute()</code> and I can overwrite returning <code>name</code> from object. <code>Name</code> is only example and I want use it with almost all attr given class.</p> <pre><code>class Item(caching.base.CachingMixin, models.Model): _name = models.CharField(_('Name'), max_length=100, db_column="name", help_text=_('Item name')) @property def name(self): return self._name @name.setter def name(self, value): self._name = value </code></pre>
-2
2016-10-12T05:48:49Z
39,992,036
<p>I found solution ideal for my usage:</p> <pre><code>def __getattribute__(self, name): if name == 'name': return 'xxx' return super(Item, self).__getattribute__(name) </code></pre>
0
2016-10-12T06:40:49Z
[ "python", "django", "object", "django-models", "attributes" ]
Subtract a column in pandas dataframe by its first value
39,991,471
<p>I need to subtract all elements in one column of pandas dataframe by its first value.</p> <p>In this code, pandas complains about self.inferred_type, which I guess is the circular referencing.</p> <pre><code>df.Time = df.Time - df.Time[0] </code></pre> <p>And in this code, pandas complains about setting value on copies.</p> <pre><code>df.Time = df.Time - df.iat[0,0] </code></pre> <p>What is the correct way to do this computation in Pandas?</p>
2
2016-10-12T06:01:15Z
39,991,512
<p>I think you can select first item in column <code>Time</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iloc.html" rel="nofollow"><code>iloc</code></a>:</p> <pre><code>df.Time = df.Time - df.Time.iloc[0] </code></pre> <p>Sample:</p> <pre><code>start = pd.to_datetime('2015-02-24 10:00') rng = pd.date_range(start, periods=5) df = pd.DataFrame({'Time': rng, 'a': range(5)}) print (df) Time a 0 2015-02-24 10:00:00 0 1 2015-02-25 10:00:00 1 2 2015-02-26 10:00:00 2 3 2015-02-27 10:00:00 3 4 2015-02-28 10:00:00 4 df.Time = df.Time - df.Time.iloc[0] print (df) Time a 0 0 days 0 1 1 days 1 2 2 days 2 3 3 days 3 4 4 days 4 </code></pre> <p>Notice:</p> <p>For me works perfectly your 2 ways also.</p>
2
2016-10-12T06:04:36Z
[ "python", "datetime", "pandas", "time", "subtraction" ]
How can i solve this regular expression, Python?
39,991,485
<p>I would like to construct a reg expression pattern for the following string, and use Python to extract:</p> <pre><code>str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n" </code></pre> <p>What I want to do is extract the <strong>independent</strong> number values and add them which should be 278. A prelimenary python code is:</p> <pre><code>import re x = re.findall('([0-9]+)', str) </code></pre> <p>The problem with the above code is that numbers within a char substring like 'ar3' would show up. Any idea how to solve this?</p>
0
2016-10-12T06:02:42Z
39,991,529
<p>How about this?</p> <pre><code>x = re.findall('\s([0-9]+)\s', str) </code></pre>
0
2016-10-12T06:05:44Z
[ "python", "regex" ]
How can i solve this regular expression, Python?
39,991,485
<p>I would like to construct a reg expression pattern for the following string, and use Python to extract:</p> <pre><code>str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n" </code></pre> <p>What I want to do is extract the <strong>independent</strong> number values and add them which should be 278. A prelimenary python code is:</p> <pre><code>import re x = re.findall('([0-9]+)', str) </code></pre> <p>The problem with the above code is that numbers within a char substring like 'ar3' would show up. Any idea how to solve this?</p>
0
2016-10-12T06:02:42Z
39,991,556
<p>To avoid a partial match use this: <code>'^[0-9]*$'</code></p>
0
2016-10-12T06:07:36Z
[ "python", "regex" ]
How can i solve this regular expression, Python?
39,991,485
<p>I would like to construct a reg expression pattern for the following string, and use Python to extract:</p> <pre><code>str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n" </code></pre> <p>What I want to do is extract the <strong>independent</strong> number values and add them which should be 278. A prelimenary python code is:</p> <pre><code>import re x = re.findall('([0-9]+)', str) </code></pre> <p>The problem with the above code is that numbers within a char substring like 'ar3' would show up. Any idea how to solve this?</p>
0
2016-10-12T06:02:42Z
39,991,567
<pre><code>s = re.findall(r"\s\d+\s", a) # \s matches blank spaces before and after the number. print (sum(map(int, s))) # print sum of all </code></pre> <p><code>\d+</code> matches all digits. This gives the exact expected output.</p> <pre><code>278 </code></pre>
2
2016-10-12T06:08:21Z
[ "python", "regex" ]
How can i solve this regular expression, Python?
39,991,485
<p>I would like to construct a reg expression pattern for the following string, and use Python to extract:</p> <pre><code>str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n" </code></pre> <p>What I want to do is extract the <strong>independent</strong> number values and add them which should be 278. A prelimenary python code is:</p> <pre><code>import re x = re.findall('([0-9]+)', str) </code></pre> <p>The problem with the above code is that numbers within a char substring like 'ar3' would show up. Any idea how to solve this?</p>
0
2016-10-12T06:02:42Z
39,991,583
<p>Why not try something simpler like this?: </p> <pre><code>str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n" print sum([int(s) for s in str.split() if s.isdigit()]) # 278 </code></pre>
1
2016-10-12T06:09:38Z
[ "python", "regex" ]