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
list
How do I get the size of an RstDocument in Kivy?
38,949,366
<p>This feels like a dumb question but I've crawled the internet for the past few days to no avail over something that seems really simple. Anyways, what I am trying to do is have a TreeView widget that has RstDocument leaves. Now, when I do this I get a bunch of leaves that have smaller windows in a similar fashion ...
1
2016-08-15T04:34:01Z
38,983,864
<p>Nevermind, I found the solution to my question. I will post it here for reference to someone else having the same or similar issue.</p> <p>The problem I had when I was trying to get a size out of the RstDocument Object was the fact that at the time the node was still collapsed, and the object's height was 0 as a r...
0
2016-08-16T20:25:47Z
[ "android", "python", "treeview", "scrollview", "kivy" ]
How can I invoke a Python 3 script as a CCS/Eclipse build step on both Linux and Windows?
38,949,377
<p>I have a Python 3.5 script that I would like to invoke as a pre-build step in my Code Composer build. To be clear, it should be run as one of the entries in <em>(my project) > Properties > CCS Build > Steps > Pre-build steps</em>.</p> <p>The script currently begins with the hashbang <code>#!/usr/bin/env python3</co...
2
2016-08-15T04:35:34Z
39,066,986
<p>Have a wrapper script that works under both Python 2 and 3 to detect and run the script with the correct Python version. The Eclipse/CCS pre build step can then be <code>python ../wrapper.py</code> (possibly with extra arguments like <code>../prebuild.py args</code>).</p> <p>You could just check if it is running on...
1
2016-08-21T17:34:02Z
[ "python", "eclipse", "cross-platform", "code-composer" ]
How to use the argument of a function to determine which class to call?
38,949,378
<p>Let's say we have a bunch of monster classes, which include a Goblin and an Imp:</p> <pre><code>class Goblin(object): def __init__(self): self.Name = "Goblin" self.HP = random.randint(15,20) self.Damage = random.randint(5,10) class Imp(object): def __init__(self): se...
1
2016-08-15T04:35:34Z
38,949,412
<p>if you're passing it as a string, you can use the <code>globals()</code> method which returns a dictionary of all the variables in the global namespace</p> <pre><code>def GenerateCharacter(Type, Number): Character_List = [] for i in range(Number): name = Type TempChar = globals()[name](name)...
1
2016-08-15T04:41:36Z
[ "python", "python-3.x", "oop", "object" ]
How to use the argument of a function to determine which class to call?
38,949,378
<p>Let's say we have a bunch of monster classes, which include a Goblin and an Imp:</p> <pre><code>class Goblin(object): def __init__(self): self.Name = "Goblin" self.HP = random.randint(15,20) self.Damage = random.randint(5,10) class Imp(object): def __init__(self): se...
1
2016-08-15T04:35:34Z
38,949,458
<p>Assuming you're passing in the name of the class as a string, try something like this:</p> <pre><code>def GenerateCharacter(Type, Number): i=0 while i &lt; (Number): if Type == "Goblin": TempChar = Goblin() elif Type == "Imp": TempChar = Imp() # Etc. for every...
1
2016-08-15T04:48:27Z
[ "python", "python-3.x", "oop", "object" ]
How to get chat id with Kik Api
38,949,402
<p>I've created code with the Kik Api in Python 3.5, but I've come to a stand still when I am trying to get the chat id. I have searched, but I have no idea to use the api to find a chat id to send messages to. How do you get the chat id with the api? My code is here: <a href="http://pastebin.com/LP8ahhhd" rel="nofollo...
0
2016-08-15T04:39:35Z
38,949,425
<p>If I'm not mistaken, the code you posted has a chatID field in it? You need to use that to send messages back to the same conversation. See here for more information: <a href="https://dev.kik.com/#/docs/messaging#sending-messages" rel="nofollow">https://dev.kik.com/#/docs/messaging#sending-messages</a></p>
0
2016-08-15T04:43:43Z
[ "python", "json", "api", "kik" ]
How to get chat id with Kik Api
38,949,402
<p>I've created code with the Kik Api in Python 3.5, but I've come to a stand still when I am trying to get the chat id. I have searched, but I have no idea to use the api to find a chat id to send messages to. How do you get the chat id with the api? My code is here: <a href="http://pastebin.com/LP8ahhhd" rel="nofollo...
0
2016-08-15T04:39:35Z
38,957,737
<p>When you receive a message it will look something like this</p> <pre><code>{ "messages": [ { "chatId": "0ee6d46753bfa6ac2f089149959363f3f59ae62b10cba89cc426490ce38ea92d", "id": "0115efde-e54b-43d5-873a-5fef7adc69fd", "type": "text", "from": "laura", ...
0
2016-08-15T15:06:44Z
[ "python", "json", "api", "kik" ]
Intricate file/text manipulation
38,949,431
<p>I have some rather tricky file manipulation I need to perform, but I am rather bad with coding and I am immediately stumped with where to even begin. Any help would be amazing, so thanks in advance. Preferably in Shell or Python as they are the languages I have cursory knowledge of, however if there is an easy solut...
-3
2016-08-15T04:44:38Z
38,962,628
<p>You will need to learn Python better than you know it now. Here is an outline what you will need to do. It is very typical for this kind of "file manipulation".</p> <ol> <li>Make a regular expression that will match lines from <code>file1</code> and <code>file2</code> (or two regular expression if the files do no...
1
2016-08-15T20:35:02Z
[ "python", "shell", "data-manipulation" ]
How do I improve my Python code about heap sort?
38,949,481
<p>I tried to write a heap sort program myself for <a href="https://leetcode.com/problems/contains-duplicate/" rel="nofollow">Leetcode 217. Contains Duplicate</a> as below rather than using Python built-in sort method. Leetcode should accept heap sort method, but for some reasons I don't know, although my heap sort pro...
-1
2016-08-15T04:52:56Z
38,949,559
<p>Speaking of heap sort, consider <a href="https://docs.python.org/2/library/heapq.html" rel="nofollow"><code>heapq</code></a> python module. It exists for this very purpose - provide an implementation of the heap queue algorithm. It isn't designed not very conveniently, but there are handy <a href="http://code.active...
0
2016-08-15T05:04:38Z
[ "python", "algorithm", "sorting", "heapsort" ]
How do I improve my Python code about heap sort?
38,949,481
<p>I tried to write a heap sort program myself for <a href="https://leetcode.com/problems/contains-duplicate/" rel="nofollow">Leetcode 217. Contains Duplicate</a> as below rather than using Python built-in sort method. Leetcode should accept heap sort method, but for some reasons I don't know, although my heap sort pro...
-1
2016-08-15T04:52:56Z
38,958,205
<p>Your code does way too much. You're rebuilding the entire heap with every item that you remove. So what should be an O(n log n) algorithm is instead O(n^2).</p> <p>Essentially, your code is doing this:</p> <pre><code>while array is not empty rearrange array into a heap extract the smallest item </code></pr...
1
2016-08-15T15:34:48Z
[ "python", "algorithm", "sorting", "heapsort" ]
How restrict creation of objects of one class to instances of another in Python?
38,949,544
<p>I have encountered a conundrum. I think I should know how to solve this — I am extremely knowledgeable and experienced in Python — but I can't figure it out. It seems like what I am struggling with should be addressed by a design pattern that is a variation on the factory theme, but I can't recall one. (At the e...
5
2016-08-15T05:01:52Z
38,949,788
<p>Python is not very good at completely hiding it's objects ... <em>Even</em> if you decide to do the "Russian doll" closure to attempt to hide a class definition, a user can still get at it...</p> <pre><code>class A(object): def create_b(self): class B(object): pass return B() a = A(...
6
2016-08-15T05:33:16Z
[ "python", "class", "encapsulation" ]
How restrict creation of objects of one class to instances of another in Python?
38,949,544
<p>I have encountered a conundrum. I think I should know how to solve this — I am extremely knowledgeable and experienced in Python — but I can't figure it out. It seems like what I am struggling with should be addressed by a design pattern that is a variation on the factory theme, but I can't recall one. (At the e...
5
2016-08-15T05:01:52Z
38,950,026
<p>Just from the top of my head:</p> <pre><code>def B(object): pass def D(object): pass def bound(object): if type(object) is C: assert isinstance(D) if type(object) is A: assert isinstance(B) else: assert false @bound def C(D): pass @bound def A(B): pass </code>...
1
2016-08-15T06:02:42Z
[ "python", "class", "encapsulation" ]
Raspberry Pi - How to print hex value?
38,949,574
<p><a href="http://i.stack.imgur.com/eb68s.png" rel="nofollow"><img src="http://i.stack.imgur.com/eb68s.png" alt="enter image description here"></a>I m using Python in Raspberry Pi and my packet is in hexadecimal value like <code>"0x750x010x010x060x000x08"</code>. I want serial communication between UART and Raspberry ...
0
2016-08-15T05:06:46Z
38,949,684
<pre><code>import serial port=serial.Serial("/dev/ttyAMA0",baudrate=115200,timeout=3.0) while True: a="0x750x010x010x060x000x08" b=a.replace("0x"," ") #print b alist = b.split(" ") for element in alist port.write("\r\n"+str(element)) </code></pre> <p>this gives the desired formatted data...
0
2016-08-15T05:21:34Z
[ "python", "windows", "hex", "putty", "raspberry-pi3" ]
Raspberry Pi - How to print hex value?
38,949,574
<p><a href="http://i.stack.imgur.com/eb68s.png" rel="nofollow"><img src="http://i.stack.imgur.com/eb68s.png" alt="enter image description here"></a>I m using Python in Raspberry Pi and my packet is in hexadecimal value like <code>"0x750x010x010x060x000x08"</code>. I want serial communication between UART and Raspberry ...
0
2016-08-15T05:06:46Z
38,949,911
<p>First of all your <code>for</code> loop and <code>if</code> statment are used wrong here, and they are not required. The <code>while</code> loop can be equivently rewriten as:</p> <pre><code>a = "0x750x010x010x060x000x08" b = a.replace("0x", " ") while True: port.write("\r\n"+b) </code></pre> <p>Your main mi...
0
2016-08-15T05:49:13Z
[ "python", "windows", "hex", "putty", "raspberry-pi3" ]
Thread identifier in multiprocessing pool workers
38,949,614
<p>I believed <code>Thread.ident</code> as a unique identifier of threads but now I see different worker processes in <code>multiprocessing.poo.Pool</code> reporting same thread identifier by <code>threading.current_thread().ident</code>. How?</p>
0
2016-08-15T05:12:52Z
38,949,714
<p>Depending on the platform, the ids may or may not be unique. The important thing to note here is that the python multiprocessing library actually uses processes instead of threads for multiprocessing, and so thread ids in between processes is actually a platform-specific implementation detail. </p> <p>On Unix/Linux...
1
2016-08-15T05:25:03Z
[ "python", "multithreading", "multiprocessing", "python-multiprocessing" ]
How to implement a Nadex autotrading bot?
38,949,710
<p>I have been searching for a way to autotrade on Nadex</p> <blockquote> <p><a href="https://www.nadex.com" rel="nofollow">https://www.nadex.com</a></p> </blockquote> <p>and came across this script <a href="https://github.com/FreeTheQuarks/NadexBot" rel="nofollow">https://github.com/FreeTheQuarks/NadexBot</a></p> ...
-1
2016-08-15T05:24:36Z
38,958,186
<h2><strong><code>A1:</code></strong> Measure Twice Rather Before One Cut$</h2> <p>Simply put, it is your money you trade with, so warnings like this one ( from FreeTheQuarks )</p> <blockquote> <p><em>(cit.:</em>)<br><strong>This was the first non-trivial program I wrote.<br>It hasn't received any significant updat...
0
2016-08-15T15:33:20Z
[ "python", "api", "trading", "algorithmic-trading" ]
Openerp Scheduler is working but the attached funciton not executing
38,949,745
<p>I tried to execute a function using Openerp scheduler but it changed nothing. If I run the function only it works perfectly fine but not with the scheduler. Please help me with this.</p> <p>in hr_holidays.xml file I added this,</p> <pre><code>&lt;record id="ir_cron_scheduler" model="ir.cron"&gt; &lt;field ...
0
2016-08-15T05:29:06Z
38,953,768
<p>You just need to set default value for that parameter and no need to pass it via cron, and if it is required in function the pass it from the cron.</p> <pre><code>def allocate_on_probations(self, cr, uid, ids,tl=False, context=None): allo=0 state='active' result = {} emps=self.poo...
1
2016-08-15T10:57:02Z
[ "python", "openerp" ]
AttributeError: 'list' object has no attribute 'astimezone'
38,950,012
<p>My python script: </p> <pre><code>import ftplib import hashlib import httplib import pytz from datetime import datetime import urllib from pytz import timezone import os.path, time import glob def ftphttp(): files = glob.glob('Desktop/images/*.png') ts = map(os.path.getmtime, files) dts = map(datetime.fromtim...
-4
2016-08-15T06:01:50Z
38,950,045
<p>You are trying to call a method on a list of objects, instead of the objects in the list. Try calling the method on the first object instead:</p> <pre><code>localtime = dts[0].astimezone(timeZone).isoformat() </code></pre> <p>Or map over the list to get all timestamps in iso format:</p> <pre><code>localtimes = ma...
1
2016-08-15T06:04:32Z
[ "python", "python-2.7" ]
AttributeError: 'list' object has no attribute 'astimezone'
38,950,012
<p>My python script: </p> <pre><code>import ftplib import hashlib import httplib import pytz from datetime import datetime import urllib from pytz import timezone import os.path, time import glob def ftphttp(): files = glob.glob('Desktop/images/*.png') ts = map(os.path.getmtime, files) dts = map(datetime.fromtim...
-4
2016-08-15T06:01:50Z
38,950,053
<p><code>dts</code> is a list of time zones. So you need to do:</p> <pre><code>[ts.astimezone(timeZone) for ts in dts] </code></pre> <p>This will give you a list of the three time zones</p>
0
2016-08-15T06:05:09Z
[ "python", "python-2.7" ]
matplotlib loaded font appears fade on another machine
38,950,173
<p>I have a python code using matplotlib which appears fine on a centos7 machine but on another centos7 machine, the font appears fade on the axes and legend: <a href="http://i.stack.imgur.com/xuQcx.png" rel="nofollow"><img src="http://i.stack.imgur.com/xuQcx.png" alt="enter image description here"></a></p> <p>My font...
0
2016-08-15T06:19:17Z
38,966,526
<p>I deleted <code>Lato-HairlineItalic.ttf</code> and <code>Lato-Hairline.ttf</code> and then deleted <code>/root/.cache/matplotlib/fontList.cache</code>. It caused matplotlib to pick the other ttf file which is the proper regular form of the font. I still would like to know how matplotlib determines which font is the ...
0
2016-08-16T04:09:15Z
[ "python", "matplotlib" ]
Pump bytes from asyncio StreamReader into a file descriptor
38,950,347
<p>I have a Python function (implemented in C++) that reads from a file descriptor (wrapped in <code>FILE*</code> on the C++ side) and I need to feed the function from an <code>asyncio.StreamReader</code>. Specifically, the reader is the content of a HTTP response: <a href="http://aiohttp.readthedocs.io/en/stable/clien...
3
2016-08-15T06:36:20Z
39,332,188
<p>I got around this issue by using a <code>ThreadPoolExecutor</code> and blocking calls to <code>os.write</code>:</p> <pre><code>(read_fd, write_fd) = os.pipe() task_1 = loop.create_task(pump_bytes_into_fd(write_fd)) task_2 = loop.run_in_executor(executor_1, parse_bytes_from_fd(read_fd)) async def pump_bytes_into_fd...
0
2016-09-05T13:55:57Z
[ "python", "python-asyncio", "aiohttp" ]
mocking an instance method of inner object in python 3.4
38,950,349
<p>I have a class in my code that makes use of a third party library. I would like to mock the instance method of the object that I obtain by calling an instance method of the library class. I am not clear on how to mock the instance method of this inner object. Following is my code:</p> <p>My class:</p> <pre><code>f...
0
2016-08-15T06:36:26Z
38,950,490
<p>Just mock out all of <code>A</code>:</p> <pre><code>@patch('a.A') def test_do_something(self, mock_A): mock_b = mock_A.return_value.get_inner_object.return_value mock_b.do_inner.return_value = 'mocked return value' test_res = self.my_class.do_something() self.assertEqual(test_res, 'mocked return v...
0
2016-08-15T06:49:01Z
[ "python", "unit-testing", "python-3.x", "mocking" ]
Opening file from Docker Container in Python/Django Web App
38,950,376
<p>I have create a docker container which specifies</p> <pre><code>WORKDIR /usr/src/app </code></pre> <p>Inside my Django web app, I try to access</p> <pre><code>file_path = '/usr/src/app/management_app/mock/printable-profile.json' File "/usr/src/app/management_app/urls/__init__.py", line 5, in &lt;module&gt; app_1...
0
2016-08-15T06:38:32Z
38,952,709
<p>Are you mounting /usr/src/app as a volume from the host? If yes, you probably rather run into permission issues, since the host enforces the uid/guid/permissions and if your <strong>python application runs under user X</strong>, but the host defined uid=14 which is noth userX, but also <code>u=r,g=,o=</code> as perm...
0
2016-08-15T09:40:05Z
[ "python", "django", "docker" ]
Error while deploy my django website on heroku
38,950,526
<p>I created a personal portfolio website using django and it also includes a blog. You can see the exact directory listing and source code in my github repository by clicking <a href="https://github.com/ikushum/First-django-website" rel="nofollow">here </a></p> <p>I have the procfile and the requirements.txt files as...
0
2016-08-15T06:52:28Z
38,951,230
<p>Your file is called Procfile.txt. It should be called just Procfile.</p>
0
2016-08-15T07:49:29Z
[ "python", "django", "heroku" ]
Error while deploy my django website on heroku
38,950,526
<p>I created a personal portfolio website using django and it also includes a blog. You can see the exact directory listing and source code in my github repository by clicking <a href="https://github.com/ikushum/First-django-website" rel="nofollow">here </a></p> <p>I have the procfile and the requirements.txt files as...
0
2016-08-15T06:52:28Z
38,951,339
<p>It might be that you made a <code>.txt</code> file instead of a non-extension one or that you named it <code>procfile</code> and not <code>Procfile</code>. Heroku is sensitive about capitalisation.</p>
0
2016-08-15T07:58:48Z
[ "python", "django", "heroku" ]
Panda runtime warning Cannot compare type 'Timestamp' with type 'str', sort order is undefined for incomparable objects
38,950,570
<p>I am currently working on homework 2 for the coursera computational finance.</p> <p>While executing this line:</p> <pre><code>ep.eventprofiler(df_events, d_data, i_lookback=20, i_lookforward=20, s_filename=report_filename, b_market_neutral=True, b_errorbars=True, s_market_sym='SPY') </code>...
1
2016-08-15T06:55:49Z
39,002,578
<p>the trouble is caused by the line:</p> <pre><code>df_rets = df_rets - df_rets[s_market_sym] </code></pre> <p>in these couple of lines:</p> <pre><code>if b_market_neutral == True: df_rets = df_rets - df_rets[s_market_sym] del df_rets[s_market_sym] del df_events[s_market_sym] </code></pre> <p>in <code>...
2
2016-08-17T17:09:46Z
[ "python", "pandas", "computational-finance" ]
Panda runtime warning Cannot compare type 'Timestamp' with type 'str', sort order is undefined for incomparable objects
38,950,570
<p>I am currently working on homework 2 for the coursera computational finance.</p> <p>While executing this line:</p> <pre><code>ep.eventprofiler(df_events, d_data, i_lookback=20, i_lookforward=20, s_filename=report_filename, b_market_neutral=True, b_errorbars=True, s_market_sym='SPY') </code>...
1
2016-08-15T06:55:49Z
39,687,712
<p>@DanielTC thanks for pointing out where the issue was, I can confirm it.</p> <p>i think the logic is that market returns should be subtracted from the individual stocks daily returns, so you are left with just what the stock gained/lost</p> <p>I solved it like this:</p> <pre><code>if b_market_neutral is True: ...
1
2016-09-25T14:06:07Z
[ "python", "pandas", "computational-finance" ]
Have to use sleep with pyserial when opening com port for arduino nano
38,950,613
<p>I'm running pyserial (3.1.1) on Windows 10 with python 2.7</p> <p>Update - get the same issue running on Xubuntu 16 as well as Windows.</p> <p>I'm writing via serial to an arduino nano via usb / serial interface.</p> <p>I'm writing a simple character string (eg. '2+') and reading the output in the arduino. If I k...
0
2016-08-15T07:00:03Z
38,955,216
<p>You're assuming that if there is data, it will be the full data. If there is buffering in how the serial port is handled on the transmitting part, you will get only partial data.</p> <p>You can try and add a <code>ser.flush()</code> in your python code, but you should also check that the data you received is comple...
1
2016-08-15T12:36:39Z
[ "python", "arduino", "pyserial" ]
Have to use sleep with pyserial when opening com port for arduino nano
38,950,613
<p>I'm running pyserial (3.1.1) on Windows 10 with python 2.7</p> <p>Update - get the same issue running on Xubuntu 16 as well as Windows.</p> <p>I'm writing via serial to an arduino nano via usb / serial interface.</p> <p>I'm writing a simple character string (eg. '2+') and reading the output in the arduino. If I k...
0
2016-08-15T07:00:03Z
39,000,160
<p>I was not able to find any way around this sleep issue. The bytes were only received correctly on the arduino if at least 1.5 seconds was allowed - presumably for the serial connection to initialise.</p> <p>As a workaround I had to open the serial port once on startup and then accept and write data through a socket...
0
2016-08-17T15:00:30Z
[ "python", "arduino", "pyserial" ]
How to subtract Sunday from datetime range in python
38,950,676
<p>I have a datetime range in python that adds a bunch of dates to a range, but i can't for the life of me figure out how to subtract Sundays from that list. I know how to count business days and weekends separately, but how do i eliminate JUST Sundays? Here is my formula:</p> <pre><code>days = 100 i = 1 daterange= []...
0
2016-08-15T07:07:19Z
38,950,753
<p>Use <code>datetime.weekday()</code> to exclude Sundays.</p> <pre><code>from datetime import datetime, timedelta days = 100 daterange = [] for i in range(1, 100): yesterday = datetime.now() - timedelta(days=i) if yesterday.weekday() != 6: daterange.append(yesterday.strftime('%m%d%y')) print(*dater...
2
2016-08-15T07:13:34Z
[ "python", "datetime" ]
Send data through get method to a TemplateView in Django
38,950,713
<p>I am using <code>openpyxl</code> to download querysets into .xlsx files, and for that I need to use a TemplateView. I am calling the TemplateView by using JQuery-Ajax, I send a single variable that I need to use as a parameter in my queryset, but I don't know how to use the value of that variable in the TemplateView...
0
2016-08-15T07:11:04Z
38,950,946
<p>You should be able to access your variable via <code>self.request.GET.get('number')</code> in the <code>get_context_data</code> method.</p> <p>Example of template view (Python3 version)</p> <pre><code>class MyTemplateView(TemplateView): template_name = 'path/to/tempplate.html' def get_context_data(self, *...
0
2016-08-15T07:28:48Z
[ "python", "ajax", "django" ]
Carriage return doesnt work properly when redirecting output to file python
38,950,877
<p>I have this simple code in which each iteration is overwriting the output of previous line:</p> <pre><code>import time for i in reversed(range (12)): print i, '\r', time.sleep(0.2) </code></pre> <p>when I run the script using the command: <code>python test.py</code> I see the output is replacing itself eac...
0
2016-08-15T07:22:45Z
38,950,994
<p>You cannot do that because redirection appends data to the end of the file.</p> <p>What's written is written.</p> <p>Edit: BUT there are workarounds.</p> <p><H2>number one: change your python code</H2></p> <pre><code>import time,sys interactive = sys.stdout.isatty() for i in reversed(range (12)): if i==0 o...
1
2016-08-15T07:31:54Z
[ "python", "command-line" ]
Carriage return doesnt work properly when redirecting output to file python
38,950,877
<p>I have this simple code in which each iteration is overwriting the output of previous line:</p> <pre><code>import time for i in reversed(range (12)): print i, '\r', time.sleep(0.2) </code></pre> <p>when I run the script using the command: <code>python test.py</code> I see the output is replacing itself eac...
0
2016-08-15T07:22:45Z
38,952,824
<p>When you run your script from the command line, the terminal interprets the <code>\r</code> character and moves the cursor to the beginning of the line. The actual bytes in the output from your Python script is the same. You can use <code>cat tmp.txt</code> to "replay" the file through the terminal, to achieve muc...
1
2016-08-15T09:47:35Z
[ "python", "command-line" ]
How to implement Swift's or Objective-C's mutable pointers in Python?
38,950,942
<p>The following function requires a "mutable pointer". How do I represent that in Python?</p> <p>Swift:</p> <pre><code>func CGPDFDocumentGetVersion( _ document: CGPDFDocument?, _ majorVersion: UnsafeMutablePointer&lt;Int32&gt;, _ minorVersion: UnsafeMutablePointer&lt;Int32&gt; ) </code></pre> <p>Objective-C:<...
0
2016-08-15T07:28:32Z
38,953,765
<p>You don't need mutable pointers at all. There are two common uses for pointers to <code>int</code> (or similar storage) in C-like code, and Python provides better ways to do both.</p> <h2>Case 1: Multiple return values</h2> <p>A C-like function can't return more than one value without defining a new <code>struct...
1
2016-08-15T10:56:51Z
[ "python", "pointers" ]
Anyone successfully bundled data files into a single file with Pyinstaller?
38,951,047
<p>I have been combing Stack Overflow and the rest of the web on how to add data files into my python application:</p> <pre><code>import Tkinter class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initi...
2
2016-08-15T07:35:22Z
38,965,385
<p>You must specify every data file you want added in your pyinstaller .spec file, or via the command line options (.spec is much easier.) Below is my .spec file,with a "datas" section: </p> <pre><code># -*- mode: python -*- block_cipher = None a = Analysis(['pubdata.py'], pathex=['.', '/interface','/r...
0
2016-08-16T01:32:23Z
[ "python", "windows", "python-2.7", "pyinstaller" ]
Custom Django aggregation for implementing distance method for the MySQL backend
38,951,049
<p>` Hello, everyone! I need to make a distance method for MySQL backend. I found a solution:</p> <pre><code>class DistanceSQL(Aggregate): sql_function = '' sql_template = "(6371 * acos(cos(radians(%(x)s)) * cos(radians(x(core_location.point))) * " \ "cos(radians(y(core_location.point)) - ra...
0
2016-08-15T07:35:30Z
38,951,508
<p>You are basically writing a lot of code to reproduce a tested bit of django that does all this in one line</p> <p><a href="https://docs.djangoproject.com/en/1.10/ref/contrib/gis/geoquerysets/#within" rel="nofollow">within</a></p> <blockquote> <p>Availability: PostGIS, Oracle, MySQL, SpatiaLite, PGRaster (Bilater...
0
2016-08-15T08:11:23Z
[ "python", "mysql", "django", "annotations", "aggregation" ]
Add items to the standard QWebView context menu
38,951,177
<p>The implementation of QWebView has a standard context menu. I want to change it and create my own - or add "Open in new tab" to the standard context menu, and then connect it to my application. How to do it?</p>
0
2016-08-15T07:44:53Z
38,955,525
<p>You can reimplement <code>QWebView.contextMenuEvent</code>:</p> <pre><code>class WebView(QtWebKit.QWebView): def __init__(self, parent=None): super(WebView, self).__init__(parent) self.newTabAction = QtGui.QAction('Open in new tab', self) self.newTabAction.triggered.connect(self.createNe...
1
2016-08-15T12:56:03Z
[ "python", "qt4", "pyqt4", "contextmenu", "qwebview" ]
Numpy sum of values between arrays of indices with a wraparound condition
38,951,193
<p>Given a large numpy array of floats and 2 arrays of indices I'm looking for an elegant way to sum all the values contained between the given indices by following the following rules:</p> <ul> <li>when index1 > index0, summation happens in a straight forward fashion</li> <li>when index1 &lt; index0, summation "wrapa...
1
2016-08-15T07:46:03Z
38,951,435
<p>What about that:</p> <pre><code># store all cumulative sums (adding 0 at the start for the empty sum) cs = np.insert(np.cumsum(values), 0, 0) # then for each indexing get the result in constant time (linear in index0/1 size): result = np.where(index0 &lt; index1, 0, cs[-1]) + cs[index1+1]-cs[index0] </code></pre>...
2
2016-08-15T08:06:12Z
[ "python", "arrays", "numpy" ]
How do I upgrade Stripe for TLS 1.2
38,951,194
<p>I am using the Stripe module for python (via <code>pip install stripe</code>), and I get the following error:</p> <pre><code>AuthenticationError: Request req_90h0QUDIec0Ej7: Stripe no longer supports API requests made with TLS 1.0. Please initiate HTTPS connections with TLS 1.2 or later. You can learn more about ...
1
2016-08-15T07:46:15Z
39,033,241
<p>You can try this You can check the TLS verison running on your server at <a href="https://www.ssllabs.com/ssltest/" rel="nofollow">https://www.ssllabs.com/ssltest/</a></p> <p>if your result displays TLS version 1.2 as NO then you have to update it as per the server you are running. </p>
0
2016-08-19T07:19:40Z
[ "python", "stripe-payments", "tls1.2" ]
Serving number of requests using python HTTPServer
38,951,263
<p>I would like to serve only limited amount of requests using python HTTPServer.</p> <p>Here are a few things about my architecture: I have a client which goes to the server and asks for data. The server (pythonic HTTPServer) has a a list containing data. Each time the client asks for data it gets the next item in th...
0
2016-08-15T07:52:39Z
38,953,699
<p>So you may want to refer this <a href="https://docs.python.org/2/library/basehttpserver.html#more-examples" rel="nofollow">https://docs.python.org/2/library/basehttpserver.html#more-examples</a> You have to define your own <code>keep_running()</code> condition. Below is my sample:</p> <pre><code>import BaseHTTPServ...
0
2016-08-15T10:52:15Z
[ "python", "httpserver" ]
How does Python interpreter allocate memory for different methods?
38,951,319
<p>Can anyone tell me how does Python interpreter or PVM manage memories for the following code?</p> <pre><code>class A(object): class_purpose = "template" def __init__(self): self.a = 0.0 self.b = 0.0 def getParams(self): return self.a, self.b @classmethod def getPurpose(...
1
2016-08-15T07:57:16Z
38,951,398
<p>Everything in your example is simply an object. All objects go on the heap. </p> <p>The class object is created at runtime and has a mapping from attribute name to objects, where all names you defined in the class body are simply attributes. The majority of those objects implement the <a href="https://docs.python.o...
4
2016-08-15T08:03:24Z
[ "python", "python-2.7", "python-internals" ]
How to get rid of multilevel index after using pivot table pandas?
38,951,345
<p>I had following data frame (the real data frame is much more larger than this one ) :</p> <pre><code>sale_user_id sale_product_id count 1 1 1 1 8 1 1 52 1 1 312 5 1 315 1 </...
1
2016-08-15T07:59:27Z
38,951,373
<p>You need remove only <code>index name</code>, use <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#changes-to-rename" rel="nofollow"><code>rename_axis</code></a> (new in <code>pandas</code> <code>0.18.0</code>):</p> <pre><code>print (reshaped_df) sale_product_id 1 8 52 312 315 sale_user_...
2
2016-08-15T08:01:26Z
[ "python", "pandas", "dataframe", "pivot-table", "data-analysis" ]
Baudline : $\tt stdin$ is very slow
38,951,377
<p>I built a radar system with two radars each with I/Q channels. I wrote a nice python script to read in the data from the serial port. The data is interleaved like so:</p> <pre><code>2.4,2.5,2.3,2.7, 2.2,2.1,2.9,3.1, ... </code></pre> <p>The python code is:</p> <pre><code>import serial import binascii import struc...
0
2016-08-15T06:03:11Z
38,955,107
<p>what is "very slow"?</p> <blockquote> <p>ser = serial.Serial('/dev/tty.usbserial-FTT86COK', 9600, bytesize=8, timeout=None)</p> </blockquote> <p>Remember, your input baud rate is 9600, so you're only getting 9600 bytes per second. </p> <p>You seem to use a complex short integer format, i.e. your sample has 4 by...
1
2016-08-15T12:28:40Z
[ "python" ]
Baudline : $\tt stdin$ is very slow
38,951,377
<p>I built a radar system with two radars each with I/Q channels. I wrote a nice python script to read in the data from the serial port. The data is interleaved like so:</p> <pre><code>2.4,2.5,2.3,2.7, 2.2,2.1,2.9,3.1, ... </code></pre> <p>The python code is:</p> <pre><code>import serial import binascii import struc...
0
2016-08-15T06:03:11Z
38,957,848
<p>Add <code>sys.stdout.flush()</code> as the last line in your for loop, like so:</p> <pre><code> import sys ... for i in range(0,10): j=i*4 print str((d[j]/4096.0*5.0)) + ',' print str((d[j+1]-4096)/4096.0*5.0) + ',' print str(d[j+2]/4096.0*5.0) + ',' print str((d[j+3]-4096)/4096.0*5.0) + ',...
0
2016-08-15T15:12:05Z
[ "python" ]
Reading a numpy saved file to a list
38,951,460
<p>from an earlier numpy process I save a list which contains an array. Like this,</p> <pre><code>np.savetxt('CHARS.out', chars, delimiter=',', fmt="%s") </code></pre> <p>And when I try to read the file to a list for a later use using this code,</p> <pre><code>chars = open('chars.out', 'r') chars = np.loadtxt(chars,...
0
2016-08-15T08:08:23Z
38,951,589
<p>You could strip the newline characters:</p> <p>For Python 2.x:</p> <pre><code>strippedChars = map(lambda string: string.strip(), chars) </code></pre> <p>For Python 3.x</p> <pre><code>strippedChars = list(map(lambda string: string.strip(), chars)) </code></pre> <p>Example with your code:</p> <pre><code>np.savet...
1
2016-08-15T08:16:51Z
[ "python", "numpy" ]
Reading a numpy saved file to a list
38,951,460
<p>from an earlier numpy process I save a list which contains an array. Like this,</p> <pre><code>np.savetxt('CHARS.out', chars, delimiter=',', fmt="%s") </code></pre> <p>And when I try to read the file to a list for a later use using this code,</p> <pre><code>chars = open('chars.out', 'r') chars = np.loadtxt(chars,...
0
2016-08-15T08:08:23Z
38,951,979
<p>If you just want to avoid the <code>\n</code> you can use <a class='doc-link' href="http://stackoverflow.com/documentation/python/5265/list-comprehensions#t=201608150846186286074">list comprehension</a> together with <a class='doc-link' href="http://stackoverflow.com/documentation/python/1494/list-slicing-selecting-...
0
2016-08-15T08:45:38Z
[ "python", "numpy" ]
Reading a numpy saved file to a list
38,951,460
<p>from an earlier numpy process I save a list which contains an array. Like this,</p> <pre><code>np.savetxt('CHARS.out', chars, delimiter=',', fmt="%s") </code></pre> <p>And when I try to read the file to a list for a later use using this code,</p> <pre><code>chars = open('chars.out', 'r') chars = np.loadtxt(chars,...
0
2016-08-15T08:08:23Z
38,952,108
<p>First, <code>savetxt</code> saves an array. If you pass a list that contains an array it effectively saves only the array.</p> <p>Second, to read the array back you don't need to open a file but rather supply the file name to <code>genfromtxt</code>, like so:</p> <pre><code>chars = np.genfromtxt('chars.out', delim...
1
2016-08-15T08:55:37Z
[ "python", "numpy" ]
Results Change On Repeated Applications Of PyCluster's K-Medoids
38,951,482
<pre><code>import Pycluster as PC matrix=([ 0. , 1.47, 2.43, 3.44, 1.08], [ 1.47, 0. , 1.5 , 2.39, 2.11], [ 2.43, 1.5 , 0. , 1.22, 2.69], [ 3.44, 2.39, 1.22, 0. , 3.45], [ 1.08, 2.11, 2.69, 3.45, 0.]) cluster,medoids,error=PC.kmedoids(matrix,3) print(cluster) </code></pre> <p>i apply kmedoids o...
-1
2016-08-15T08:09:23Z
38,962,617
<p>K-medoids is a randomized algorithm, so you get different results every time.</p> <p>The cluster number is probably the index of the medoid. Did you look at the source code of pycluster?</p>
0
2016-08-15T20:34:21Z
[ "python", "cluster-analysis" ]
reStructuredText link in Python
38,951,484
<p>If I have the following function in Python:</p> <pre><code>def _add_parameter(self, a): # do something </code></pre> <p>And I want to add a docstring to link to the above function using reStructuredText, I just need to add an underscore at the end of the function name like the following:</p> <pre><code>""" Th...
1
2016-08-15T08:09:32Z
38,958,291
<p>The autodoc extension only documents non private members, i.e. members where the name does not start with an underscore. From the documentation:</p> <pre><code>.. autoclass:: Noodle :members: will document all non-private member functions and properties (that is, those whose name doesn’t start with...
0
2016-08-15T15:41:16Z
[ "python", "python-2.7", "python-3.x", "restructuredtext", "docstring" ]
django rest return result that combines filters
38,951,498
<p>I'm new to Django rest and i'm trying to return response that have to use two query sets: The first one is for the specific project and the second one is only for specific users inside this project:</p> <p>serializers.py</p> <pre><code>class ProjectFiltersSerializer(serializers.ModelSerializer): class Meta: ...
0
2016-08-15T08:10:34Z
38,952,392
<p>You can use Nested Serializer. For more information: <a href="http://www.django-rest-framework.org/api-guide/relations/#nested-relationships" rel="nofollow">http://www.django-rest-framework.org/api-guide/relations/#nested-relationships</a></p>
1
2016-08-15T09:17:10Z
[ "python", "django", "django-models", "django-views", "django-rest-framework" ]
django rest return result that combines filters
38,951,498
<p>I'm new to Django rest and i'm trying to return response that have to use two query sets: The first one is for the specific project and the second one is only for specific users inside this project:</p> <p>serializers.py</p> <pre><code>class ProjectFiltersSerializer(serializers.ModelSerializer): class Meta: ...
0
2016-08-15T08:10:34Z
38,978,252
<p>create a nested serializer (notice it's not a Model Serializer)</p> <pre><code>class ProjectCustomerSerializer(serializers.Serializer): users = UserSerializer(many=True) project = ProjectSerializer() </code></pre> <p>the UserSerializer and ProjectSerializer can be ModelSerializers however. Then in the view...
0
2016-08-16T14:58:15Z
[ "python", "django", "django-models", "django-views", "django-rest-framework" ]
Search CSV for matching field and use initial date
38,951,638
<p>I am attempting to search a CSV file for rows with duplicate device names. The output should record the date from the 1st matching row and also record the date from the last row found. I need some assistance with the logic of removing duplicate device names from the CSV file, whilst also keeping a record of when a d...
1
2016-08-15T08:20:39Z
38,952,084
<p>As Vedang Mehta said in the comments, you could use a dict to store the data.</p> <pre><code> my_dict = {} for i in Input: AlertTime = epoch.mktime(epoch.strptime(i[0], '%d/%m/%Y %H:%M')) if AlertTime &gt; cutoff: #if we have seen this device before, update it if i[1] ...
1
2016-08-15T08:53:32Z
[ "python", "csv", "duplicates" ]
Search CSV for matching field and use initial date
38,951,638
<p>I am attempting to search a CSV file for rows with duplicate device names. The output should record the date from the 1st matching row and also record the date from the last row found. I need some assistance with the logic of removing duplicate device names from the CSV file, whilst also keeping a record of when a d...
1
2016-08-15T08:20:39Z
38,953,681
<p>You can use an <code>OrderedDict</code> to preserve the order that devices are seen in the CSV file. A dictionary is used to automatically remove duplicates. </p> <p>The following works by attempting to update an existing dictionary entry, if it not already present, Python generates a <code>KeyError</code> exceptio...
1
2016-08-15T10:50:19Z
[ "python", "csv", "duplicates" ]
How can python drive selenium to use browser find something in the page(ctrl + F) or hightlight keywords
38,951,717
<p>Now my task is getting some WebPage screen shot . I use python &amp; selenium to achieve it. ShootScreen is finished, but the question is how to highlight keyword, in order to make shootScreen clear. </p> <p>One of my idea is using browser itself function of finding in the page(<kbd>ctrl</kbd> + <kbd>F</kbd>), whic...
0
2016-08-15T08:27:18Z
38,952,025
<p>An expansion of my comment, a sample Python code:</p> <pre><code>from selenium import webdriver broswer = webdriver.Chrome(executable_path='path/to/chromedriver') broswer.get('www.example.com') element = broswer.find_element_by_xpath(r'path/to/required/element') # Or any other selection method available in seleni...
0
2016-08-15T08:49:19Z
[ "python", "selenium", "browser", "highlight" ]
python send email global name 'msg' is not defined
38,951,891
<p>I have a code snippet to send an email in Python. I am getting the error NameError: global name 'msg' is not defined:</p> <pre><code> Traceback (most recent call last): File "E:/test_runners 2 edit project in progress add more tests/selenium_regression_test_5_1_1/Email/email_selenium_report.py", line 32, in ...
0
2016-08-15T08:40:00Z
38,952,224
<p>it seems like you haven't declared your variable <code>msg</code> correctly. I assume you declare it somewhere off the code we're seeing here. but make sure you assign some value to it, even None, in this case though it should be <code>MIMEText(content, "html")</code> for example. as explained in this <a href="http:...
-1
2016-08-15T09:04:54Z
[ "python", "python-2.7" ]
python send email global name 'msg' is not defined
38,951,891
<p>I have a code snippet to send an email in Python. I am getting the error NameError: global name 'msg' is not defined:</p> <pre><code> Traceback (most recent call last): File "E:/test_runners 2 edit project in progress add more tests/selenium_regression_test_5_1_1/Email/email_selenium_report.py", line 32, in ...
0
2016-08-15T08:40:00Z
38,952,353
<p>You forgot to declare <code>msg</code> variable inside <code>send_report_summary_from_htmltestrunner_selenium_report</code> function. You can do it e.g. like this:</p> <pre><code>from email.mime.text import MIMEText msg = MIMEText('body of your message') </code></pre>
1
2016-08-15T09:14:33Z
[ "python", "python-2.7" ]
How to make an option 'All' in django filters when filtering data
38,952,015
<p>I am developing a django application in which I can filter ingredients based on recipes. I am using django filters to give my user filtration options. My filtration dropdown works perfectly fine but I want to add an option 'All', upon submitting which all ingredients should be listed regardless of their recipe.</p> ...
1
2016-08-15T08:48:37Z
39,086,095
<p>This is a known <a href="https://github.com/carltongibson/django-filter/issues/261" rel="nofollow">issue</a>. The workaround is to override the choices for the filter.</p> <pre class="lang-py prettyprint-override"><code>class RecipeFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): s...
0
2016-08-22T18:11:41Z
[ "python", "django", "django-filter" ]
Program doesn't work beyond py2exe
38,952,059
<p>My code is worked well, when I used the raw py file. But when I compiled with py2exe, it will drop an AttributeError:</p> <pre><code>File "test.py", line 1, in &lt;module&gt; import wmi File "&lt;frozen importlib._bootstrap&gt;", line 2237, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line ...
0
2016-08-15T08:51:14Z
39,052,807
<p>Since I did clearly reinstall python 2.7 (and of course the necessary modules), everything works on my windows 10, however on the winpe 10 still did not!</p> <p>I had to add wmi packages to the winpe image, the previous winpe version contains it by default! Now It works on winpe as well. <br/> (I can't understand i...
0
2016-08-20T09:59:43Z
[ "python", "python-2.7", "wmi", "py2exe", "winpe" ]
Why is scrapy crawling a different facebook page?
38,952,089
<p>This is a scrapy spider.This spider is supposed to collect the names of all div nodes with class attribute=5d-5 essentially making a list of all people with x name from y location.</p> <pre><code>import scrapy from scrapy.selector import Selector from scrapy.http import HtmlResponse class fb_spider(scrapy.Spider):...
-2
2016-08-15T08:53:56Z
38,952,155
<p>Facebook is redirecting the request to the new url. </p>
0
2016-08-15T08:59:56Z
[ "python", "facebook", "scrapy" ]
Why is scrapy crawling a different facebook page?
38,952,089
<p>This is a scrapy spider.This spider is supposed to collect the names of all div nodes with class attribute=5d-5 essentially making a list of all people with x name from y location.</p> <pre><code>import scrapy from scrapy.selector import Selector from scrapy.http import HtmlResponse class fb_spider(scrapy.Spider):...
-2
2016-08-15T08:53:56Z
38,952,168
<p>it seems as though you are missing some headers in your request.</p> <pre><code>2016-08-15 14:00:14 [scrapy] ERROR: Spider error processing &lt;GET https://www.facebook.com/search/top/?q=jaslyn%20california&gt; (referer: None) </code></pre> <p>as you can see the referer is None, I would advise you add some headers...
0
2016-08-15T09:00:42Z
[ "python", "facebook", "scrapy" ]
Why is scrapy crawling a different facebook page?
38,952,089
<p>This is a scrapy spider.This spider is supposed to collect the names of all div nodes with class attribute=5d-5 essentially making a list of all people with x name from y location.</p> <pre><code>import scrapy from scrapy.selector import Selector from scrapy.http import HtmlResponse class fb_spider(scrapy.Spider):...
-2
2016-08-15T08:53:56Z
38,952,587
<p>Scraping is not allowed on Facebook: <a href="https://www.facebook.com/apps/site_scraping_tos_terms.php" rel="nofollow">https://www.facebook.com/apps/site_scraping_tos_terms.php</a></p> <p>If you want to get data from Facebook, you have to use their Graph API. For example, this would be the API to search for users:...
1
2016-08-15T09:30:50Z
[ "python", "facebook", "scrapy" ]
How to trasfer a string to DataFrame
38,952,135
<p>I have a list like the below following:</p> <pre><code>a= [['LSJW26760ES050487,2016-04-29,00:40:1,3'],['LSJW26760ES050487,2016-04-29,00:40:1,2'],['LSJW26760ES050487,2016-04-29,00:45:1,3'],['LSJW26760ES050487,2016-04-29,00:40:1,4'],.....] </code></pre> <p>how can I read it in pandas as DataFrame:</p> <pre><code> ...
0
2016-08-15T08:57:44Z
38,952,208
<p><code>pandas.DataFrame()</code> can construct a dataframe from a list of lists. The only preprocessing step you need to do is to convert the string into a list, you can do that using <code>"string".split(",")</code>. Here is a working example: </p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; a= [['LS...
0
2016-08-15T09:03:46Z
[ "python", "pandas", "dataframe" ]
How to trasfer a string to DataFrame
38,952,135
<p>I have a list like the below following:</p> <pre><code>a= [['LSJW26760ES050487,2016-04-29,00:40:1,3'],['LSJW26760ES050487,2016-04-29,00:40:1,2'],['LSJW26760ES050487,2016-04-29,00:45:1,3'],['LSJW26760ES050487,2016-04-29,00:40:1,4'],.....] </code></pre> <p>how can I read it in pandas as DataFrame:</p> <pre><code> ...
0
2016-08-15T08:57:44Z
38,952,213
<p>You need first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a> for spliting by <code>,</code> and then convert columns:</p> <pre><code>import pandas as pd a= [['LSJW26760ES050487,2016-04-29,00:40:1,3'], ['LSJW26760ES050487,2...
0
2016-08-15T09:04:13Z
[ "python", "pandas", "dataframe" ]
How to trasfer a string to DataFrame
38,952,135
<p>I have a list like the below following:</p> <pre><code>a= [['LSJW26760ES050487,2016-04-29,00:40:1,3'],['LSJW26760ES050487,2016-04-29,00:40:1,2'],['LSJW26760ES050487,2016-04-29,00:45:1,3'],['LSJW26760ES050487,2016-04-29,00:40:1,4'],.....] </code></pre> <p>how can I read it in pandas as DataFrame:</p> <pre><code> ...
0
2016-08-15T08:57:44Z
38,952,435
<p>This is a Python 3 code, using <code>np.genfromtxt</code> to create an array using a comma delimiter:</p> <pre><code>import numpy as np import pandas as pd from io import BytesIO a= [['LSJW26760ES050487,2016-04-29,00:40:1,3'],['LSJW26760ES050487,2016-04- 29,00:40:1,2']] data = [np.genfromtxt(BytesIO(item[0].encode...
1
2016-08-15T09:19:42Z
[ "python", "pandas", "dataframe" ]
How to share an instance variable among different classes in Python
38,952,287
<p>Suppose I have a class <code>Game</code> with attributes <code>player1</code>, <code>player2</code>, and <code>Q</code>. <code>player1</code> and <code>player2</code> are themselves instances of the class <code>Player</code> which also has an attribute called <code>Q</code>. I would like to make it such that when I ...
0
2016-08-15T09:10:07Z
38,952,461
<p>You can introduce base class with <code>Q</code> as a class attribute:</p> <pre><code>class Base(object): Q = {} class Player(Base): def __init__(self, mark): self.mark = mark class Game(Base): def __init__(self, player1, player2): self.player1 = player1 self.player2 = player...
0
2016-08-15T09:21:58Z
[ "python" ]
How to share an instance variable among different classes in Python
38,952,287
<p>Suppose I have a class <code>Game</code> with attributes <code>player1</code>, <code>player2</code>, and <code>Q</code>. <code>player1</code> and <code>player2</code> are themselves instances of the class <code>Player</code> which also has an attribute called <code>Q</code>. I would like to make it such that when I ...
0
2016-08-15T09:10:07Z
38,952,708
<p>Following <a href="http://stackoverflow.com/users/1222951/rawing">Rawing</a>'s comment, I used <code>self.Q = self.player1.Q = self.player2.Q = {}</code> in the <code>__init__</code> of <code>Game</code>:</p> <pre><code>class Game: def __init__(self, player1, player2): self.player1 = player1 sel...
0
2016-08-15T09:40:03Z
[ "python" ]
Create zipfile: TypeError: object of type 'ElementTree' has no len()
38,952,412
<p>I'm writing a xml data to the zip.</p> <pre><code>from xml.etree.ElementTree import Element, SubElement, ElementTree from zipfile import ZipFile def create_tree(): root = Element("root") doc = SubElement(root, "doc") SubElement(doc, "field", name="blah").text = "text" return ElementTree(root) de...
-1
2016-08-15T09:18:26Z
38,952,521
<p>Write the element into a fake file (a buffer)</p> <pre><code>from xml.etree.ElementTree import Element, SubElement, ElementTree from zipfile import ZipFile from io import BytesIO def create_tree(): root = Element("root") doc = SubElement(root, "doc") SubElement(doc, "field", name="blah").text = "text" ...
1
2016-08-15T09:26:08Z
[ "python", "xml", "elementtree", "zipfile" ]
Paypal Rest API keeps returning malformed json error
38,952,451
<p>I am trying to create payment using <code>paypal</code> Rest API, but I keep getting this error response:</p> <pre><code>{"name":"MALFORMED_REQUEST","message":"The request JSON is not well formed.","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST","debug_id":"262cbdc417...
1
2016-08-15T09:21:28Z
38,961,784
<p>Your <em>return_url</em> and <em>cancel_url</em> values need to have quotes around them. As the message says, your JSON is malformed.</p> <p>Try this - <a href="http://jsonlint.com/" rel="nofollow">http://jsonlint.com/</a> to see your errors.</p>
0
2016-08-15T19:33:49Z
[ "python", "api", "rest", "paypal" ]
pycharm project files have disappeared
38,952,539
<p>I was working on a python project in <a href="https://www.jetbrains.com/pycharm/" rel="nofollow">JetBrains PyCharm 2016.2</a> on Lubuntu and all of a sudden, all my project files have disappeared from the IDE.</p> <p>I have tried the following with no success:</p> <ol> <li><p>Exit PyCharm, navigate to project root...
0
2016-08-15T09:27:43Z
38,956,261
<p>Try this: Go to <code>File -&gt; Open recent</code> you should see a list of your recent projects there. If you still don't see it there then just reopen the project by going to <code>File -&gt; Open</code> and go to the location where you saved your project. </p>
1
2016-08-15T13:44:50Z
[ "python", "linux", "ide", "pycharm" ]
pycharm project files have disappeared
38,952,539
<p>I was working on a python project in <a href="https://www.jetbrains.com/pycharm/" rel="nofollow">JetBrains PyCharm 2016.2</a> on Lubuntu and all of a sudden, all my project files have disappeared from the IDE.</p> <p>I have tried the following with no success:</p> <ol> <li><p>Exit PyCharm, navigate to project root...
0
2016-08-15T09:27:43Z
38,969,749
<p>Ok so I have found the issue, which turned out to be indirect in the end. I just installed the latest updates for Lubuntu, restarted the PC, then opened PyCharm and like magic all my project files are now visible!</p> <p>I know it was not just the restart because I had already tried that. So it must have been one o...
0
2016-08-16T08:13:14Z
[ "python", "linux", "ide", "pycharm" ]
How to load csv files in a tensorflow program?
38,952,554
<p>I am working on a deep neural network by following the tensorflow tutorial on convolutional neural nets. But the dataset i have is in the form of csv files. I have 4 csv files 2 for training(xtrain.csv and ytrain.csv) and 2 for testing(xtest.csv and ytest.csv). xtrain.csv and xtest.csv contain the inputs with 1280 r...
0
2016-08-15T09:29:24Z
38,958,349
<p>Tensorflow has a function below that seems like would do it.</p> <pre><code>tf.decode_csv(records, record_defaults, field_delim=None, name=None) </code></pre> <p>You can use this to load your data into a tensor. From there you just need to convert the tensor to the correct shape.</p> <pre><code>imgs = tf.decode_c...
0
2016-08-15T15:45:24Z
[ "python", "csv", "image-processing", "tensorflow", "conv-neural-network" ]
Avoid `logger=logging.getLogger(__name__)` without loosing way to filter logs
38,952,681
<p>I am lazy and want to avoid this line in every python file which uses logging:</p> <pre><code>logger = logging.getLogger(__name__) </code></pre> <p>In january I asked how this could be done, and found an answer: <a href="http://stackoverflow.com/questions/34726515/avoid-logger-logging-getlogger-name">Avoid `logger...
-3
2016-08-15T09:38:16Z
38,967,311
<p>Think well if you really want to do this.</p> <p>Create a Module e.g. <code>magiclog.py</code> like this:</p> <pre><code>import logging import inspect def L(): # FIXME: catch indexing errors callerframe = inspect.stack()[1][0] name = callerframe.f_globals["__name__"] # avoid cyclic ref, see https:...
1
2016-08-16T05:37:54Z
[ "python", "logging" ]
Avoid `logger=logging.getLogger(__name__)` without loosing way to filter logs
38,952,681
<p>I am lazy and want to avoid this line in every python file which uses logging:</p> <pre><code>logger = logging.getLogger(__name__) </code></pre> <p>In january I asked how this could be done, and found an answer: <a href="http://stackoverflow.com/questions/34726515/avoid-logger-logging-getlogger-name">Avoid `logger...
-3
2016-08-15T09:38:16Z
39,064,783
<blockquote> <p>I am lazy and want to avoid this line in every python file which uses logging:</p> <pre><code>logger = logging.getLogger(__name__) </code></pre> </blockquote> <p>Well, it's the recommended way:</p> <blockquote> <p>A good convention to use when naming loggers is to use a module-level logger, i...
1
2016-08-21T13:34:34Z
[ "python", "logging" ]
Python pandas extract, how to extract remaining part of string
38,952,809
<p>I have looked for hours and this should be simple. I am trying to extract all the letters from a string with a mixture or digits and letters. Here is an example:</p> <pre><code>df = pd.Series(['ENGLANDSR11SW']) df = df.to_frame('column') df['ValueAfterExtract'] = df['column'].str.extract("(?P&lt;letter&gt;[a-zA-Z]+...
0
2016-08-15T09:46:38Z
38,952,846
<p>Replace all digits (<code>\d</code>) with empty strings:</p> <pre><code>In [6]: df['column'].str.replace(r'\d', '') Out[10]: 0 ENGLANDSRSW Name: column, dtype: object </code></pre> <p>Or, to remove everything which is not in <code>[a-zA-Z]</code> use the regexp <code>[^a-zA-Z]</code>. This would remove, for in...
3
2016-08-15T09:49:00Z
[ "python", "pandas", "extract" ]
how to convert a 1-dimensional image array to PIL image in Python
38,952,853
<p>My question is related to a <a href="https://www.kaggle.com/c/digit-recognizer/data" rel="nofollow">Kaggle data science competition</a>. I'm trying to read an image from a one-dimensional array containing <strong>1-bit grayscale</strong> pixel information (<strong>0 to 255)</strong> for an <strong>28x28 image</stron...
1
2016-08-15T09:49:29Z
38,953,115
<p>You can convert a NumPy array to PIL image using <code>Image.fromarray</code>:</p> <pre><code>import numpy as np from PIL import Image arr = np.random.randint(255, size=(28*28)) img = Image.fromarray(arr.reshape(28,28), 'L') </code></pre> <p><code>L</code> mode indicates the array values represent luminance. The...
2
2016-08-15T10:07:27Z
[ "python", "image", "numpy", "matplotlib", "python-imaging-library" ]
Python string concatenation and equivalent of bash parameter expansion
38,952,979
<p>I'm kind of new to python, but something I find myself doing in bash a lot is prepending and appending strings to filenames with parameter expansion.</p> <p>e.g.</p> <pre><code>for file in *.txt ; do mkdir ${file%.*} ; mv $file ${file%.*}/ ; done </code></pre> <p>Would be an example for stripping off the extensio...
0
2016-08-15T09:58:05Z
38,953,177
<p>You can use <code>os.path.splitext</code> which is build especially for file names:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; &gt;&gt;&gt; fname = '/tmp/foo/bar.baz' &gt;&gt;&gt; sp = os.path.splitext(fname) &gt;&gt;&gt; sp ('/tmp/foo/bar', '.baz') </code></pre> <p>Extracting the name of the file without...
1
2016-08-15T10:11:20Z
[ "python", "string", "bash", "biopython" ]
Connect to a Bluetooth LE device using bluez python dbus interface
38,953,175
<p>I would like to connect to a Bluetooth LE device and receive notifications from it in python. I would like to use the Bluez dbus API, but can't find an example I can understand. :-)</p> <p>With gatttool, I can use the following command:</p> <p>gatttool -b C4:8D:EE:C8:D2:D8 --char-write-req -a 0x001d -n 0100 –lis...
1
2016-08-15T10:11:17Z
38,997,649
<p>See 'test/example-gatt-client' from bluez package</p>
1
2016-08-17T13:11:13Z
[ "python", "dbus", "bluez", "gatt" ]
How to integrate django countries in to an existing model
38,953,242
<p>I have an existing countries class in a database in production but would like to use the Django_Countries model to update all the countries I use.</p> <p>Here is the existing model. It allows users create a country and upload a flag of their country</p> <pre><code>class Country(models.Model): name = models.Cha...
0
2016-08-15T10:17:12Z
38,971,232
<p>Finally ended up just doing a dump of the countries in to a json file and writing a migration to update the database. </p> <pre><code>def forwards(apps, schema_editor): Country = apps.get_model('country', 'Country') Region = apps.get_model('country', 'Region') Region.objects.filter(id=45).delete() ...
0
2016-08-16T09:28:48Z
[ "python", "django", "django-models", "django-countries" ]
Django Filter Objects and Get First Corresponding Values
38,953,245
<p>I have two models.</p> <pre><code>class House(models.Model): name= models.Charfield(max_length=100) city= models.Charfield(max_length=100) area= models.CharField(max_length=200) country=models.CharField(max_length=30) class HouseRooms(models.Model): room_name=models.Charfield(max_length=200) ...
0
2016-08-15T10:17:25Z
38,954,126
<p>You shouldn't query HouseRooms explicitly in the view. Instead, you can use the reverse relationship accessor inside your iteration in the template itself.</p> <pre><code>{% for m in rms %} &lt;p&gt; Name: {{ m.name }} &lt;/p&gt; {% with m.house_hr.first as sd %} {% if sd %} &lt;p&gt; price: {{ sd.roo...
2
2016-08-15T11:21:36Z
[ "python", "django" ]
Certbot fails to run on CentOS 6 server
38,953,248
<p>I'm having some issues running the <code>certbot-auto</code> application on a CentOS 6 server, which has both Python 2.6 (<code>/usr/bin/python</code>) and 2.7 (<code>/usr/bin/python2.7</code>) installed.</p> <p>A copy of the output from running <code>./certbot-auto</code> with no arguments can be found in this pas...
-1
2016-08-15T10:17:36Z
38,953,568
<p>Managed to solve the issue, the development dependencies for Python 2.7 were missing. Fix by running <code>yum install python27-devel</code>.</p>
0
2016-08-15T10:41:29Z
[ "python", "linux", "centos", "centos6", "lets-encrypt" ]
What’s the equivalent of rsplit() with re.split()?
38,953,278
<p><a href="https://docs.python.org/2/library/stdtypes.html#str.rsplit" rel="nofollow"><code>rsplit()</code></a> starts splitting at the end of the string. How can I start splitting at the end of the string when using <a href="https://docs.python.org/2/library/re.html#re.split" rel="nofollow"><code>re.split()</code></a...
2
2016-08-15T10:19:49Z
38,953,526
<p>There is no need to split if you just want the last one.</p> <pre><code>match = re.search(r'[^!?]*$', splitme) if match: return match.group(0) </code></pre>
0
2016-08-15T10:38:17Z
[ "python", "regex" ]
How do you plot the total summation of harmonics in python
38,953,369
<p>I am using the below manual method so as to plot the summation of harmonics. The below method is working fine.Please refer the image below.When the same thing implemented in for loop,it is not working as desired.The for loop is meant to take care of n number of harmonic values.Could any help me in this?</p> <pre><c...
0
2016-08-15T10:26:25Z
38,953,504
<p>Do you mean something like that?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x=np.linspace(0,2*np.pi,2000) y = [0 for _ in x] def Harmonic(i): global y global x for n in range(0,i): y += np.sin((2*n+1)*(2*np.pi)*(x))/(2*n+1) Harmonic(5) plt.plot(x,y) plt.grid() plt.show(...
1
2016-08-15T10:36:23Z
[ "python", "numpy", "matplotlib" ]
How do you plot the total summation of harmonics in python
38,953,369
<p>I am using the below manual method so as to plot the summation of harmonics. The below method is working fine.Please refer the image below.When the same thing implemented in for loop,it is not working as desired.The for loop is meant to take care of n number of harmonic values.Could any help me in this?</p> <pre><c...
0
2016-08-15T10:26:25Z
38,953,660
<p>Here's a working example for you with a little bit of refactoring:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def first_solution(N=2000): w = 2 * np.pi x = np.linspace(0, w, N) y1 = np.sin(1 * w * x) / 1 y2 = np.sin(3 * w * x) / 3 y3 = np.sin(5 * w * x) / 5 y4 = np....
2
2016-08-15T10:48:46Z
[ "python", "numpy", "matplotlib" ]
How do you plot the total summation of harmonics in python
38,953,369
<p>I am using the below manual method so as to plot the summation of harmonics. The below method is working fine.Please refer the image below.When the same thing implemented in for loop,it is not working as desired.The for loop is meant to take care of n number of harmonic values.Could any help me in this?</p> <pre><c...
0
2016-08-15T10:26:25Z
38,953,774
<p>If the goal was to see the impact of increasing the number of harmonics in "real time", you should use <code>FuncAnimation</code></p> <pre><code>fig,ax = plt.subplots() x=np.linspace(0,2*np.pi,2000) y=np.zeros((2000,)) l, = ax.plot(x,y) def initPlot(): ax.set_xlim(0,2*np.pi) ax.set_ylim(-1,1) l, = ax.p...
3
2016-08-15T10:57:29Z
[ "python", "numpy", "matplotlib" ]
Python - self-referencing class (Vector addition using magic operators)
38,953,411
<p>I'm having trouble understanding how the self-reference for this class works in this code:</p> <pre><code>class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y) first = Vector2D(5, 7) second = Vector2D(3, 9) resu...
2
2016-08-15T10:29:21Z
38,953,461
<blockquote> <p>the argument <code>other</code> refers to <code>second</code>, right?</p> </blockquote> <p>Correct. You can verify that with a <code>print</code> inside <code>__add__</code>:</p> <pre><code>class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): pr...
1
2016-08-15T10:32:50Z
[ "python", "class", "python-3.x", "magic-methods" ]
Python - self-referencing class (Vector addition using magic operators)
38,953,411
<p>I'm having trouble understanding how the self-reference for this class works in this code:</p> <pre><code>class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y) first = Vector2D(5, 7) second = Vector2D(3, 9) resu...
2
2016-08-15T10:29:21Z
38,953,467
<p>Yes, this is equivalent to:</p> <pre><code>result = first.__add__(second) </code></pre> <p>so:</p> <ol> <li><code>self</code> is <code>first</code></li> <li><code>other</code> is <code>second</code></li> <li><code>result</code> is the new <code>Vector2D</code></li> </ol>
3
2016-08-15T10:33:09Z
[ "python", "class", "python-3.x", "magic-methods" ]
Python - self-referencing class (Vector addition using magic operators)
38,953,411
<p>I'm having trouble understanding how the self-reference for this class works in this code:</p> <pre><code>class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y) first = Vector2D(5, 7) second = Vector2D(3, 9) resu...
2
2016-08-15T10:29:21Z
38,953,468
<p>Yes, <code>other</code> is the right-hand-side expression result, <code>second</code> in your case.</p> <p>From the <a href="https://docs.python.org/3/reference/datamodel.html#object.__add__" rel="nofollow"><code>object.__add__()</code> documentation</a>:</p> <blockquote> <p>For instance, to evaluate the express...
1
2016-08-15T10:33:10Z
[ "python", "class", "python-3.x", "magic-methods" ]
CSV.Reader importing a list of lists
38,953,527
<p>I am running the following on a csv of UIDs:</p> <pre><code>with open('C:/uid_sample.csv',newline='') as f: reader = csv.reader(f,delimiter=' ') uidlist = list(reader) </code></pre> <p>but the list returned is actually a list of lists:</p> <pre><code>[['27465307'], ['27459855'], ['27451353']...] </code></...
0
2016-08-15T10:38:17Z
38,957,305
<p>A CSV file is a file where each line, or row, contains columns that are usually delimited by commas. In your case, you told <code>csv.reader()</code> that your columns are delimited by a space. Since there aren't any spaces in any of the lines, each row of the <code>csv.reader</code> object has only one item. The ...
1
2016-08-15T14:42:16Z
[ "python", "list", "csv" ]
Why does value_counts not show all values present?
38,953,532
<p>I am using pandas 0.18.1 on a large dataframe. I am confused by the behaviour of <code>value_counts()</code>. This is my code:</p> <pre><code>print df.phase.value_counts() def normalise_phase(x): print x return int(str(x).split('/')[0]) df['phase_normalised'] = df['phase'].apply(normalise_phase) </code></pr...
1
2016-08-15T10:38:44Z
38,953,589
<p>You need to pass <code>dropna=False</code> for NaNs to be tallied (see the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow">docs</a>). <code>int64</code> is the dtype of the series (counts of the values). The values themselves are the index. dtype of the ...
3
2016-08-15T10:42:49Z
[ "python", "pandas" ]
codecs.open create txt file in specific path Python
38,953,533
<p>i have this code but it saves the files in the same path of .py file, how can i do to create txt files in specific folder?</p> <pre><code>f = codecs.open("gabili" + '.txt', mode="w", encoding="utf-16") reload(sys) sys.setdefaultencoding('utf8') f.write(u"[HELLO] *ASDASD* /(&amp;) \n") </code></pre>
0
2016-08-15T10:38:50Z
38,953,726
<p>The <a href="https://docs.python.org/3/library/codecs.html?#codecs.open" rel="nofollow"><code>codecs.open</code></a> fonction takes a <em>filename</em> parameter. This <em>filename</em> can be a file name or a full path. So, you can use <code>"/full/path/to/gabili.txt"</code>.</p> <p>To build a full path, you can u...
1
2016-08-15T10:54:27Z
[ "python", "file", "text" ]
Plotting 2 variables with a heat map
38,953,668
<p>I'm on the python 3 and I have two variables x and y, where x ranges from 1 to 5 and y from 0.03 to 0.7 and I then have a method that takes x and y and generates a scalar number. I want to create a heat map type plot with x as the x-axis and y as the y axis and a colour key to represent the method f(x,y). How is thi...
2
2016-08-15T10:49:09Z
39,917,631
<p>Lets say <code>z = f(x, y)</code>. Your heatmap's key is able to represent one dimension only (usually that would be <em>z</em>). What do you mean by </p> <blockquote> <p>represent the method f(x,y)</p> </blockquote> <p>For 2-dimensional plotting, you would need a 3-dimensional heatmap.</p>
0
2016-10-07T12:44:18Z
[ "python", "plot", "heatmap" ]
Plotting 2 variables with a heat map
38,953,668
<p>I'm on the python 3 and I have two variables x and y, where x ranges from 1 to 5 and y from 0.03 to 0.7 and I then have a method that takes x and y and generates a scalar number. I want to create a heat map type plot with x as the x-axis and y as the y axis and a colour key to represent the method f(x,y). How is thi...
2
2016-08-15T10:49:09Z
39,919,592
<p>If you start with 2 mono-dimensional vectors, <code>x</code> and <code>y</code> to compute a function of <code>x</code> and <code>y</code> on a grid of 2D points you have first to generate said 2D grid, using <code>numpy.meshgrid</code>.</p> <pre><code>from numpy import linspace, meshgrid x, y = linspace(1, 5, 41)...
1
2016-10-07T14:24:49Z
[ "python", "plot", "heatmap" ]
Convert list of NaNs and strings to int?
38,953,704
<p>I have the following list in Python:</p> <pre><code>mylist = [float('NaN'), u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] </code></pre> <p>I want to convert everything to an int. I want the strings with a slash in to take the first value.</p> <p>This is what I've tried:</p> <pre><code>newlist = [int(str(x).split...
1
2016-08-15T10:52:28Z
38,953,967
<p>You can use the isnan function in the maths library to check if a float is NaN, however it takes float as an argument, so you'll have to first convert your items into float. You can choose whether to skip the NaN, or save them as some default value. In the code below the NaN's are saved as int 0</p> <pre><code>impo...
1
2016-08-15T11:09:49Z
[ "python" ]
Convert list of NaNs and strings to int?
38,953,704
<p>I have the following list in Python:</p> <pre><code>mylist = [float('NaN'), u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] </code></pre> <p>I want to convert everything to an int. I want the strings with a slash in to take the first value.</p> <p>This is what I've tried:</p> <pre><code>newlist = [int(str(x).split...
1
2016-08-15T10:52:28Z
38,954,085
<p>We know, that <strong>NaN is always != NaN</strong>.<br> Use the following approach <em>to convert everything to integer</em>:</p> <pre><code>mylist = [float('NaN'), u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] newList = [0 if (not item or (item != item)) else int(str(item).split('/')[0]) for item in mylist] pri...
0
2016-08-15T11:18:39Z
[ "python" ]
Convert list of NaNs and strings to int?
38,953,704
<p>I have the following list in Python:</p> <pre><code>mylist = [float('NaN'), u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] </code></pre> <p>I want to convert everything to an int. I want the strings with a slash in to take the first value.</p> <p>This is what I've tried:</p> <pre><code>newlist = [int(str(x).split...
1
2016-08-15T10:52:28Z
38,954,158
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.isnull.html" rel="nofollow"><code>pandas.isnull</code></a>:</p> <pre><code>import pandas as pd import numpy as np mylist = [np.nan, u'2', u'3', u'1', u'4', u'1/2', u'2/3', u'0'] newList = [0 if pd.isnull(item) else int(str...
0
2016-08-15T11:24:12Z
[ "python" ]
Python - Best way to lookup values in a table-like scheme
38,953,748
<p>I have a client who wants a way to calculate shipping costs. It's calculated by weight and kilometer (not linear unfortunately). It looks like this:</p> <pre><code>| | To 50km | To 100km | To 150km | To 200km | |------- |--------- |---------- |---------- |---------- | | 10kg | 84€ | ...
-3
2016-08-15T10:56:04Z
38,956,266
<p>So if anyone is wondering. I did it like this:</p> <pre><code>def calc_shipping_cost(weight, kilometer): WEIGHT_BREAKPOINTS = [10, 20, 40, 60, 80, 100, 500] KILOMETER_BREAKPOINTS = [50, 100, 150, 200, 999] prices = [ [84.85, 95.15, 104.45, 116.70, 122.25], [98.65, 108.45, 117.20, 127.9...
0
2016-08-15T13:45:01Z
[ "python" ]
Python - Best way to lookup values in a table-like scheme
38,953,748
<p>I have a client who wants a way to calculate shipping costs. It's calculated by weight and kilometer (not linear unfortunately). It looks like this:</p> <pre><code>| | To 50km | To 100km | To 150km | To 200km | |------- |--------- |---------- |---------- |---------- | | 10kg | 84€ | ...
-3
2016-08-15T10:56:04Z
38,962,163
<p>I agree that this question can be considered off-topic, but, for once, it's a real-world problem to solve, not a student question.</p> <p>Unfortunately, the solution you gave is wrong: you only consider that you could havethe “breakpoints” values. If you give different <em>weight</em> (for instance 21) or <em>k...
0
2016-08-15T19:59:32Z
[ "python" ]
returning the element in one list based on the index and maximum value of an element in another list
38,953,807
<p>I have a list of lists which I converted into a numpy array:</p> <pre><code>lsts = ([[1,2,3], ['a','b','a']], [[4,5,6,7], ['a','a','b','b']], [[1,2,3],['b','a','b']]) np_lsts = np.array(lsts) </code></pre> <p>I want to return the largest element in the first list where a 'b' occurs in the second ...
0
2016-08-15T10:58:47Z
38,953,901
<p>That will do:</p> <pre><code>[max(u for u,v in zip(x,y) if v=='b') for x,y in lsts if 'b' in y] </code></pre> <p>Using <a href="https://docs.python.org/3.5/library/functions.html#zip" rel="nofollow"><code>zip()</code></a> and <a href="https://docs.python.org/3.5/library/functions.html#max" rel="nofollow"><code>max...
1
2016-08-15T11:05:58Z
[ "python", "numpy" ]
returning the element in one list based on the index and maximum value of an element in another list
38,953,807
<p>I have a list of lists which I converted into a numpy array:</p> <pre><code>lsts = ([[1,2,3], ['a','b','a']], [[4,5,6,7], ['a','a','b','b']], [[1,2,3],['b','a','b']]) np_lsts = np.array(lsts) </code></pre> <p>I want to return the largest element in the first list where a 'b' occurs in the second ...
0
2016-08-15T10:58:47Z
38,953,940
<p>One possible solution to your problem:</p> <pre><code>lsts = ([[1, 2, 3], ['a', 'b', 'a']], [[4, 5, 6, 7], ['a', 'a', 'b', 'b']], [[1, 2, 3], ['b', 'a', 'b']], [[1, 2, 3], ['a']] ) result = [] for l in lsts: indices = [l[0][index] for index, v in enumerate(l[1]) if v == 'b'] ...
1
2016-08-15T11:08:21Z
[ "python", "numpy" ]
returning the element in one list based on the index and maximum value of an element in another list
38,953,807
<p>I have a list of lists which I converted into a numpy array:</p> <pre><code>lsts = ([[1,2,3], ['a','b','a']], [[4,5,6,7], ['a','a','b','b']], [[1,2,3],['b','a','b']]) np_lsts = np.array(lsts) </code></pre> <p>I want to return the largest element in the first list where a 'b' occurs in the second ...
0
2016-08-15T10:58:47Z
38,953,999
<pre><code>def get_max(l): first = True for e1, e2 in zip(l[0], l[1]): if e2 == 'b' and first: max = e1 first = False elif e2 == 'b' and e1 &gt; max: max = e1 return max result = () for l in lsts: if 'b' in l[1]: result += (get_max(l),) print(...
0
2016-08-15T11:12:01Z
[ "python", "numpy" ]
returning the element in one list based on the index and maximum value of an element in another list
38,953,807
<p>I have a list of lists which I converted into a numpy array:</p> <pre><code>lsts = ([[1,2,3], ['a','b','a']], [[4,5,6,7], ['a','a','b','b']], [[1,2,3],['b','a','b']]) np_lsts = np.array(lsts) </code></pre> <p>I want to return the largest element in the first list where a 'b' occurs in the second ...
0
2016-08-15T10:58:47Z
38,954,070
<p>The following function returns a <code>result</code> list. If needed, you could return a tuple instead of a list.</p> <pre><code>def maxNum(lsts, character): result = [] for entry in lsts: if character in entry[1]: result.append(max(entry[0])) return result # lsts = ... # (put lsts ...
1
2016-08-15T11:17:37Z
[ "python", "numpy" ]