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 to get matplotlib to place lines accurately?
39,183,658
<p>By default, matplotlib plot can place lines very inaccurately.</p> <p>For example, see the placement of the left endpoint in the attached plot. There's at least a whole pixel of air that shouldn't be there. In fact I think the line center is 2 pixels off.</p> <p>How to get matplotlib to draw <strong>accurately</strong>? I don't mind if there is some performance hit.</p> <p>Inaccurately rendered line in matplotlib plot:</p> <p><a href="http://i.stack.imgur.com/siGbJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/siGbJ.png" alt="inaccurately rendered line in matplotlib plot"></a></p> <p>Inaccurately rendered line in matplotlib plot - detail magnified:</p> <p><a href="http://i.stack.imgur.com/luXjK.png" rel="nofollow"><img src="http://i.stack.imgur.com/luXjK.png" alt="inaccurately rendered line in matplotlib plot - detail magnified"></a></p> <p>This was made with the default installations in Ubuntu 16.04 (Python 3), Jupyter notebook (similar result from command line).</p> <p>Mathematica, for comparison, does subpixel-perfect rendering directly and by default: <a href="http://i.stack.imgur.com/E4oB6.png" rel="nofollow"><img src="http://i.stack.imgur.com/E4oB6.png" alt="Same thing rendered by Mathematica"></a> Why can't we?</p>
2
2016-08-27T17:04:28Z
39,186,474
<p>Consider the following to see what is going on</p> <pre><code>import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 5, 4], clip_on=False, lw=5, alpha=.5) ax.set_xlim([1, 3]) fig.savefig('so.png', dpi=400) </code></pre> <p><a href="http://i.stack.imgur.com/1s56E.png" rel="nofollow"><img src="http://i.stack.imgur.com/1s56E.png" alt="example"></a></p> <p>You can also disable pixel snapping by passing <code>snap=False</code> to <code>plot</code>, however once you get down to placing ~ single pixel wide line, you are going to have issues because the underlying rasterization is too coarse.</p>
2
2016-08-27T22:46:43Z
[ "python", "matplotlib" ]
strip() works selectively on the input function but properly on a string literal
39,183,662
<p>I am trying to understand the <code>strip()</code> function. And I'm seeing a confusing behavior.</p> <pre><code>import sys test = input().strip('e') print(test) N = input().strip('cmowz.') print(N) print('www.example.com'.strip('cmowz.')) </code></pre> <p>This gives the following output:</p> <pre><code>test message here 'www.example.com' example </code></pre> <p>So what I'm seeing is that calling <code>input().strip()</code> method works properly for trailing and leading spaces. But it doesn't work for anything else.</p> <p><code>input().strip('e')</code> doesn't really strip e from the string.</p> <p>However, calling a string literal <code>"somethinghere".strip('e')</code> works fine.</p> <p>Can someone please explain this inconsistent behavior?</p>
0
2016-08-27T17:05:00Z
39,183,691
<p>According to the <a href="https://docs.python.org/2/library/string.html#string.strip" rel="nofollow">docs</a>:</p> <blockquote> <p>string.strip(s[, chars]) Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.</p> <p>Changed in version 2.2.3: The chars parameter was added. The chars parameter cannot be passed in earlier 2.2 versions.</p> </blockquote> <p>The important part is, that only trailing and leading characters are removed.</p>
1
2016-08-27T17:08:17Z
[ "python", "python-3.x", "strip" ]
strip() works selectively on the input function but properly on a string literal
39,183,662
<p>I am trying to understand the <code>strip()</code> function. And I'm seeing a confusing behavior.</p> <pre><code>import sys test = input().strip('e') print(test) N = input().strip('cmowz.') print(N) print('www.example.com'.strip('cmowz.')) </code></pre> <p>This gives the following output:</p> <pre><code>test message here 'www.example.com' example </code></pre> <p>So what I'm seeing is that calling <code>input().strip()</code> method works properly for trailing and leading spaces. But it doesn't work for anything else.</p> <p><code>input().strip('e')</code> doesn't really strip e from the string.</p> <p>However, calling a string literal <code>"somethinghere".strip('e')</code> works fine.</p> <p>Can someone please explain this inconsistent behavior?</p>
0
2016-08-27T17:05:00Z
39,183,694
<p>From the <a href="https://docs.python.org/2/library/string.html#string.strip" rel="nofollow">documentation</a>:</p> <blockquote> <p>Return a copy of the string with <code>leading</code> and <code>trailing</code> characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.</p> </blockquote> <p>This is working exactly as expected. </p>
2
2016-08-27T17:08:44Z
[ "python", "python-3.x", "strip" ]
How to mock components within unit tests for Click-based CLI applications?
39,183,741
<p>I'm not sure if this is the best fit for here or the Programmers Stack Exchange, but I'll try here first and cross-post this over there if it's not appropriate.</p> <p>I've recently developed a web service and I'm trying to create a Python-based command-line interface to make it easier to interact with. I've been using Python for a while for simple scripting purposes but I'm inexperienced at creating full-blown packages, including CLI applications.</p> <p>I've researched different packages to help with creating CLI apps and I've settled on using <a href="http://click.pocoo.org/5/" rel="nofollow">click</a>. What I'm concerned about is how to structure my application to make it thoroughly <em>testable</em> before I actually go about putting it all together, and how I can use click to help with that.</p> <p>I have read <a href="http://click.pocoo.org/5/testing/" rel="nofollow">click's documentation on testing</a> as well as examined the <a href="http://click.pocoo.org/5/api/#testing" rel="nofollow">relevant part of the API</a> and while I've managed to use this for testing simple functionality (verifying <code>--version</code> and <code>--help</code> work when passed as arguments to my CLI), I'm not sure how to handle more advanced test cases.</p> <p>I'll provide a specific example of what I'm trying to test right now. I'm planning for my application to have the following sort of architecture...</p> <p><a href="http://i.stack.imgur.com/rD9MM.png" rel="nofollow"><img src="http://i.stack.imgur.com/rD9MM.png" alt="architecture"></a></p> <p>...where the <code>CommunicationService</code> encapsulates all logic involved in connecting and directly communicating with the web service over HTTP. My CLI provides defaults for the web service hostname and port but should allow users to override these either through explicit command-line arguments, writing config files or setting environment variables:</p> <pre><code>@click.command(cls=TestCubeCLI, help=__doc__) @click.option('--hostname', '-h', type=click.STRING, help='TestCube Web Service hostname (default: {})'.format(DEFAULT_SETTINGS['hostname'])) @click.option('--port', '-p', type=click.IntRange(0, 65535), help='TestCube Web Service port (default: {})'.format(DEFAULT_SETTINGS['port'])) @click.version_option(version=version.__version__) def cli(hostname, port): click.echo('Connecting to TestCube Web Service @ {}:{}'.format(hostname, port)) pass def main(): cli(default_map=DEFAULT_SETTINGS) </code></pre> <p>I want to test that if the user specifies different hostnames and ports, then <code>Controller</code> will instantiate a <code>CommunicationService</code> using these settings and not the defaults.</p> <p>I imagine that the best way to do this would be something along these lines:</p> <pre><code>def test_cli_uses_specified_hostname_and_port(): hostname = '0.0.0.0' port = 12345 mock_comms = mock(CommunicationService) # Somehow inject `mock_comms` into the application to make it use that instead of 'real' comms service. result = runner.invoke(testcube.cli, ['--hostname', hostname, '--port', str(port)]) assert result.exit_code == 0 assert mock_comms.hostname == hostname assert mock_comms.port == port </code></pre> <p>If I can get advice on how to properly handle this case, I should hopefully be able to pick it up and use the same technique for making every other part of my CLI testable.</p> <p>For what it's worth, I'm currently using pytest for my tests and this is the extent of the tests I've got so far:</p> <pre><code>import pytest from click.testing import CliRunner from testcube import testcube # noinspection PyShadowingNames class TestCLI(object): @pytest.fixture() def runner(self): return CliRunner() def test_print_version_succeeds(self, runner): result = runner.invoke(testcube.cli, ['--version']) from testcube import version assert result.exit_code == 0 assert version.__version__ in result.output def test_print_help_succeeds(self, runner): result = runner.invoke(testcube.cli, ['--help']) assert result.exit_code == 0 </code></pre>
1
2016-08-27T17:14:33Z
39,191,622
<p>I think I've found one way of doing it. I stumbled across Python's <a href="https://docs.python.org/3/library/unittest.mock.html" rel="nofollow">unittest.mock</a> module, and after a bit of playing around with it I ended up with the following.</p> <p>In my 'comms' module, I define <code>CommunicationService</code>:</p> <pre><code>class CommunicationService(object): def establish_communication(self, hostname: str, port: int): print('Communications service instantiated with {}:{}'.format(hostname, port)) </code></pre> <p>This is a production class and the print statement will eventually get replaced with the actual communication logic.</p> <p>In my main module, I make my top-level command instantiate this communication service and try to establish communications:</p> <pre><code>def cli(hostname, port): comms = CommunicationService() comms.establish_communication(hostname, port) </code></pre> <p>And then the fun part. In my test suite I define this test case:</p> <pre><code>def test_user_can_override_hostname_and_port(self, runner): hostname = 'mock_hostname' port = 12345 # noinspection PyUnresolvedReferences with patch.object(CommunicationService, 'establish_communication', spec=CommunicationService)\ as mock_establish_comms: result = runner.invoke(testcube.cli, ['--hostname', hostname, '--port', str(port), 'mock.enable', 'true']) assert result.exit_code == 0 mock_establish_comms.assert_called_once_with(hostname, port) </code></pre> <p>This temporarily replaces the <code>CommunicationService.establish_communication</code> method with an instance of <code>MagicMock</code>, which will perform no real logic but will record how many times it's called, with what arguments, etc. I can then invoke my CLI and make assertions about how it tried to establish communications based on the supplied command-line arguments.</p> <p>Having worked with projects written primarily in statically-typed languages like Java and C#, it never would have occurred to me that I could just monkey patch methods of my existing production classes, rather than create mock versions of those classes and find a way to substitute those in. It's pretty convenient.</p> <p>Now if I were to accidentally make it so that my CLI ignored explicit user-provided overrides for the hostname and port...</p> <pre><code>def cli(hostname, port): comms = CommunicationService() comms.establish_communication(DEFAULT_SETTINGS['hostname'], DEFAULT_SETTINGS['port']) </code></pre> <p>...then I have my handy test case to alert me:</p> <pre><code>&gt; raise AssertionError(_error_message()) from cause E AssertionError: Expected call: establish_communication('mock_hostname', 12345) E Actual call: establish_communication('127.0.0.1', 36364) </code></pre>
0
2016-08-28T13:11:33Z
[ "python", "testing", "mocking", "command-line-interface", "python-click" ]
Topological Sort not behaving as expected
39,183,880
<p>Here's my graph implementation in Python. This is a directed graph.</p> <pre><code>class DiGraph: def __init__(self): self.all_vertices = [] self.vertex_map = {} self.size = 0 def add(self, a, b): if a in self.vertex_map: av = self.vertex_map[a] if b in self.vertex_map: bv = self.vertex_map[b] av.add(bv) else: bv = Vertex(b) av.add(bv) self.vertex_map[b] = bv self.all_vertices.append(bv) self.size += 1 else: av = Vertex(a) self.size += 1 if b in self.vertex_map: bv = self.vertex_map[b] av.add(bv) else: bv = Vertex(b) av.add(bv) self.vertex_map[b] = bv self.all_vertices.append(bv) self.size += 1 self.vertex_map[a] = av self.all_vertices.append(av) def __sizeof__(self): return self.size def print(self): for v in self.all_vertices: print(v.data, end='-&gt;') for n in v.neighbors: print(n.data, end=', ') print() class Vertex: def __init__(self, data): self.data = data self.neighbors = [] self.connections = 0 def add(self, item): self.neighbors.append(item) self.connections += 1 </code></pre> <p>This is my code for topological sort</p> <pre><code>def top_sort(g): stack = [] visited = set() for v in g.all_vertices: if v not in visited: top_sort_util(v, visited, stack) for ele in stack: print(ele, end=' ') print() def top_sort_util(v, visited, stack): visited.add(v) for n in v.neighbors: if n in visited: continue top_sort_util(n, visited, stack) stack.append(n) </code></pre> <p>This is the caller graph.</p> <pre><code>def main(): graph = DiGraph() graph.add(1, 2) graph.add(1, 3) graph.add(3, 4) graph.add(3, 5) graph.add(2, 6) graph.add(2, 7) graph.add(2, 8) top_sort(graph) if __name__ == '__main__': main() </code></pre> <p>This is the error message that I get,</p> <pre><code>stack.append(n) UnboundLocalError: local variable 'n' referenced before assignment </code></pre> <p>On debugging the code I can see that on the line stack.append(n) nothing gets appended and though the recursion folds out the call stack doesn't go to the next iteration of traversing the neighbors inside the top_sort_util. Can't seem to understand what is logically incorrect here. Any help appreciated.</p>
0
2016-08-27T17:28:43Z
39,183,906
<p>If <code>v.neighbors</code> is empty, <code>n</code> is never set, so the <code>stack.append(n)</code> <em>outside</em> the <code>for n in v.neighbors:</code> fails.</p> <p>If all <code>n</code> must be added to the stack (and not just the last), indent <code>stack.append()</code> properly to be inside the loop:</p> <pre><code>def top_sort_util(v, visited, stack): visited.add(v) for n in v.neighbors: if n in visited: continue top_sort_util(n, visited, stack) stack.append(n) </code></pre>
1
2016-08-27T17:32:20Z
[ "python", "graph", "topological-sort" ]
How to view output from print statements with Django on Elastic Beanstalk
39,183,886
<p>I am running a Django app on Elastic Beanstalk. If I put a print statement in e.g. <code>admin.py</code>, how can I see the result?</p>
0
2016-08-27T17:29:52Z
39,189,921
<p>You should use logging instead of print, you can look back your log anytime and filter the result depend on different level. Check this out <a href="https://docs.python.org/2/howto/logging-cookbook.html" rel="nofollow">logging cookbook</a></p>
0
2016-08-28T09:40:43Z
[ "python", "django", "amazon-web-services", "elastic-beanstalk" ]
regex - swap two phrases around
39,183,970
<p>Python 3. Each line is constructed of a piece of text, then a pipe symbol, then a second piece of text. I want to swap the two pieces of text around and remove the pipe. This is the code so far:</p> <pre><code>p = re.compile('^(.*) \| (.*)$', re.IGNORECASE) mytext = p.sub(r'\2\1', mytext) </code></pre> <p>Yet for some reason that I can't work out, it is not matching. A sample of the text it should be matching is (ironically):</p> <pre><code>(https://www.youtube.com/watch?v=NIKdKCQnbNo) | [Regular Expressions 101 - YouTube] </code></pre> <p>and should end up like:</p> <pre><code>[The Field Expedient Pump Drill - YouTube](https://www.youtube.com/watch?v=4QDXUxTrlRw) </code></pre> <p>(in other words, the code is formatting the links into the format expected of a markdown converter).</p> <p>Here is the full code:</p> <pre><code>#! /usr/bin/env python3 import re, os def create_text(myinputfile): with open(myinputfile, 'r', encoding='utf-8') as infile: mytext = infile.read() return mytext def reg_replace(mytext): p = re.compile('^(.*) \| (.*)$', re.IGNORECASE) mytext = p.sub(r'\2\1', mytext) return mytext def write_out(mytext, myfinalfile): with open(myfinalfile, 'w') as myoutfile: myoutfile.write(mytext) def main(): mytext = create_text('out.md') mytext = reg_replace(mytext) write_out(mytext, 'out1.md') os.rename("out.md", "out_original.md") os.rename("out1.md", "out.md") main() </code></pre>
1
2016-08-27T17:38:15Z
39,184,013
<p>sorry if I'm missing something here, but why not just use <code>re.match</code> with groups instead of <code>re.sub</code>?:</p> <pre><code>import re p = re.compile('^(.*) \| (.*)$', re.IGNORECASE) sample = "(https://www.youtube.com/watch?v=NIKdKCQnbNo) | [Regular Expressions 101 - YouTube]" matches = p.search(sample) new_string = "{0}{1}".format(matches.group(2), matches.group(1)) print(new_string) &gt;&gt;&gt; [Regular Expressions 101 - YouTube](https://www.youtube.com/watch?v=NIKdKCQnbNo) </code></pre>
0
2016-08-27T17:42:44Z
[ "python", "regex", "python-3.x" ]
regex - swap two phrases around
39,183,970
<p>Python 3. Each line is constructed of a piece of text, then a pipe symbol, then a second piece of text. I want to swap the two pieces of text around and remove the pipe. This is the code so far:</p> <pre><code>p = re.compile('^(.*) \| (.*)$', re.IGNORECASE) mytext = p.sub(r'\2\1', mytext) </code></pre> <p>Yet for some reason that I can't work out, it is not matching. A sample of the text it should be matching is (ironically):</p> <pre><code>(https://www.youtube.com/watch?v=NIKdKCQnbNo) | [Regular Expressions 101 - YouTube] </code></pre> <p>and should end up like:</p> <pre><code>[The Field Expedient Pump Drill - YouTube](https://www.youtube.com/watch?v=4QDXUxTrlRw) </code></pre> <p>(in other words, the code is formatting the links into the format expected of a markdown converter).</p> <p>Here is the full code:</p> <pre><code>#! /usr/bin/env python3 import re, os def create_text(myinputfile): with open(myinputfile, 'r', encoding='utf-8') as infile: mytext = infile.read() return mytext def reg_replace(mytext): p = re.compile('^(.*) \| (.*)$', re.IGNORECASE) mytext = p.sub(r'\2\1', mytext) return mytext def write_out(mytext, myfinalfile): with open(myfinalfile, 'w') as myoutfile: myoutfile.write(mytext) def main(): mytext = create_text('out.md') mytext = reg_replace(mytext) write_out(mytext, 'out1.md') os.rename("out.md", "out_original.md") os.rename("out1.md", "out.md") main() </code></pre>
1
2016-08-27T17:38:15Z
39,184,041
<p>This should help you. (View demo on <a href="https://regex101.com/r/hW2kR9/2" rel="nofollow">regex101</a>)</p> <pre><code>(\S+)\s*\|\s*(.+) </code></pre> <p>Sub with:</p> <pre><code> \2\1 </code></pre>
1
2016-08-27T17:45:27Z
[ "python", "regex", "python-3.x" ]
Graphical map objects representation website
39,183,987
<p>Sorry this question is too broad, but I need any advice, because I'm facing a task bit above my experience level.</p> <p>The map should be displayed with database objects like restaurants/events/etc. The suggested platform is Python/Django (which is fine both for me and customer) for both frontend and backend. As a map itself I want to use <a href="http://leafletjs.com/" rel="nofollow">Leaflet</a> because its (presumably) flexible and free. In the first phase there should be just one toolbar with checkboxes, allowing to choose object types to be shown on the map and time range to choose objects.</p> <p>My draft is the following:</p> <ul> <li>Leaflet (js based) as map</li> <li>use database for map objects with default Django admin first and add functionality when needed;</li> <li>use HTML and Django widgets for toolbar, checkboxes and all other stuff;</li> </ul> <p>The only concern is about the frontend/widgets. Is it all likely to work this way? Maybe its definetly better to switch to JS frontend for this type of application (as future planning)?</p>
0
2016-08-27T17:39:58Z
39,184,353
<p>Your plan seems solid.</p> <blockquote> <p>Maybe its definetly better to switch to JS frontend for this type of application (as future planning)?</p> </blockquote> <p>You're already using JS with leaflet, so I assume you're asking about building your own or using a maps service API directly. That approach will take more time, and will lock you into the service API, so I would recommend against it.</p>
1
2016-08-27T18:21:35Z
[ "javascript", "python", "django", "leaflet" ]
Google App Engine Error: __init__() got an unexpected keyword argument 'require'
39,184,071
<p>I'm doing a tutorial on Google App Engine and I"m getting this error:</p> <pre><code>ERROR 2016-08-27 17:41:18,545 webapp2.py:1552] __init__() got an unexpected keyword argument 'require' </code></pre> <p>And I don't know what it's asking for or what it means. Please advise. Thanks. </p> <p>This happens when I call: </p> <p>Controller: </p> <pre><code>json_response = Users.add_new_user(name, email, password) </code></pre> <p>Model: </p> <pre><code>class Users(db.Model): name = db.StringProperty(required = True) email = db.StringProperty(required = True) password = db.StringProperty(require = True) confirmation_code = db.StringProperty(required = True) confirmed_email = db.BooleanProperty(default = False) @classmethod def check_if_exists(cls, email): return cls.query(cls.email == email).get() @classmethod def add_new_user(cls, name, email, password): user = cls.check_if_exists(email) if not user: random_bytes = urandom(64) salt = b64encode(random_bytes).decode('utf-8') hashed_password = salt + sha256(salt + password).hexdigest() confirmation_code = str(uuid.uuid4().get_hex()) new_user_key = cls( name=name, email=email, password=hashed_password, confirmation_code=confirmation_code ).put() print(new_user_key) return { 'created': True, 'user_id': new_user_key.id(), 'confirmation_code':confirmation_code } else: return { 'created': False, 'title': 'This email is already in use', 'message': 'Please log in if this is your email account. ' } </code></pre>
0
2016-08-27T17:49:08Z
39,184,184
<p>You have a typo: <code>require</code> instead of <code>required</code> here:</p> <pre><code> password = db.StringProperty(require = True) </code></pre>
1
2016-08-27T18:02:19Z
[ "python", "python-2.7", "google-app-engine" ]
Flask receiving Post Json
39,184,083
<p>I'm working on a flask web application in which the client posts data to the server in the form of:</p> <p>{ "sess_id" : 1 , "annotations" : [ {"tag_start" : "TIME","tag_end" : "TIME","tag" : "YOUR_TAG"}, {"tag_start" : "TIME","tag_end" : "TIME","tag" : "YOUR_TAG"}, {"tag_start" : "TIME","tag_end" : "TIME","tag" : "YOUR_TAG"}] }</p> <p>Here is the full Ajax post...</p> <pre><code> $.ajax({ url: 'http://127.0.0.1:5000/api/saveannotation', type: 'POST', headers: {'Content-Type' : 'application/json'}, data: {'sess_id' : $('#sessionid_area').val(), 'annotations': JSON.parse(annotations)}, success: function(data) { alert(data.status); } }); </code></pre> <p>so I can even see this on the api side, which is defined as such:</p> <pre><code>@sessionapis.route('/saveannotation', methods=['GET', 'POST']) @login_required def save_annotation(): rData = request.data if request.method == 'GET': return jsonify({'status' : 'success GET'}) else: return jsonify({'status' : 'success'}) </code></pre> <p>The issue is that data is a "byte" type, not a dict. I also can't call request.json or request.get_json(silent=True), it returns "400 bad request".</p> <p>Here is a sample of what is in request.data:</p> <pre><code>b'sess_id=1&amp;annotations%5B0%5D%5Btag_start%5D=2... </code></pre> <p>it appears to be url encoded for some reason. Values is also empty. If I choose to do something wild, like leave out the content-type = json; I can get a dict-like thing, but I have to access it very oddly. I don't get individual objects, but rather just flat access to all properties.</p> <p>Any thoughts on how to just get the json parsed into a reasonable object?</p> <p>Thanks for any hints!</p>
0
2016-08-27T17:50:44Z
39,184,251
<p>Just passing a content-type header of JSON doesn't actually make the data itself into JSON. You either need to do that yourself, or tell jQuery to do so.</p> <pre><code>$.ajax({ url: 'http://127.0.0.1:5000/api/saveannotation', type: 'POST', contentType: 'application/json', data: JSON.stringify({'sess_id' : $('#sessionid_area').val(), 'annotations': JSON.parse(annotations)}), success: function(data) { alert(data.status); } }); </code></pre> <p>Now your data will be in JSON format and you can get it as a Python dict with <code>request.get_json()</code>.</p>
2
2016-08-27T18:08:56Z
[ "python", "json", "flask" ]
What does cur.fetchone()[0] do?
39,184,133
<p>I am using the following code for an educational purpose:</p> <pre><code>import json import sqlite3 conn = sqlite3.connect('rosterdb.sqlite') cur = conn.cursor() # Do some setup cur.executescript(''' DROP TABLE IF EXISTS User; DROP TABLE IF EXISTS Member; DROP TABLE IF EXISTS Course; CREATE TABLE User ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE ); CREATE TABLE Course ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, title TEXT UNIQUE ); CREATE TABLE Member ( user_id INTEGER, course_id INTEGER, role INTEGER, PRIMARY KEY (user_id, course_id) ) ''') fname = raw_input('Enter file name: ') if ( len(fname) &lt; 1 ) : fname = 'roster_data.json' # [ # [ "Charley", "si110", 1 ], # [ "Mea", "si110", 0 ], str_data = open(fname).read() json_data = json.loads(str_data) for entry in json_data: name = entry[0]; title = entry[1]; role = entry[2]; # print name, title, role cur.execute('''INSERT OR IGNORE INTO User (name) VALUES ( ? )''', ( name, ) ) cur.execute('SELECT id FROM User WHERE name = ? ', (name, )) user_id = cur.fetchone()[0] cur.execute('''INSERT OR IGNORE INTO Course (title) VALUES ( ? )''', ( title, ) ) cur.execute('SELECT id FROM Course WHERE title = ? ', (title, )) course_id = cur.fetchone()[0] cur.execute('''INSERT OR REPLACE INTO Member (user_id, course_id, role) VALUES ( ?, ?, ? )''', (user_id, course_id, role) ) conn.commit() </code></pre> <p>What does cur.fetchone()[0] do? Why the cur.fetchnone()[0] is not necessary when populating the Member table?</p> <p>You can download the json file which is read by the program at:</p> <p><a href="https://pr4e.dr-chuck.com/tsugi/mod/sql-intro/roster_data.php?PHPSESSID=7530ba71982b2e10c3f61bd0cb1bfcb5" rel="nofollow">https://pr4e.dr-chuck.com/tsugi/mod/sql-intro/roster_data.php?PHPSESSID=7530ba71982b2e10c3f61bd0cb1bfcb5</a></p>
0
2016-08-27T17:55:56Z
39,184,169
<p><code>cur.fetchone()</code> retrieves one result row for the query that was executed on that cursor. A row is always a sequence of 1 or more columns, and <code>[0]</code> indexes that row to get the first element.</p> <p>It only makes sense to retrieve results from a <code>SELECT</code> query; in <code>INSERT</code> adds data to the database and there are no results to retrieve for that operation.</p> <p>The <code>SELECT</code> queries retrieve extra information to insert into the Member table. The <code>id</code> columns in the User and Course tables are <em>autoincrementing</em>, so each time you insert a row a new id is generated for those new rows. The <code>SELECT</code> statements retrieve these id values so they can be used in the Member table. </p>
1
2016-08-27T17:59:52Z
[ "python", "sql", "python-2.7", "sqlite", "mooc" ]
Deserialisation "pickle" file
39,184,135
<p>My code is:</p> <pre><code>import _pickle with open('items_10000_matrix.pickle', 'rb') as f: data_new = _pickle.load(f) </code></pre> <p>But an error occurs: </p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 212: ordinal not in range(128) </code></pre> <p>I am using windows 10 + python 3.5 with VS tools for python. </p>
2
2016-08-27T17:56:00Z
39,215,566
<p>Try using <code>_pickle.load(f, encoding='bytes')</code>.</p> <p>By the way, in Python 3, there's no reason to explicitly import <code>_pickle</code> rather than <code>pickle</code> because it will automatically switch to the C version if it's available. See the accepted answer to the question <a href="http://stackoverflow.com/questions/19191859/what-difference-between-pickle-and-pickle-in-python-3"><em>What difference between pickle and _pickle in python 3?</em></a></p>
1
2016-08-29T21:33:24Z
[ "python", "python-3.x", "pickle", "python-unicode" ]
Deserialisation "pickle" file
39,184,135
<p>My code is:</p> <pre><code>import _pickle with open('items_10000_matrix.pickle', 'rb') as f: data_new = _pickle.load(f) </code></pre> <p>But an error occurs: </p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 212: ordinal not in range(128) </code></pre> <p>I am using windows 10 + python 3.5 with VS tools for python. </p>
2
2016-08-27T17:56:00Z
39,215,717
<p>I was told to use python 2 instead of python 3, and it worked. Still dont know the solution for python3</p>
0
2016-08-29T21:48:55Z
[ "python", "python-3.x", "pickle", "python-unicode" ]
Converting time from AM/PM format to military time in Python
39,184,198
<p>Without using any libraries, I'm trying to solve the Hackerrank problem "<a href="https://www.hackerrank.com/challenges/time-conversion?h_r=next-challenge&amp;h_v=zen" rel="nofollow">Time Conversion</a>", the problem statement of which is copied below.</p> <p><a href="http://i.stack.imgur.com/YRr6p.png" rel="nofollow"><img src="http://i.stack.imgur.com/YRr6p.png" alt="enter image description here"></a></p> <p>I came up with the following:</p> <pre><code>time = raw_input().strip() meridian = time[-2:] # "AM" or "PM" time_without_meridian = time[:-2] hour = int(time[:2]) if meridian == "AM": hour = (hour+1) % 12 - 1 print ("%02d" % hour) + time_without_meridian[2:] elif meridian == "PM": hour += 12 print str(hour) + time_without_meridian[2:] </code></pre> <p>However, this fails on one test case:</p> <p><a href="http://i.stack.imgur.com/yQLb9.png" rel="nofollow"><img src="http://i.stack.imgur.com/yQLb9.png" alt="enter image description here"></a></p> <p>Since the test cases are hidden to the user, however, I'm struggling to see where the problem is occurring. "12:00:00AM" is correctly converted to "00:00:00", and "01:00:00AM" to "01:00:00" (with the padded zero). What could be wrong with this implementation?</p>
1
2016-08-27T18:03:25Z
39,184,237
<p>I figured it out: it was converting "12:00:00PM" to "24:00:00" and not "12:00:00". I modified the code as follows:</p> <pre><code>time = raw_input().strip() meridian = time[-2:] # "AM" or "PM" time_without_meridian = time[:-2] hour = int(time[:2]) if meridian == "AM": hour = (hour+1) % 12 - 1 print ("%02d" % hour) + time_without_meridian[2:] elif meridian == "PM": hour = hour % 12 + 12 print str(hour) + time_without_meridian[2:] </code></pre> <p>leading to it passing all the test cases (see below).</p> <p><a href="http://i.stack.imgur.com/xKV9t.png" rel="nofollow"><img src="http://i.stack.imgur.com/xKV9t.png" alt="enter image description here"></a></p>
0
2016-08-27T18:07:30Z
[ "python" ]
Converting time from AM/PM format to military time in Python
39,184,198
<p>Without using any libraries, I'm trying to solve the Hackerrank problem "<a href="https://www.hackerrank.com/challenges/time-conversion?h_r=next-challenge&amp;h_v=zen" rel="nofollow">Time Conversion</a>", the problem statement of which is copied below.</p> <p><a href="http://i.stack.imgur.com/YRr6p.png" rel="nofollow"><img src="http://i.stack.imgur.com/YRr6p.png" alt="enter image description here"></a></p> <p>I came up with the following:</p> <pre><code>time = raw_input().strip() meridian = time[-2:] # "AM" or "PM" time_without_meridian = time[:-2] hour = int(time[:2]) if meridian == "AM": hour = (hour+1) % 12 - 1 print ("%02d" % hour) + time_without_meridian[2:] elif meridian == "PM": hour += 12 print str(hour) + time_without_meridian[2:] </code></pre> <p>However, this fails on one test case:</p> <p><a href="http://i.stack.imgur.com/yQLb9.png" rel="nofollow"><img src="http://i.stack.imgur.com/yQLb9.png" alt="enter image description here"></a></p> <p>Since the test cases are hidden to the user, however, I'm struggling to see where the problem is occurring. "12:00:00AM" is correctly converted to "00:00:00", and "01:00:00AM" to "01:00:00" (with the padded zero). What could be wrong with this implementation?</p>
1
2016-08-27T18:03:25Z
39,184,280
<p>You've already solved the problem but here's another possible answer:</p> <pre><code>from datetime import datetime def solution(time): return datetime.strptime(time, '%I:%M:%S%p').strftime('%H:%M:%S') if __name__ == '__main__': tests = [ "12:00:00PM", "12:00:00AM", "07:05:45PM" ] for t in tests: print solution(t) </code></pre> <p>Although it'd be using a python library :-)</p>
1
2016-08-27T18:12:30Z
[ "python" ]
Converting time from AM/PM format to military time in Python
39,184,198
<p>Without using any libraries, I'm trying to solve the Hackerrank problem "<a href="https://www.hackerrank.com/challenges/time-conversion?h_r=next-challenge&amp;h_v=zen" rel="nofollow">Time Conversion</a>", the problem statement of which is copied below.</p> <p><a href="http://i.stack.imgur.com/YRr6p.png" rel="nofollow"><img src="http://i.stack.imgur.com/YRr6p.png" alt="enter image description here"></a></p> <p>I came up with the following:</p> <pre><code>time = raw_input().strip() meridian = time[-2:] # "AM" or "PM" time_without_meridian = time[:-2] hour = int(time[:2]) if meridian == "AM": hour = (hour+1) % 12 - 1 print ("%02d" % hour) + time_without_meridian[2:] elif meridian == "PM": hour += 12 print str(hour) + time_without_meridian[2:] </code></pre> <p>However, this fails on one test case:</p> <p><a href="http://i.stack.imgur.com/yQLb9.png" rel="nofollow"><img src="http://i.stack.imgur.com/yQLb9.png" alt="enter image description here"></a></p> <p>Since the test cases are hidden to the user, however, I'm struggling to see where the problem is occurring. "12:00:00AM" is correctly converted to "00:00:00", and "01:00:00AM" to "01:00:00" (with the padded zero). What could be wrong with this implementation?</p>
1
2016-08-27T18:03:25Z
39,184,444
<p>It's even simpler than how you have it.</p> <pre><code>hour = int(time[:2]) meridian = time[8:] if (hour == 12): hour = 0 if (meridian == 'PM'): hour += 12 print("%02d" % hour + time[2:8]) </code></pre>
2
2016-08-27T18:31:21Z
[ "python" ]
sha256 result dosen't change
39,184,256
<p>First time using sha256.</p> <p>With this code, the result always equals to <code>4aa6892909e369933b9f1babc10519121e2dfd1042551f6b9bdd4eae51f1f0c2</code></p> <p>what is wrong?</p> <pre><code>def signning(self,D_path): BUF_SIZE = 65536 hashed = hashlib.sha256() with open(D_path, 'rb') as f: while True: data = f.read(BUF_SIZE) if not data: break hashed.update(data) hashed_D = hashed.hexdigest() print hashed_D </code></pre>
-1
2016-08-27T18:09:29Z
39,184,317
<p>Yeah, there is nothing wrong with your code, here's a little example showing that hashlib.sha256 is deterministic:</p> <pre><code>import random import string import hashlib random.seed(1) for i in range(5): data = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) hashed = hashlib.sha256() hashed.update(data) print data, "-&gt;", hashed.hexdigest() </code></pre> <p>Run this script over and over and you'll be getting the same output cos the input is always the same ;)</p>
0
2016-08-27T18:17:57Z
[ "python", "python-2.7", "sha256", "sha" ]
How can I decorate all functions imported from a file?
39,184,338
<p>I have created many functions that are divided into different files, now I would like to apply the same decorator for all of them without modifying the files and without applying the decorators one by one.</p> <p>I have tried to use <a href="http://stackoverflow.com/questions/6307761/how-can-i-decorate-all-functions-of-a-class-without-typing-it-over-and-over-for">this explanation</a> written by delnan, but I got no success for imported functions.</p> <p>About the decorator, it must update a list every time a function within a class is executexecuted with the function arguments and values, just like <a href="http://stackoverflow.com/questions/39154006/update-a-list-every-time-a-function-within-a-class-is-executexecuted-with-the-fu">this other question</a> I asked.</p> <p>Any suggestions to help me with this issue? Thanks</p>
1
2016-08-27T18:19:56Z
39,184,411
<p>A little bit of introspection (<a href="https://docs.python.org/3/library/functions.html#dir" rel="nofollow"><code>dir()</code></a>) and dynamic look-up with <a href="https://docs.python.org/3/library/functions.html#getattr" rel="nofollow"><code>getattr()</code></a> and <a href="https://docs.python.org/3/library/functions.html#setattr" rel="nofollow"><code>setattr()</code></a>.</p> <p>First we iterate over all names found in module and <a href="https://docs.python.org/3/library/types.html#types.FunctionType" rel="nofollow">check for objects that look like functions</a>. After that we simply reassign old function with decorated one.</p> <p><strong>main.py:</strong></p> <pre><code>import types import functools def decorate_all_in_module(module, decorator): for name in dir(module): obj = getattr(module, name) if isinstance(obj, types.FunctionType): setattr(module, name, decorator(obj)) def my_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): print(f) return f(*args, **kwargs) return wrapper import mymod1 decorate_all_in_module(mymod1, decorator) </code></pre> <p><strong>mymod1.py</strong>:</p> <pre><code>def f(x): print(x) def g(x, y): print(x + y) </code></pre> <p><strong>Output:</strong></p> <pre><code>&lt;function f at 0x101e309d8&gt; 2 &lt;function g at 0x101e30a60&gt; 7 </code></pre> <p>Process does not goes that smooth if you use star imports (<code>from mymod import *</code>). Reason is simple - because all names are in one huge bag and there no differentiation on where they come from, you need a lot of additional tricks to find what exactly you want to patch. But, well, that's why we use namespaces - <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">because they are one honking great idea</a>.</p>
3
2016-08-27T18:28:08Z
[ "python", "wrapper", "python-decorators" ]
Is there any expression in Swift that similar Python for else syntax
39,184,398
<p>I am solving a algorithm problem, and I use both Python and Swift to solve it. In python, I can use a for else syntax solve it easily. But in Swift, I am struggling to find a way that similar to python's for else syntax. </p> <p>Here is the algorithm problem, it may help you understand what I am doing.</p> <blockquote> <p>Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.</p> <p>Example 1: Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]</p> <p>Return 16</p> <p>The two words can be "abcw", "xtfn".</p> <p>Example 2: Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]</p> <p>Return 4 </p> <p>The two words can be "ab", "cd".</p> <p>Example 3: Given ["a", "aa", "aaa", "aaaa"]</p> <p>Return 0</p> <p>No such pair of words.</p> </blockquote> <p>Here are my two sets code. </p> <p>The Python code works.</p> <pre><code>class Solution(object): def maxProduct(self, words): maximum = 0 while words: currentWord = set(words[0]) current_length = len(words[0]) words = words[1:] for ele in words: for char in currentWord: if char in ele: break else: maximum = max(maximum,current_length*len(ele)) return maximum </code></pre> <p>The swift code not works well.</p> <pre><code>class Solution { func maxProduct(words: [String]) -&gt; Int { var input = words let length = input.count var maximum = 0 while input.count != 0 { let cur_word = Set(input[0].characters) let cur_length = input[0].characters.count input = Array(input[1..&lt;length]) for item in input { for char in item.characters { if cur_word.contains(char) { break } } // how add a control follow here? if cur_word does not share same character with item, then does the below max statement //else //{ maximum = max(maximum,cur_length*(item.characters.count)) //} } } return maximum } } </code></pre>
1
2016-08-27T18:26:27Z
39,184,537
<p>You could just introduce a flag to record if <code>break</code> is called or not. The statement</p> <pre><code>for a in b: if c(a): break else: d() </code></pre> <p>is the same as</p> <pre><code>found = False for a in b: if c(a): found = True break if not found: d() </code></pre> <p>But note that you don't need the <code>for char in item.characters</code> loop at all, since you could just use the <a href="https://developer.apple.com/library/ios/documentation/Swift/Reference/Swift_SetAlgebraType_Protocol/index.html#//apple_ref/swift/intfm/SetAlgebraType/s:FPs14SetAlgebraType14isDisjointWithFxSb" rel="nofollow"><code>Set.isDisjointWith(_:)</code> method</a>.</p> <pre><code>if cur_word.isDisjointWith(item.characters) { maximum = ... } </code></pre> <p>(On Swift 3 this method is <a href="https://developer.apple.com/reference/swift/set/1781080-isdisjoint" rel="nofollow">renamed to <code>Set.isDisjoint(with:)</code></a>)</p>
0
2016-08-27T18:41:03Z
[ "python", "swift2", "for-else" ]
Is there any expression in Swift that similar Python for else syntax
39,184,398
<p>I am solving a algorithm problem, and I use both Python and Swift to solve it. In python, I can use a for else syntax solve it easily. But in Swift, I am struggling to find a way that similar to python's for else syntax. </p> <p>Here is the algorithm problem, it may help you understand what I am doing.</p> <blockquote> <p>Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.</p> <p>Example 1: Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]</p> <p>Return 16</p> <p>The two words can be "abcw", "xtfn".</p> <p>Example 2: Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]</p> <p>Return 4 </p> <p>The two words can be "ab", "cd".</p> <p>Example 3: Given ["a", "aa", "aaa", "aaaa"]</p> <p>Return 0</p> <p>No such pair of words.</p> </blockquote> <p>Here are my two sets code. </p> <p>The Python code works.</p> <pre><code>class Solution(object): def maxProduct(self, words): maximum = 0 while words: currentWord = set(words[0]) current_length = len(words[0]) words = words[1:] for ele in words: for char in currentWord: if char in ele: break else: maximum = max(maximum,current_length*len(ele)) return maximum </code></pre> <p>The swift code not works well.</p> <pre><code>class Solution { func maxProduct(words: [String]) -&gt; Int { var input = words let length = input.count var maximum = 0 while input.count != 0 { let cur_word = Set(input[0].characters) let cur_length = input[0].characters.count input = Array(input[1..&lt;length]) for item in input { for char in item.characters { if cur_word.contains(char) { break } } // how add a control follow here? if cur_word does not share same character with item, then does the below max statement //else //{ maximum = max(maximum,cur_length*(item.characters.count)) //} } } return maximum } } </code></pre>
1
2016-08-27T18:26:27Z
39,186,853
<p>I would like to share my answer. Appreciate Kennytm's help. </p> <pre><code>class Solution { func maxProduct(words: [String]) -&gt; Int { var input = words var length = input.count var maximum = 0 while input.count != 0 { let cur_word = Set(input[0].characters) let cur_length = input[0].characters.count input = Array(input[1..&lt;length]) length -= 1 for item in input { if cur_word.isDisjointWith(item.characters) { maximum = max(maximum, cur_length*(item.characters.count)) } } } return maximum } } </code></pre>
0
2016-08-28T00:03:04Z
[ "python", "swift2", "for-else" ]
Celery connect to remote server broker_url
39,184,400
<p>I'm daemonizing celery following the <a href="http://docs.celeryproject.org/en/latest/tutorials/daemonizing.html" rel="nofollow">docs</a>. </p> <p>My BROKER_URL has been set in the following format:- <code>'amqp://&lt;user&gt;:&lt;password&gt;@&lt;ip&gt;/&lt;vhost&gt;'</code>.</p> <p>So, when I start celery manually, <code>celery worker -A app_name</code>, it connects with the remote server. But when I daemonize it, it connects with the localhost amqp. Any reason why?</p> <p>Here is how I create my celery object:-</p> <pre><code>app = Celery('c26_search') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.update( CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend' ) print app.conf.BROKER_URL # prints remote url </code></pre> <p>My settings.py file:-</p> <pre><code>CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' BROKER_URL = `'amqp://&lt;user&gt;:&lt;password&gt;@&lt;ip&gt;/&lt;vhost&gt;'` </code></pre> <p>Why is it acting so weirdly? Even it prints the remote IP url, but still tries to connects with the local amqp?</p>
0
2016-08-27T18:26:36Z
39,185,568
<p>Well, I found the answer to the question:-</p> <p>Pass broker url is <code>CELERY_OPTS</code> as <code>CELERYD_OPTS="-n worker2.%h --broker=amqp://&lt;user&gt;:&lt;password&gt;@&lt;ip&gt;/&lt;vhost&gt;"</code> in celeryd file.</p>
0
2016-08-27T20:42:35Z
[ "python", "django", "celery", "django-celery", "djcelery" ]
Atom package linter-flake8 not showing output
39,184,428
<p>I have installed linter-flake8 with Atom on MacOSX. Atom automatically installed linter. My problem is that the package doesn't detect any errors with python scripts. The strange thing is that if I run flake8 from the command line, it does detect multiple errors and specifies in which file the errors occured.</p> <p>Here is a screenshot: </p> <p><a href="http://image.noelshack.com/fichiers/2016/34/1472320581-capture-d-ecran-2016-08-27-a-19-55-57.png" rel="nofollow">http://image.noelshack.com/fichiers/2016/34/1472320581-capture-d-ecran-2016-08-27-a-19-55-57.png</a></p>
0
2016-08-27T18:29:19Z
39,184,531
<p>I've notices several Flake8 plugins don't support reading from stdin priperly since <code>flake8 &gt;= 3</code>. The flake8 Atom package basically runs <code>cat $FILENAME | flake8 -</code>. Try running that command from the terminal and report differences in output to the relevant plugin.</p>
0
2016-08-27T18:40:20Z
[ "python", "atom-editor", "flake8" ]
pandas.DataFrame set all string values to nan
39,184,442
<p>I have a <code>pandas.DataFrame</code> that contain string, float and int types.</p> <p>Is there a way to set all strings that cannot be converted to float to <code>NaN</code> ?</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code> A B C D 0 1 2 5 7 1 0 4 NaN 15 2 4 8 9 10 3 11 5 8 0 4 11 5 8 "wajdi" </code></pre> <p>to:</p> <pre class="lang-py prettyprint-override"><code> A B C D 0 1 2 5 7 1 0 4 NaN 15 2 4 8 9 10 3 11 5 8 0 4 11 5 8 NaN </code></pre>
1
2016-08-27T18:30:49Z
39,184,505
<p>Try </p> <pre><code>df.convert_objects(convert_numeric=True) </code></pre> <p>To be fair to the other answers using to_numeric, this method is deprecated as Merlin pointed out. So make sure to take that into account when using this, especially if you plan to roll it into a long term solution. Although, you should be fine if you're just applying this to an ad-hoc analysis. </p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.html" rel="nofollow">Pandas.DataFrame.convert_objects</a></p>
3
2016-08-27T18:37:21Z
[ "python", "string", "pandas", "dataframe" ]
pandas.DataFrame set all string values to nan
39,184,442
<p>I have a <code>pandas.DataFrame</code> that contain string, float and int types.</p> <p>Is there a way to set all strings that cannot be converted to float to <code>NaN</code> ?</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code> A B C D 0 1 2 5 7 1 0 4 NaN 15 2 4 8 9 10 3 11 5 8 0 4 11 5 8 "wajdi" </code></pre> <p>to:</p> <pre class="lang-py prettyprint-override"><code> A B C D 0 1 2 5 7 1 0 4 NaN 15 2 4 8 9 10 3 11 5 8 0 4 11 5 8 NaN </code></pre>
1
2016-08-27T18:30:49Z
39,184,512
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.to_numeric.html" rel="nofollow"><code>pd.to_numeric</code></a> with <code>errors='coerce'</code>. </p> <pre><code>In [30]: df = pd.DataFrame({'a': [1, 2, 'NaN', 'bob', 3.2]}) In [31]: pd.to_numeric(df.a, errors='coerce') Out[31]: 0 1.0 1 2.0 2 NaN 3 NaN 4 3.2 Name: a, dtype: float64 </code></pre> <p>Here is one way to apply it to all columns:</p> <pre><code>for c in df.columns: df[c] = pd.to_numeric(df[c], errors='coerce') </code></pre> <p>(See comment by NinjaPuppy for a better way.)</p>
1
2016-08-27T18:37:59Z
[ "python", "string", "pandas", "dataframe" ]
pandas.DataFrame set all string values to nan
39,184,442
<p>I have a <code>pandas.DataFrame</code> that contain string, float and int types.</p> <p>Is there a way to set all strings that cannot be converted to float to <code>NaN</code> ?</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code> A B C D 0 1 2 5 7 1 0 4 NaN 15 2 4 8 9 10 3 11 5 8 0 4 11 5 8 "wajdi" </code></pre> <p>to:</p> <pre class="lang-py prettyprint-override"><code> A B C D 0 1 2 5 7 1 0 4 NaN 15 2 4 8 9 10 3 11 5 8 0 4 11 5 8 NaN </code></pre>
1
2016-08-27T18:30:49Z
39,184,562
<p>Here is a way:</p> <pre><code>df['E'] = pd.to_numeric(df.D, errors='coerce') </code></pre> <p>And then you have:</p> <pre><code> A B C D E 0 1 2 5.0 7 7.0 1 0 4 NaN 15 15.0 2 4 8 9.0 10 10.0 3 11 5 8.0 0 0.0 4 11 5 8.0 wajdi NaN </code></pre>
3
2016-08-27T18:43:47Z
[ "python", "string", "pandas", "dataframe" ]
Connect JS client with Python server
39,184,455
<p>I'm relatively new to JS and Python, so this is probably a beginners question. I'm trying to send a string from a JS client to Python Server (and then send the string to another Python client).</p> <p>This is my code:</p> <p>JS client:</p> <pre><code> var socket = io.connect('http://127.0.0.1:8484'); socket.send('lalala'); </code></pre> <p>Python server:</p> <pre><code>HOST = '127.0.0.1' PORT = 8484 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(2) #JS conn1, addr1 = s.accept() print 'Connected by', addr1 #PY conn2, addr2 = s.accept() print 'Connected by', addr2 while 1: try: data = conn1.recv(1024) except socket.error: print '' if data: print data.decode('utf-8') conn2.send('data') </code></pre> <p>Python client:</p> <pre><code>def __init__(self): #inicializacion self.comando = '0' self.HOST = '127.0.0.1' self.PORT = 8484 self.cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM) fcntl.fcntl(self.cliente, fcntl.F_SETFL, os.O_NONBLOCK) def activate(self): print "Plugin de envio en marcha." def deactivate(self): print "Plugin de envio off." def __call__(self, sample): self.cliente.connect((self.HOST, self.PORT)) try: self.comando = self.cliente.recv(1024).decode('utf-8') except socket.error, e: self.comando = '0' print "******************" print self.comando print "******************" </code></pre> <p>I have no problem sending a random string from python server to python client, but I can't receive from the JS client. </p> <p>When I run the server and the clients there are no problems with the connection: </p> <pre><code>Connected by ('127.0.0.1', 52602) Connected by ('127.0.0.1', 52603) </code></pre> <p>But, for example, this is what I receive from the JS:</p> <pre><code>GET /socket.io/1/?t=1472322502274 HTTP/1.1 Host: 127.0.0.1:8484 Connection: keep-alive Origin: http://127.0.0.1:8880 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36 Accept: */* Referer: http://127.0.0.1:8880/normal.html Accept-Encoding: gzip, deflate, sdch Accept-Language: es-ES,es;q=0.8 Cookie: io=e7675566ceab4aa1991d55cd72c8075c </code></pre> <p>But I want the string 'lalala'.</p> <p>Any ideas? </p> <p>(And thank you!)</p>
0
2016-08-27T18:32:03Z
39,184,584
<p><code>socket.socket()</code> doesn't create a websocket server.</p> <p>You should use a websocket server, check this : <a href="https://websockets.readthedocs.io/en/stable/" rel="nofollow">https://websockets.readthedocs.io/en/stable/</a></p> <p>Also your python client should use <code>websockets</code> too, even though you could still send data using raw sockets.</p>
0
2016-08-27T18:46:11Z
[ "javascript", "python", "node.js", "sockets", "socket.io" ]
Connect JS client with Python server
39,184,455
<p>I'm relatively new to JS and Python, so this is probably a beginners question. I'm trying to send a string from a JS client to Python Server (and then send the string to another Python client).</p> <p>This is my code:</p> <p>JS client:</p> <pre><code> var socket = io.connect('http://127.0.0.1:8484'); socket.send('lalala'); </code></pre> <p>Python server:</p> <pre><code>HOST = '127.0.0.1' PORT = 8484 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(2) #JS conn1, addr1 = s.accept() print 'Connected by', addr1 #PY conn2, addr2 = s.accept() print 'Connected by', addr2 while 1: try: data = conn1.recv(1024) except socket.error: print '' if data: print data.decode('utf-8') conn2.send('data') </code></pre> <p>Python client:</p> <pre><code>def __init__(self): #inicializacion self.comando = '0' self.HOST = '127.0.0.1' self.PORT = 8484 self.cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM) fcntl.fcntl(self.cliente, fcntl.F_SETFL, os.O_NONBLOCK) def activate(self): print "Plugin de envio en marcha." def deactivate(self): print "Plugin de envio off." def __call__(self, sample): self.cliente.connect((self.HOST, self.PORT)) try: self.comando = self.cliente.recv(1024).decode('utf-8') except socket.error, e: self.comando = '0' print "******************" print self.comando print "******************" </code></pre> <p>I have no problem sending a random string from python server to python client, but I can't receive from the JS client. </p> <p>When I run the server and the clients there are no problems with the connection: </p> <pre><code>Connected by ('127.0.0.1', 52602) Connected by ('127.0.0.1', 52603) </code></pre> <p>But, for example, this is what I receive from the JS:</p> <pre><code>GET /socket.io/1/?t=1472322502274 HTTP/1.1 Host: 127.0.0.1:8484 Connection: keep-alive Origin: http://127.0.0.1:8880 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36 Accept: */* Referer: http://127.0.0.1:8880/normal.html Accept-Encoding: gzip, deflate, sdch Accept-Language: es-ES,es;q=0.8 Cookie: io=e7675566ceab4aa1991d55cd72c8075c </code></pre> <p>But I want the string 'lalala'.</p> <p>Any ideas? </p> <p>(And thank you!)</p>
0
2016-08-27T18:32:03Z
39,184,665
<p>If you want to connect to the python TCP server, then you can use a code similar to the following in node:</p> <pre><code>var net = require('net'); var client = new net.Socket(); client.connect(8484, '127.0.0.1', function() { console.log('Connected'); client.write('Hello, server! Love, Client.'); }); client.on('data', function(data) { console.log('Received: ' + data); client.destroy(); // kill client after server's response }); </code></pre> <p>The server started by your python code doesn't listens for raw TCP connections. If you read up on <a href="https://tools.ietf.org/html/rfc2616" rel="nofollow">HTTP protocol</a> you will understand why you saw those strings when your js code sent that string. </p>
0
2016-08-27T18:55:46Z
[ "javascript", "python", "node.js", "sockets", "socket.io" ]
using sdl2 in Kivy instead of pygame
39,184,571
<p>I couldn't resize my windows on the applications i made with Kivy, so I found out using sdl2, instead of Pygame, with Kivy can fix this. I uninstalled Kivy and Pygame, then installed sdl2, then reinstalled Kivy. Kivy still is trying to use pygame though. Please Help.</p> <pre><code>File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/kivy/core/__init__.py", line 59, in core_select_lib fromlist=[modulename], level=0) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/kivy/core/window/window_pygame.py", line 8, in &lt;module&gt; import pygame </code></pre>
1
2016-08-27T18:44:41Z
39,186,099
<p>The easiest way to fix this is to purge your current kivy install and re-install it fresh using the following links as a reference point (these are the official installation instructions)</p> <p><a href="https://kivy.org/docs/installation/installation-windows.html" rel="nofollow">https://kivy.org/docs/installation/installation-windows.html</a></p> <p>With that being said please note the following, do to an issue with a few compilers 1.9.2 doesn't work on windows with python 3.5 this is an ongoing issue the kivy team is aware of and working on.</p> <p>So this means you're left with using python 3.4 for the newest version(s) of kivy on windows. Kivy no longers uses pygame and should by default prompt you to install sdl2.</p> <p>The only issue you may have with the official instructions in the link I provided is setting up GStreamer if it gives you a problem you can skip that and just grab a ported version which suffices.</p> <p>If you're on Linux then just re-install :)</p>
1
2016-08-27T21:55:45Z
[ "python", "python-3.x", "pygame", "kivy", "sdl-2" ]
QWebEngineView fails loading SVG using setHtml(...)
39,184,615
<p>I tried two different ways to load and show an SVG file in PyQt:</p> <pre><code>import sys from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl app = QApplication(sys.argv) webView = QWebEngineView() # Variant 1: Reasonably fast webView.load(QUrl('file:///Test.svg')) # Variant 2: Slow for small files, not working for big ones webView.setHtml('&lt;svg&gt;........') webView.show() sys.exit(app.exec_()) </code></pre> <p>The first way works okay but requires a file as input. I would like to generate the SVGs dynamically though, so this is not really an option. Does anyone have an idea why the second approach is so darn slow or failing completely for more complex vector images?</p>
1
2016-08-27T18:50:02Z
39,186,648
<p>The <code>setHtml</code> function cannot load any content (not just svg) that is greater than 2MB in size. This is because Chromium uses a <code>data:</code> scheme url to load the content (which obvioulsy limits the size to the maximum length for a url). So it would seem that the only option is to load the svg from a local file.</p> <ul> <li>See: <a href="http://bugreports.qt.io/browse/QTBUG-53414" rel="nofollow">QTBUG-53414</a></li> </ul>
1
2016-08-27T23:18:12Z
[ "python", "qt", "svg", "pyqt5", "qtwebengine" ]
Create a list from a list of dictionaries subject to a condition (counter and accumulator) in python
39,184,654
<p>I have a list dictionary of items: </p> <pre><code>ListDictItem = [ {'Item No': 1,'Weight':610,'Quantity':2},{'Item No': 2,'Weight':610,'Quantity':2},{'Item No': 3,'Weight':500,'Quantity':2},{'Item No': 4,'Weight':484,'Quantity':2},{'Item No': 5,'Weight':470,'Quantity':2},{'Item No': 6,'Weight':440,'Quantity':2},{'Item No': 7,'Weight':440,'Quantity':2},{'Item No': 8,'Weight':400,'Quantity':2}] </code></pre> <p>I have created a list of weights from above like this: </p> <pre><code>ItemWeigths: [610.0, 610.0, 500.0, 484.0, 470.0, 440.0,440, 400.0] </code></pre> <p>I would like to pack the items in shelves such that the total weight of each shelf is less than a particular value and have a list in the following format:</p> <pre><code>shelves = [[{'Item No': 1,'Weight':610,'Quantity':2}],[{'Item No': 2,'Weight':610,'Quantity':2}],[{'Item No': 3,'Weight':500,'Quantity':2}],[{'Item No': 4,'Weight':484,'Quantity':2}], [{'Item No': 7,'Weight':440,'Quantity':2}],[{'Item No': 8,'Weight':400,'Quantity':2}] ] </code></pre> <p>where the sum of the all the weights of a particular shelf is &lt;= 610</p> <p>I have created a code that it is packing the first shelf correctly but I am unable to write the code for creating shelves for other items:</p> <pre><code>shelves=[] ShelvesWeightTotal = 0 shelf=[] new=[] ShelfToPack=[] for i in range(0,len(ItemWeigths)): while ShelvesWeightTotal + ItemWeigths[i] &lt;= WeightOfObject: shelves += [ItemWeigths[i]] ShelvesWeightTotal = sum(shelves) </code></pre> <p>The above code works for 1st item but to create other shelves for remaining items I wrote the code which doesnot work:</p> <pre><code>for i in range(0,len(ItemWeigths)): while ItemsToCut !=[]: if ShelvesWeightTotal + ItemWeigths[i] &lt;=WeightOfObject: shelves += [ItemWeigths[i]] ShelvesWeightTotal = sum(shelves) ItemWeigths.pop(i) ItemsToCut.pop(i) shelf.append(shelves) </code></pre> <p>Any suggestion to write the code to create shelves in a better way will be appreciated.</p>
0
2016-08-27T18:54:49Z
39,185,046
<p>I took a simpler approach:</p> <pre><code>ListDictItem = [{'Item No': 1,'Weight':610,'Quantity':2}, {'Item No': 2,'Weight':610,'Quantity':2}, {'Item No': 3,'Weight':500,'Quantity':2}, {'Item No': 4,'Weight':484,'Quantity':2}, {'Item No': 5,'Weight':470,'Quantity':2}, {'Item No': 6,'Weight':440,'Quantity':2}, {'Item No': 7,'Weight':440,'Quantity':2}, {'Item No': 8,'Weight':400,'Quantity':2}] maxWeight = 610 shelves = [] shelf = [] current_shelf_weight = 0 for item in ListDictItem: if current_shelf_weight + item['Weight'] &lt;= maxWeight: shelf.append(item) current_shelf_weight += item['Weight'] else: shelves.append(shelf) if item['Weight'] &lt;= maxWeight: shelf = [item] current_shelf_weight = item['Weight'] else: shelf = [] current_shelf_weight = 0 if shelf: #append any remaining items shelves.append(shelf) print("shelves = " + str(shelves)) </code></pre> <p>When I check the output of this code, I get this:</p> <pre><code>shelves = [[{'Weight': 610, 'Item No': 1, 'Quantity': 2}], [{'Weight': 610, 'Item No': 2, 'Quantity': 2}], [{'Weight': 500, 'Item No': 3, 'Quantity': 2}], [{'Weight': 484, 'Item No': 4, 'Quantity': 2}], [{'Weight': 470, 'Item No': 5, 'Quantity': 2}], [{'Weight': 440, 'Item No': 6, 'Quantity': 2}], [{'Weight': 440, 'Item No': 7, 'Quantity': 2}], [{'Weight': 400, 'Item No': 8, 'Quantity': 2}]] </code></pre> <p>Which is exactly what you wanted.</p>
4
2016-08-27T19:39:29Z
[ "python", "list", "python-3.x", "dictionary" ]
Create a list from a list of dictionaries subject to a condition (counter and accumulator) in python
39,184,654
<p>I have a list dictionary of items: </p> <pre><code>ListDictItem = [ {'Item No': 1,'Weight':610,'Quantity':2},{'Item No': 2,'Weight':610,'Quantity':2},{'Item No': 3,'Weight':500,'Quantity':2},{'Item No': 4,'Weight':484,'Quantity':2},{'Item No': 5,'Weight':470,'Quantity':2},{'Item No': 6,'Weight':440,'Quantity':2},{'Item No': 7,'Weight':440,'Quantity':2},{'Item No': 8,'Weight':400,'Quantity':2}] </code></pre> <p>I have created a list of weights from above like this: </p> <pre><code>ItemWeigths: [610.0, 610.0, 500.0, 484.0, 470.0, 440.0,440, 400.0] </code></pre> <p>I would like to pack the items in shelves such that the total weight of each shelf is less than a particular value and have a list in the following format:</p> <pre><code>shelves = [[{'Item No': 1,'Weight':610,'Quantity':2}],[{'Item No': 2,'Weight':610,'Quantity':2}],[{'Item No': 3,'Weight':500,'Quantity':2}],[{'Item No': 4,'Weight':484,'Quantity':2}], [{'Item No': 7,'Weight':440,'Quantity':2}],[{'Item No': 8,'Weight':400,'Quantity':2}] ] </code></pre> <p>where the sum of the all the weights of a particular shelf is &lt;= 610</p> <p>I have created a code that it is packing the first shelf correctly but I am unable to write the code for creating shelves for other items:</p> <pre><code>shelves=[] ShelvesWeightTotal = 0 shelf=[] new=[] ShelfToPack=[] for i in range(0,len(ItemWeigths)): while ShelvesWeightTotal + ItemWeigths[i] &lt;= WeightOfObject: shelves += [ItemWeigths[i]] ShelvesWeightTotal = sum(shelves) </code></pre> <p>The above code works for 1st item but to create other shelves for remaining items I wrote the code which doesnot work:</p> <pre><code>for i in range(0,len(ItemWeigths)): while ItemsToCut !=[]: if ShelvesWeightTotal + ItemWeigths[i] &lt;=WeightOfObject: shelves += [ItemWeigths[i]] ShelvesWeightTotal = sum(shelves) ItemWeigths.pop(i) ItemsToCut.pop(i) shelf.append(shelves) </code></pre> <p>Any suggestion to write the code to create shelves in a better way will be appreciated.</p>
0
2016-08-27T18:54:49Z
39,185,394
<pre><code>ListDictItem = [ {'Item No': 1,'Weight':610,'Quantity':2},{'Item No': 2,'Weight':610,'Quantity':2},{'Item No': 3,'Weight':500,'Quantity':2},{'Item No': 4,'Weight':484,'Quantity':2},{'Item No': 5,'Weight':470,'Quantity':2},{'Item No': 6,'Weight':440,'Quantity':2},{'Item No': 7,'Weight':440,'Quantity':2},{'Item No': 8,'Weight':400,'Quantity':2}]; sh = []; #weight, itemNo for a in ListDictItem: for b in range(0, a['Quantity']): for j in range(0, len(sh)): if sh[j]['weight'] + a['Weight'] &lt;= 610: sh[j]['weight'] += a['Weight'] sh[j]['items'].append(a['Item No']) else: sh.append({'weight' : a['Weight'], 'items' : [a['Item No']]}) print(sh) </code></pre> <p>A very simple solution to your problem.</p>
0
2016-08-27T20:19:33Z
[ "python", "list", "python-3.x", "dictionary" ]
Classifier.fit(X,y) error
39,184,664
<p>I'm trying some machine learning algorithms.</p> <p>I'm using sklearn tool for logistic regression script.</p> <p>this is my script:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from sklearn.linear_model import LogisticRegression #from sklearn.neighbors import KNeighborsClassifier X = np.array([[10000,80000,35],[7000,120000,57],[100,23000,22],[223,18000,26]]) y = np.array([1,1,0,0]).reshape((1, -1)) classifier = LogisticRegression() classifier.fit(X,y) print(classifier.predict([5500,80000,25])) </code></pre> <p>The error that I got : </p> <pre><code>Traceback (most recent call last): File "logictic_regression2.py", line 11, in &lt;module&gt; classifier.fit(X,y) File "/usr/local/lib/python2.7/dist-packages/sklearn/linear_model logistic.py", line 1142, in fit order="C") File "/usr/local/lib/python2.7/dist-packages/sklearn/utils validation.py", line 515, in check_X_y y = column_or_1d(y, warn=True) File "/usr/local/lib/python2.7/dist-packages/sklearn/util /validation.py", line 551, in column_or_1d raise ValueError("bad input shape {0}".format(shape)) ValueError: bad input shape (1, 4) </code></pre>
-1
2016-08-27T18:55:29Z
39,184,785
<p>The <code>LogisticRegression.fit()</code> method expects a one-dimensional array for the target vector <code>y</code>. The error you mentioned should be gone if you remove the <code>.reshape((1, -1))</code> that converts it into a 1x4 matrix (row vector).</p> <p>Furthermore, the last line of your code</p> <pre><code>print(classifier.predict([5500,80000,25])) </code></pre> <p>raises a warning (at least in sklearn version 0.17.1) as for data a row per observation is expected. If you pass a two-dimensional numpy array (1x3 matrix) (<code>np.array([[5500,80000,25]]))</code>) everything works as expected.</p>
0
2016-08-27T19:11:08Z
[ "python", "scikit-learn" ]
SciKit Learn - Mathematical model behind linear regression?
39,184,669
<p>What mathematical model does the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression" rel="nofollow">Linear Regression</a> function use in scikit learn? The Ordinary Least Squares model has more than one way to minimize the cost function. I've found the form of the function it solves <a href="http://scikit-learn.org/stable/modules/linear_model.html" rel="nofollow">here</a>, but I'm also interested which method it uses exactly. Can anyone elaborate? Thank you!</p>
2
2016-08-27T18:56:39Z
39,184,847
<p>You can basically hunt around the source code enough, and you'll find it.</p> <ul> <li><p>In <a href="https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/linear_model/base.py#L349" rel="nofollow"><code>base.py</code></a>, you can find it uses <code>linal.lstsq</code>.</p></li> <li><p>In <a href="https://github.com/numpy/numpy/blob/master/numpy/linalg/linalg.py" rel="nofollow"><code>linalg.py</code></a>, you can see that <code>lstsq</code> uses the <a href="https://software.intel.com/sites/products/documentation/doclib/mkl_sa/11/mkl_lapack_examples/dgelsd.htm" rel="nofollow"><code>dglelsd</code> family</a>. </p></li> <li><p>This family is SVD-related. It <a href="http://math.stackexchange.com/questions/974193/why-does-svd-provide-the-least-squares-solution-to-ax-b">uses SVD to solve the original problem</a>.</p></li> </ul>
0
2016-08-27T19:19:41Z
[ "python", "math", "scikit-learn", "linear-regression" ]
Process a dictionary based on types of it's value and generate another dictionary by using dictionary comprehension
39,184,703
<p>Input dictionary </p> <pre><code>{11: [1, 2], 23: 'ewewe', 3: [4], 41: 5, 55: 6} </code></pre> <p>I need to form another dictionary based on types of items in input dictionary, it would be like :- </p> <pre><code>{type: list of keys which has this type} </code></pre> <p>Expected output would be</p> <pre><code>{&lt;type 'list'&gt;: [11, 3], &lt;type 'str'&gt;: [23], &lt;type 'int'&gt;: [41, 55]} </code></pre> <p>I have written below code for this:- </p> <pre><code>input_dict = {1: [1, 2], 2: 'ewewe', 3: [4], 4: 5, 5: 6} &gt;&gt;&gt; d = {} &gt;&gt;&gt; seen = [] for key,val in input_dict.items(): if type(val) in seen: d[type(val)].append(key) else: seen.append(type(val)) d[type(val)] = [key] &gt;&gt;&gt; d {&lt;type 'list'&gt;: [1, 3], &lt;type 'str'&gt;: [2], &lt;type 'int'&gt;: [4, 5]} </code></pre> <p>I am trying to replace above code with dictionary comprehension, I couldn't do it after spending hours, Any help would be appreciated. Thanks in advance...</p>
3
2016-08-27T19:01:13Z
39,184,722
<p>You can't do this with dictionary comprehension (only with one), instead as a more pythonic way you can use <code>collections.defaultdict()</code>:</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; d = defaultdict(list) &gt;&gt;&gt; &gt;&gt;&gt; test = {11: [1, 2], 23: 'ewewe', 3: [4], 41: 5, 55: 6} &gt;&gt;&gt; &gt;&gt;&gt; for i, j in test.items(): ... d[type(j)].append(i) ... &gt;&gt;&gt; d defaultdict(&lt;type 'list'&gt;, {&lt;type 'list'&gt;: [3, 11], &lt;type 'str'&gt;: [23], &lt;type 'int'&gt;: [41, 55]}) &gt;&gt;&gt; </code></pre>
1
2016-08-27T19:04:10Z
[ "python", "dictionary", "dictionary-comprehension" ]
Process a dictionary based on types of it's value and generate another dictionary by using dictionary comprehension
39,184,703
<p>Input dictionary </p> <pre><code>{11: [1, 2], 23: 'ewewe', 3: [4], 41: 5, 55: 6} </code></pre> <p>I need to form another dictionary based on types of items in input dictionary, it would be like :- </p> <pre><code>{type: list of keys which has this type} </code></pre> <p>Expected output would be</p> <pre><code>{&lt;type 'list'&gt;: [11, 3], &lt;type 'str'&gt;: [23], &lt;type 'int'&gt;: [41, 55]} </code></pre> <p>I have written below code for this:- </p> <pre><code>input_dict = {1: [1, 2], 2: 'ewewe', 3: [4], 4: 5, 5: 6} &gt;&gt;&gt; d = {} &gt;&gt;&gt; seen = [] for key,val in input_dict.items(): if type(val) in seen: d[type(val)].append(key) else: seen.append(type(val)) d[type(val)] = [key] &gt;&gt;&gt; d {&lt;type 'list'&gt;: [1, 3], &lt;type 'str'&gt;: [2], &lt;type 'int'&gt;: [4, 5]} </code></pre> <p>I am trying to replace above code with dictionary comprehension, I couldn't do it after spending hours, Any help would be appreciated. Thanks in advance...</p>
3
2016-08-27T19:01:13Z
39,184,772
<p>Using <code>defaultdict</code> and dictionary comprehension (kind of):</p> <pre><code>from collections import defaultdict input_dict = {1: [1, 2], 2: 'ewewe', 3: [4], 4: 5, 5: 6} d = defaultdict(list) {d[type(value)].append(key) for key, value in input_dict.items()} d = dict(d) print(d) </code></pre> <p><strong>Output</strong></p> <pre><code>{&lt;type 'list'&gt;: [1, 3], &lt;type 'int'&gt;: [4, 5], &lt;type 'str'&gt;: [2]} </code></pre>
1
2016-08-27T19:09:46Z
[ "python", "dictionary", "dictionary-comprehension" ]
Update program: overwrite files?
39,184,705
<p>I'm developing a software and I want, for several reasons, to develop my own auto-update feature. The program is a full GUI, written with PyQt, and uses icons, data files, etc. It will be frozen with cx_freeze or pyinstaller.</p> <p>The auto-update part will download the new version (a zip) on a remote server. Then, it gets complicated:</p> <p>The software is running, and has downloaded the new version. What does it do with the new version ? Can the software extract the files from the zip, and overwrite the files of the running version ?</p> <p>Or should I store the new version aside, quit the running version, and somehow use the new version ? If so, how do I do the exchange between the old and new version ?</p> <p>EDIT:</p> <p>Here is for example the <code>closeEvent</code> method of my class QMainWindow:</p> <pre><code>def closeEvent(self, event): """Method to perform actions before exiting. Allows to save the prefs in a file""" ...Do some stuff... QtGui.qApp.quit() self.logger.info("Closing the program") </code></pre> <p>Can I use this method to perform the exchange ?</p>
0
2016-08-27T19:01:36Z
39,190,539
<p>This is a similar <a href="http://stackoverflow.com/questions/16549331/pyqt-application-performing-updates">question</a> to yours and the accepted answer says:</p> <blockquote> <p>After downloading the installer for the newer version, you can use <a href="http://docs.python.org/2/library/atexit.html#atexit.register" rel="nofollow"><code>atexit.register()</code></a> with <a href="http://docs.python.org/3.3/library/os#os.execl" rel="nofollow"><code>os.exec*()</code></a> to run the installer, e.g. <code>atexit.register(os.execl, "installer.exe", "installer.exe")</code>. This will make the installer start when the application is about to exit. The application will immediately exit after the <code>os.exec*()</code> call, so no race condition will occur.</p> </blockquote> <p>Looks like a good solution for your use-case</p>
0
2016-08-28T10:56:45Z
[ "python", "pyqt", "auto-update" ]
exponent digits in scientific notation in Python
39,184,719
<p>In Python, scientific notation always gives me 2 digits in exponent:</p> <pre><code>print('%17.8E\n' % 0.0665745511651039) 6.65745512E-02 </code></pre> <p>However, I badly want to have 3 digits like:</p> <pre><code>6.65745512E-002 </code></pre> <p>Can we do this with a built-in configuration/function in Python?</p> <p>I know my question is basically the same question as: <a href="http://stackoverflow.com/questions/9910972/python-number-of-digits-in-exponent">Python - number of digits in exponent</a>, but this question was asked 4 years ago and I don't want to call such a function thousand times. I hope there should be a better solution now.</p>
1
2016-08-27T19:03:44Z
39,186,094
<p>Unfortunately, you can not change this default behavior since you can not override the <code>str</code> methods. </p> <p>However, you can wrap the float, and use the <code>__format__</code> method:</p> <pre><code>class MyNumber: def __init__(self, val): self.val = val def __format__(self,format_spec): ss = ('{0:'+format_spec+'}').format(self.val) if ( 'E' in ss): mantissa, exp = ss.split('E') return mantissa + 'E'+ exp[0] + '0' + exp[1:] return ss print( '{0:17.8E}'.format( MyNumber(0.0665745511651039))) </code></pre>
1
2016-08-27T21:55:25Z
[ "python", "scientific-notation", "exponent" ]
exponent digits in scientific notation in Python
39,184,719
<p>In Python, scientific notation always gives me 2 digits in exponent:</p> <pre><code>print('%17.8E\n' % 0.0665745511651039) 6.65745512E-02 </code></pre> <p>However, I badly want to have 3 digits like:</p> <pre><code>6.65745512E-002 </code></pre> <p>Can we do this with a built-in configuration/function in Python?</p> <p>I know my question is basically the same question as: <a href="http://stackoverflow.com/questions/9910972/python-number-of-digits-in-exponent">Python - number of digits in exponent</a>, but this question was asked 4 years ago and I don't want to call such a function thousand times. I hope there should be a better solution now.</p>
1
2016-08-27T19:03:44Z
39,188,256
<p>You can use your own formatter and override <code>format_field</code>:</p> <pre><code>import string class MyFormatter(string.Formatter): def format_field(self, value, format_spec): ss = string.Formatter.format_field(self,value,format_spec) if format_spec.endswith('E'): if ( 'E' in ss): mantissa, exp = ss.split('E') return mantissa + 'E'+ exp[0] + '0' + exp[1:] return ss print( MyFormatter().format('{0:17.8E}',0.00665745511651039) ) </code></pre>
0
2016-08-28T05:19:08Z
[ "python", "scientific-notation", "exponent" ]
ComboBox with two columns
39,184,776
<p>I'm trying to create a <code>GtkComboBox</code> with two columns. I picked up some examples and I'm trying to adapt but without success. Only the items that would be the second column are shown.</p> <pre><code>#!/usr/bin/env python3 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class ComboBox(Gtk.Window): def __init__(self): Gtk.Window.__init__(self) self.set_title("ComboBox") self.set_default_size(150, -1) self.connect("destroy", Gtk.main_quit) slist = Gtk.ListStore(str, str) slist.append(['01', 'Ferro']) slist.append(['07', 'Uranio']) slist.append(['08', 'Cobalto']) combobox = Gtk.ComboBox() combobox.set_model(slist) combobox.set_active(0) combobox.set_wrap_width(2) self.add(combobox) cellrenderertext = Gtk.CellRendererText() combobox.pack_start(cellrenderertext, True) combobox.add_attribute(cellrenderertext, "text", 1) window = ComboBox() window.show_all() Gtk.main() </code></pre> <p>I want create a <code>GtkComboBox</code> like this:</p> <p><a href="http://i.stack.imgur.com/bJo1s.gif" rel="nofollow"><img src="http://i.stack.imgur.com/bJo1s.gif" alt="enter image description here"></a></p>
1
2016-08-27T19:10:21Z
39,184,892
<p>There must be a CellRendererText for each column to be displayed.</p> <pre><code>cell1 = Gtk.CellRendererText() cell2 = Gtk.CellRendererText() combobox.pack_start(cell1, True) combobox.pack_start(cell2, True) combobox.add_attribute(cell1, "text", 0) combobox.add_attribute(cell2, "text", 1) </code></pre>
1
2016-08-27T19:23:23Z
[ "python", "python-3.x", "gtk", "gtk3" ]
How to efficiently find all paths formed by k number of nodes in a directed acyclic graph?
39,184,881
<p>I have a DAG that looks like this: <a href="http://i.stack.imgur.com/d4MN0.png" rel="nofollow">Example DAG</a></p> <p>I want to extract all the paths constituted by 4 nodes in this graph.</p> <p>My expected result should look like this:</p> <p>N1 -> N2 -> N3 -> N4</p> <p>N1 -> N2 -> N3 -> N5</p> <p>N1 -> N3 -> N4 -> N5</p> <p>N2 -> N3 -> N4 -> N5</p> <p>My current attempt looks like this</p> <pre><code>def path_finder(n1): paths = [] if DAG.has_node(n1): for n2 in DAG.successors(n1): for n3 in DAG.successors(n2): for n4 in DAG.successors(n3): paths.append([n1, n2, n3, n4]) return paths </code></pre> <p>I'm calling this function for each node. <code>DAG</code> is a global variable, more specifically it is a <code>networkx</code> object (<code>DAG = networkx.DiGraph()</code> ) This naive function is pathetically slow. Is there a more efficient strategy to do this?</p> <p>I have looked at question <a href="http://stackoverflow.com/questions/20262712/enumerating-all-paths-in-a-directed-acyclic-graph">20262712</a> but was self-solved by the author of the question in rather obscure way. </p> <p>Thanks</p> <p>UPDATE:</p> <p>Since I couldn't get any satisfactory algorithm to solve this, I ended up parallelizing the job using my naive function as a worker while dumping all the data into a queue. I used <code>pool.imap_unordered</code> to launch worker function and aggregated the results from queue. It still is slow (takes couple of hours for 5M nodes). I should also furnish the data for the average degree of nodes that I'm dealing with, because that will have an effect upon how fast my workers runs. But, I'll leave that out for now.</p>
2
2016-08-27T19:22:31Z
39,185,156
<p>Part of your problem could be that if you come across a node <code>u</code> as the second node in a path then you do all of the calculations to find all the paths of length 3. But then if you come across <code>u</code> again as the second node, you repeat all of these calculations.</p> <p>So try to avoid this. We'll do it recursively calculating all the length 3 paths first (which requires calculating length 2 paths)</p> <pre><code>def get_paths(G, n): '''returns a dict, paths, such that paths[u] is a list of all paths of length n that start from u''' if n == 1: #base case, return a dict so that D[u] is a #list of all length 1 paths starting from u. #it's a boring list. return {u: [[u]] for u in G.nodes()} #if we get to here n&gt;1 (unless input was bad) subpath_dict = get_paths(G,n-1) #contains all length n-1 paths, #indexed by first node path_dict = {} for u in G: path_dict[u] = [] for v in G.successors(u): path_dict[u].extend([[u]+subpath for subpath in subpath_dict[v]]) return(path_dict) G=nx.DiGraph() G.add_path([1,2,3,4,5,6]) G.add_path([1,3,6,8,10]) path_dict = get_paths(G,4) path_list = [] for paths in path_dict.values(): path_list.extend(paths) </code></pre>
0
2016-08-27T19:52:20Z
[ "python", "algorithm", "graph", "networkx", "graph-traversal" ]
How to efficiently find all paths formed by k number of nodes in a directed acyclic graph?
39,184,881
<p>I have a DAG that looks like this: <a href="http://i.stack.imgur.com/d4MN0.png" rel="nofollow">Example DAG</a></p> <p>I want to extract all the paths constituted by 4 nodes in this graph.</p> <p>My expected result should look like this:</p> <p>N1 -> N2 -> N3 -> N4</p> <p>N1 -> N2 -> N3 -> N5</p> <p>N1 -> N3 -> N4 -> N5</p> <p>N2 -> N3 -> N4 -> N5</p> <p>My current attempt looks like this</p> <pre><code>def path_finder(n1): paths = [] if DAG.has_node(n1): for n2 in DAG.successors(n1): for n3 in DAG.successors(n2): for n4 in DAG.successors(n3): paths.append([n1, n2, n3, n4]) return paths </code></pre> <p>I'm calling this function for each node. <code>DAG</code> is a global variable, more specifically it is a <code>networkx</code> object (<code>DAG = networkx.DiGraph()</code> ) This naive function is pathetically slow. Is there a more efficient strategy to do this?</p> <p>I have looked at question <a href="http://stackoverflow.com/questions/20262712/enumerating-all-paths-in-a-directed-acyclic-graph">20262712</a> but was self-solved by the author of the question in rather obscure way. </p> <p>Thanks</p> <p>UPDATE:</p> <p>Since I couldn't get any satisfactory algorithm to solve this, I ended up parallelizing the job using my naive function as a worker while dumping all the data into a queue. I used <code>pool.imap_unordered</code> to launch worker function and aggregated the results from queue. It still is slow (takes couple of hours for 5M nodes). I should also furnish the data for the average degree of nodes that I'm dealing with, because that will have an effect upon how fast my workers runs. But, I'll leave that out for now.</p>
2
2016-08-27T19:22:31Z
39,185,177
<p>Here is a function that returns the paths of a given length between all nodes in the graph. It iterates between all sets of nodes and uses the <code>networkx.all_simple_paths</code> to get the paths.</p> <pre><code>import networkx as nx g = nx.DiGraph() g.add_nodes_from(['A','B','C','D','E']) g.add_path(['A','B','C','D']) g.add_path(['A','B','C','E']) g.add_path(['A','C','D','E']) g.add_path(['B','C','D','D']) def find_paths(graph, number_nodes=4): paths = [] for source in graph.nodes_iter(): for target in graph.nodes_iter(): if not source==target: p_source_target = nx.all_simple_paths(graph, source, target, cutoff=number_nodes-1) paths.extend([p for p in p_source_target if len(p)==number_nodes]) return paths find_paths(g) # output: [['B', 'C', 'D', 'E'], ['A', 'C', 'D', 'E'], ['A', 'B', 'C', 'E'], ['A', 'B', 'C', 'D']] </code></pre>
0
2016-08-27T19:54:03Z
[ "python", "algorithm", "graph", "networkx", "graph-traversal" ]
How to efficiently find all paths formed by k number of nodes in a directed acyclic graph?
39,184,881
<p>I have a DAG that looks like this: <a href="http://i.stack.imgur.com/d4MN0.png" rel="nofollow">Example DAG</a></p> <p>I want to extract all the paths constituted by 4 nodes in this graph.</p> <p>My expected result should look like this:</p> <p>N1 -> N2 -> N3 -> N4</p> <p>N1 -> N2 -> N3 -> N5</p> <p>N1 -> N3 -> N4 -> N5</p> <p>N2 -> N3 -> N4 -> N5</p> <p>My current attempt looks like this</p> <pre><code>def path_finder(n1): paths = [] if DAG.has_node(n1): for n2 in DAG.successors(n1): for n3 in DAG.successors(n2): for n4 in DAG.successors(n3): paths.append([n1, n2, n3, n4]) return paths </code></pre> <p>I'm calling this function for each node. <code>DAG</code> is a global variable, more specifically it is a <code>networkx</code> object (<code>DAG = networkx.DiGraph()</code> ) This naive function is pathetically slow. Is there a more efficient strategy to do this?</p> <p>I have looked at question <a href="http://stackoverflow.com/questions/20262712/enumerating-all-paths-in-a-directed-acyclic-graph">20262712</a> but was self-solved by the author of the question in rather obscure way. </p> <p>Thanks</p> <p>UPDATE:</p> <p>Since I couldn't get any satisfactory algorithm to solve this, I ended up parallelizing the job using my naive function as a worker while dumping all the data into a queue. I used <code>pool.imap_unordered</code> to launch worker function and aggregated the results from queue. It still is slow (takes couple of hours for 5M nodes). I should also furnish the data for the average degree of nodes that I'm dealing with, because that will have an effect upon how fast my workers runs. But, I'll leave that out for now.</p>
2
2016-08-27T19:22:31Z
39,344,130
<p>Number of sequences is of order |V|*d^3, where d is average node output degree. From how graph is created, d is bounded. I suppose that d is not very small (like &lt; 5). That means, for 5M nodes graph there are > 1G paths.</p> <p>Since finding one path is fast (they are short) it is not sure that DP like algorithm can help. DP like algorithms try to take an advantage of partially calculated data, so there is an overhead of storing and retrieving that data and maybe that is larger overhead than just to calculate needed partial data.</p> <p>One idea is algorithm that traverse DAG in back topological order and do two things:</p> <ul> <li>for node keep all paths that starts from that node of length 3,</li> <li>using successors paths of length 3 print all paths of length 4.</li> </ul> <p>This method can use lot of memory, but some of it can be freed for nodes that are not successor of any traverse boundary node.</p> <p>Other idea is just to make simple algorithm more optimized. In your solution there are three for loops for each node. That means four for loops for all paths. Note that each loop is through nodes. It is possible to join first two loops by iterating through edges. That is due each path has to start with one edge. Algorithm is like:</p> <pre><code>for n1, n2 in DAG.edges(): for n3 in DAG.successors(n2): for n4 in DAG.successors(n3): paths.append([n1, n2, n3, n4]) </code></pre> <p>Or even simpler by first selecting middle edge:</p> <pre><code>for n2, n3 in DAG.edges(): for n1, n4 in itertools.product(DAG.predecessors(n2), DAG.successors(n3)): paths.append([n1, n2, n3, n4]) </code></pre> <p>Outer loop can be optimized by not selecting middle edge that starts on source node or ends on target node. But that is quite fast detected in product() method. Maybe this optimization can help by not sending not needed data into other process.</p>
0
2016-09-06T08:27:33Z
[ "python", "algorithm", "graph", "networkx", "graph-traversal" ]
ValueError: math domain error, keeps popping up
39,185,025
<p>I keep getting this message from time to time. i tried all variations, changing the way i use the sqrt, doing it step by step..etc But still this error keeps popping up. It might be a rookie mistake which i am not noticing since i am new to python and ubuntu. This is my source code:-(a very simple program)</p> <pre><code>#To find the area of a triangle a=input("Input the side 'a' of a triangle ") b=input("Input the side 'b' of a trianlge ") c=input("Input the side 'c' of a triangle ") from math import * s=(a+b+c)/2 sq=(s*(s-a)*(s-b)*(s-c)) area=(sqrt(sq)) perimeter=2*(a+b) print "Area = ", area print "perimeter=", perimeter </code></pre> <p>and this is the error i keep getting </p> <pre><code>Traceback (most recent call last): line 8, in &lt;module&gt; area=(sqrt(sq)) ValueError: math domain error </code></pre>
0
2016-08-27T19:37:05Z
39,185,060
<p>If a,b,c doesn't form a triangle, sq will come out to be -ve. Check if <code>s*(s-a)*(s-b)*(s-c)</code> is positive because sqrt(-ve number) is a complex number. </p> <p>To resolve this issue, you can use exception handling. </p> <pre><code>try: a=input("Input the side 'a' of a triangle ") b=input("Input the side 'b' of a trianlge ") c=input("Input the side 'c' of a triangle ") from math import * s=(a+b+c)/2 sq=(s*(s-a)*(s-b)*(s-c)) area=(sqrt(sq)) perimeter=2*(a+b) print "Area = ", area print "perimeter=", perimeter except ValueError: print "Invalid sides of a triangle" </code></pre>
2
2016-08-27T19:41:24Z
[ "python", "math" ]
ValueError: math domain error, keeps popping up
39,185,025
<p>I keep getting this message from time to time. i tried all variations, changing the way i use the sqrt, doing it step by step..etc But still this error keeps popping up. It might be a rookie mistake which i am not noticing since i am new to python and ubuntu. This is my source code:-(a very simple program)</p> <pre><code>#To find the area of a triangle a=input("Input the side 'a' of a triangle ") b=input("Input the side 'b' of a trianlge ") c=input("Input the side 'c' of a triangle ") from math import * s=(a+b+c)/2 sq=(s*(s-a)*(s-b)*(s-c)) area=(sqrt(sq)) perimeter=2*(a+b) print "Area = ", area print "perimeter=", perimeter </code></pre> <p>and this is the error i keep getting </p> <pre><code>Traceback (most recent call last): line 8, in &lt;module&gt; area=(sqrt(sq)) ValueError: math domain error </code></pre>
0
2016-08-27T19:37:05Z
39,190,634
<p>As others have pointed out, your calculation for area using Heron's formula will involve the square root of a negative number if the three "sides" do not actually form a triangle. One answer showed how to handle that with exception handling. However, that does not catch the case where the three "sides" form a degenerate triangle, one with area zero and thus is not a traditional triangle. An example of that would be <code>a=1, b=2, c=3</code>. The exception also waits until you try the calculation to find the problem. Another approach is to check the values before the calculations, which will find the problem immediately and allows you to decide whether or not to accept a degenerate triangle. Here is one way to check:</p> <pre><code>a=input("Input the side 'a' of a triangle ") b=input("Input the side 'b' of a triangle ") c=input("Input the side 'c' of a triangle ") if a + b &lt;= c or b + c &lt;= a or c + a &lt;= b: print('Those values do not form a triangle.') else: # calculate </code></pre> <p>Here is another check, with only two inequalities rather than the traditional three:</p> <pre><code>if min(a,b,c) &lt;= 0 or sum(a,b,c) &lt;= 2*max(a,b,c): print('Those values do not form a triangle.') else: # calculate </code></pre> <p>If you want to allow degenerate triangles, remove the equal signs in the checks.</p>
1
2016-08-28T11:08:29Z
[ "python", "math" ]
additional column when saving pandas data frame to csv file
39,185,028
<p>Here the the code to process and save csv file, and raw input csv file and output csv file, using pandas on Python 2.7 and wondering why there is an additional column at the beginning when saving the file? Thanks.</p> <pre><code>c_a,c_b,c_c,c_d hello,python,pandas,0.0 hi,java,pandas,1.0 ho,c++,numpy,0.0 sample = pd.read_csv('123.csv', header=None, skiprows=1, dtype={0:str, 1:str, 2:str, 3:float}) sample.columns = pd.Index(data=['c_a', 'c_b', 'c_c', 'c_d']) sample['c_d'] = sample['c_d'].astype('int64') sample.to_csv('saved.csv') </code></pre> <p>Here is the saved file, there is an additional column at the beginning, whose values are <code>0, 1, 2</code>.</p> <pre><code>cat saved.csv ,c_a,c_b,c_c,c_d 0,hello,python,pandas,0 1,hi,java,pandas,1 2,ho,c++,numpy,0 </code></pre>
1
2016-08-27T19:37:46Z
39,185,114
<p>The additional column corresponds to the index of the dataframe and is aggregated once you read the CSV file. You can use this index to slice, select or sort your DF in an effective manner.</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.html</a></p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/indexing.html</a></p> <p>If you want to avoid this index, you can set the <code>index</code> flag to <code>False</code> when you save your dataframe with the function <code>pd.to_csv</code>. Also, you are removing the header and aggregating it later, but you can use the header of the CSV to avoid this step.</p> <pre><code>sample = pd.read_csv('123.csv', dtype={0:str, 1:str, 2:str, 3:float}) sample.to_csv('output.csv', index= False) </code></pre> <p>Hope it helps :)</p>
1
2016-08-27T19:47:16Z
[ "python", "python-2.7", "csv", "pandas", "dataframe" ]
Django Project Setup on Google VM
39,185,034
<p>I am trying to setup a django project on a VM by Google Compute Engine. I have done all the installations &amp; have copied the project on my VM. But I am not able to do the Apache/mod_wsgi Or Gunicorn/Nginx linking to make the project run end to end on the final IP address of VM. </p> <p>I have two queries:</p> <p>1) Which one is better Apache/mod_wsgi OR Gunicorn/Nginx OR any other ?</p> <p>2) Can someone please explain in simple step by step way to do this linking? </p> <p>Any one way Or some good Reference Link would also be appreciated.</p> <p>Thanks,</p>
0
2016-08-27T19:38:28Z
39,185,566
<p>Add the Following Code in /etc/apache2/sites-available/000-default.conf File. Do make corresponding changes acc. to your project path.</p> <p>1) sudo vim /etc/apache2/sites-available/000-default.conf</p> <p>2) Add below code between &amp; </p> <pre><code>&lt;VirtualHost *:80&gt; . . . Alias /static /home/user/myproject/static &lt;Directory /home/user/myproject/static&gt; Require all granted &lt;/Directory&gt; &lt;Directory /home/user/myproject/myproject&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; WSGIDaemonProcess myproject python-path=/home/user/myproject:/home/user/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/user/myproject/myproject/wsgi.py &lt;/VirtualHost&gt; </code></pre> <p>3) sudo chown :www-data ~/myproject/</p> <p>4) sudo service apache2 restart</p> <p>Now try hitting your IP address. Enjoy!</p> <p>Hope this might be helpful.</p> <p>Thanks,</p>
0
2016-08-27T20:41:49Z
[ "python", "django", "nginx", "virtual-machine", "google-compute-engine" ]
calculations for different columns in a numpy array
39,185,056
<p>I have a 2D array with filled with some values (column 0) and zeros (rest of the columns). I would like to do pretty much the same as I do with MS excel but using numpy, meaning to put into the rest of the columns values from calculations based on the first column. Here it is a MWE:</p> <pre><code>import numpy as np a = np.zeros(20, dtype=np.int8).reshape(4,5) b = [1, 2, 3, 4] b = np.array(b) a[:, 0] = b # don't change the first column for column in a[:, 1:]: a[:, column] = column[0]+1 </code></pre> <p>The expected output:</p> <pre><code>array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]], dtype=int8) </code></pre> <p>The resulting output:</p> <pre><code>array([[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]], dtype=int8) </code></pre> <p>Any help would be appreciated.</p>
2
2016-08-27T19:40:35Z
39,185,102
<p>Your usage of <code>column</code> is a little ambiguous: in <code>for column in a[:, 1:]</code>, it is treated as a column and in the body, however, it is treated as index to the column. You can try this instead:</p> <pre><code>for column in range(1, a.shape[1]): a[:, column] = a[:, column-1]+1 a #array([[1, 2, 3, 4, 5], # [2, 3, 4, 5, 6], # [3, 4, 5, 6, 7], # [4, 5, 6, 7, 8]], dtype=int8) </code></pre>
1
2016-08-27T19:45:51Z
[ "python", "numpy" ]
calculations for different columns in a numpy array
39,185,056
<p>I have a 2D array with filled with some values (column 0) and zeros (rest of the columns). I would like to do pretty much the same as I do with MS excel but using numpy, meaning to put into the rest of the columns values from calculations based on the first column. Here it is a MWE:</p> <pre><code>import numpy as np a = np.zeros(20, dtype=np.int8).reshape(4,5) b = [1, 2, 3, 4] b = np.array(b) a[:, 0] = b # don't change the first column for column in a[:, 1:]: a[:, column] = column[0]+1 </code></pre> <p>The expected output:</p> <pre><code>array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]], dtype=int8) </code></pre> <p>The resulting output:</p> <pre><code>array([[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]], dtype=int8) </code></pre> <p>Any help would be appreciated.</p>
2
2016-08-27T19:40:35Z
39,185,121
<p>Looping is slow and there is no need to loop to produce the array that you want:</p> <pre><code>&gt;&gt;&gt; a = np.ones(20, dtype=np.int8).reshape(4,5) &gt;&gt;&gt; a[:, 0] = b &gt;&gt;&gt; a array([[1, 1, 1, 1, 1], [2, 1, 1, 1, 1], [3, 1, 1, 1, 1], [4, 1, 1, 1, 1]], dtype=int8) &gt;&gt;&gt; np.cumsum(a, axis=1) array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]]) </code></pre> <h3>What went wrong</h3> <p>Let's start, as in the question, with this array:</p> <pre><code>&gt;&gt;&gt; a array([[1, 0, 0, 0, 0], [2, 0, 0, 0, 0], [3, 0, 0, 0, 0], [4, 0, 0, 0, 0]], dtype=int8) </code></pre> <p>Now, using the code from the question, let's do the loop and see what <code>column</code> actually is:</p> <pre><code>&gt;&gt;&gt; for column in a[:, 1:]: ... print(column) ... [0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0] </code></pre> <p>As you can see, <code>column</code> is not the index of the column but the actual values in the column. Consequently, the following does not do what you would hope:</p> <pre><code>a[:, column] = column[0]+1 </code></pre> <h3>Another method</h3> <p>If we want to loop (so that we can do something more complex), here is another approach to generating the desired array:</p> <pre><code>&gt;&gt;&gt; b = np.array([1, 2, 3, 4]) &gt;&gt;&gt; np.column_stack([b+i for i in range(5)]) array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]]) </code></pre>
2
2016-08-27T19:48:05Z
[ "python", "numpy" ]
Multiple unexpected errors
39,185,086
<p>I'm not entirely sure what is wrong with these line, I don't understand why they are problematic. In the order of the problems (failing line will be highlighted with ***)</p> <p>File "C:\Users\Harry\Desktop\CS Project\game test", line 32, in drawArena pygame.draw.line(DISPLAYSURF, WHITE, ((WINDOWWIDTH/2),0),((WINDOWWIDTH/2),WINDOWHEIGHT), (LINETHICKNESS/4)) TypeError: integer argument expected, got float</p> <p>File "C:\Users\Harry\Desktop\CS Project\game test", line 144, in main drawArena()</p> <p>File "C:\Users\Harry\Desktop\CS Project\game test", line 178, in main()</p> <pre><code>def drawArena(): DISPLAYSURF.fill((0,0,0)) #Draw outline of arena pygame.draw.rect(DISPLAYSURF, WHITE, ((0,0),(WINDOWWIDTH,WINDOWHEIGHT)), LINETHICKNESS*2) #Draw centre line ***pygame.draw.line(DISPLAYSURF, WHITE, ((WINDOWWIDTH/2),0),((WINDOWWIDTH/2),WINDOWHEIGHT), (LINETHICKNESS/4))*** ***drawArena()*** drawPaddle(paddle1) drawPaddle(paddle2) drawBall(ball) if __name__ == '__main__': ***main()*** </code></pre>
-1
2016-08-27T19:44:43Z
39,185,155
<p>It's telling you the error. When using the method <code>pygame.draw.line()</code>, you must provide integer arguments for the dimensions of the line. If you look at your problematic line:</p> <p><code>pygame.draw.line(DISPLAYSURF, WHITE, ((WINDOWWIDTH/2),0),((WINDOWWIDTH/2),WINDOWHEIGHT), (LINETHICKNESS/4))</code></p> <p>One or more of the quotients of those division operations are resulting in a float(decimal) number. One simple way to fix this is to use the Python <code>int()</code> function to round any of your decimals to a whole number, like so:</p> <p><code>pygame.draw.line(int((WINDOWWIDTH/2)),0),(int((WINDOWWIDTH/2)),WINDOWHEIGHT), int((LINETHICKNESS/4)))</code></p> <p>If int, for some reason is not suitable, you can also use the Python <code>round()</code> function:</p> <p><code>pygame.draw.line(round((WINDOWWIDTH/2)),0),(round((WINDOWWIDTH/2)),WINDOWHEIGHT), round((LINETHICKNESS/4)))</code></p>
1
2016-08-27T19:52:09Z
[ "python", "python-3.x" ]
How to call a dictionary from my first function in my second function in Python
39,185,157
<p>I am pretty new to Python and to help new learn, I am building a program, which I want broken down into 2 steps:</p> <p>Step 1) Count the number of a particular words in a text file, store that in a dictionary where the key, value pairs are {word, count}</p> <p>Step 2) Order the dictionary from (1) in descending order, to show the top 100 words</p> <p>Step 1 works fine but in attempting step 2, I am struggling to call the dictionary from the first function. I create a new variable 'tallies' but this is a tuple and shows only the first entry in the dictionary.</p> <p>How do I call the full dictionary to my 2nd function?</p> <p>Thanks.</p> <pre><code>filename = 'nameoffile.txt' def tally(): file = open(filename,'r') wordcount={} for word in file.read().split(): if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 for k,v in wordcount.items(): return k,v def Count(): tallies = tally() print tallies Count() </code></pre>
0
2016-08-27T19:52:20Z
39,185,186
<p>These tasks are exactly what <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter()</code></a> is for. You can use this function in order to create a counter-dictionary object contains words and their frequency, you can call it on splited text. Then use <code>Counter.most_common(N)</code> to get most N common items.</p> <p>And regarding your code in following part:</p> <pre><code>for k,v in wordcount.items(): return k,v </code></pre> <p>After first iteration you are breaking the loop by <code>return</code> and it only will return the first item.</p> <p>You can simply return the dictionary:</p> <pre><code>def tally(): file = open(filename,'r') wordcount={} for word in file.read().split(): if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 return wordcount </code></pre> <p>You even could use <code>collections.defaultdict()</code> in order to create your counter object manually. The benefit of using this function is that it overrides one method and adds one writable instance variable.</p> <pre><code>from collections import defaultdict wordcount = defaultdict(int) # default is 0 def tally(): with open(filename) as f for word in f.read().split(): wordcount[word] += 1 return wordcount </code></pre> <p>And for returning the sorted items you can use <code>sorted()</code> function on dictionary items by passing a key function to it, to say that sort the items by second item. For example:</p> <pre><code>sorted(wordcount.items(), key=lambda x:x[1]) </code></pre> <p>But as I said the the first, the pythonic and optimized approach is using <code>collections. Counter()</code>.</p> <pre><code>from collections import Counter with open(filename) as f: wordcount = Counter(f.read().split()) top100 = wordcount.most_common(100) </code></pre>
0
2016-08-27T19:55:15Z
[ "python", "dictionary" ]
How to call a dictionary from my first function in my second function in Python
39,185,157
<p>I am pretty new to Python and to help new learn, I am building a program, which I want broken down into 2 steps:</p> <p>Step 1) Count the number of a particular words in a text file, store that in a dictionary where the key, value pairs are {word, count}</p> <p>Step 2) Order the dictionary from (1) in descending order, to show the top 100 words</p> <p>Step 1 works fine but in attempting step 2, I am struggling to call the dictionary from the first function. I create a new variable 'tallies' but this is a tuple and shows only the first entry in the dictionary.</p> <p>How do I call the full dictionary to my 2nd function?</p> <p>Thanks.</p> <pre><code>filename = 'nameoffile.txt' def tally(): file = open(filename,'r') wordcount={} for word in file.read().split(): if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 for k,v in wordcount.items(): return k,v def Count(): tallies = tally() print tallies Count() </code></pre>
0
2016-08-27T19:52:20Z
39,185,218
<p>your tally function is returning the first item it sees; <code>return</code> can only return once, but you're calling it in a loop. try returning the whole wordcount dict:</p> <pre><code>filename = 'nameoffile.txt' def tally(): file = open(filename,'r') wordcount={} for word in file.read().split(): if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 return wordcount def Count(): tallies = tally() sorted_tallies = sorted(tallies.items(), key=operator.itemgetter(1)) print sorted_tallies[:100] Count() </code></pre> <p>in python a <code>dict</code> is by nature unordered, so to order it you need to sort its tuples into a list. the <code>sorted</code> code does this (<a href="http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value">see this reference</a>).</p> <p>good luck!</p>
1
2016-08-27T19:58:59Z
[ "python", "dictionary" ]
How to call a dictionary from my first function in my second function in Python
39,185,157
<p>I am pretty new to Python and to help new learn, I am building a program, which I want broken down into 2 steps:</p> <p>Step 1) Count the number of a particular words in a text file, store that in a dictionary where the key, value pairs are {word, count}</p> <p>Step 2) Order the dictionary from (1) in descending order, to show the top 100 words</p> <p>Step 1 works fine but in attempting step 2, I am struggling to call the dictionary from the first function. I create a new variable 'tallies' but this is a tuple and shows only the first entry in the dictionary.</p> <p>How do I call the full dictionary to my 2nd function?</p> <p>Thanks.</p> <pre><code>filename = 'nameoffile.txt' def tally(): file = open(filename,'r') wordcount={} for word in file.read().split(): if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 for k,v in wordcount.items(): return k,v def Count(): tallies = tally() print tallies Count() </code></pre>
0
2016-08-27T19:52:20Z
39,185,320
<p>Your issue is that you returned <code>k,v</code> after the first iteration meaning you only ever grabbed the first item. The following code fixes this. I also added the reversal function.</p> <pre><code>def tally(): file = open(filename,'r') wordcount={} for word in file.read().split(): if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 return tuple(reversed(sorted(((k, v) for k, v in wordcount.items()),key=lambda x: x[1]))) def Count(): tallies = tally() print tallies </code></pre>
0
2016-08-27T20:10:55Z
[ "python", "dictionary" ]
Python 3.5 Tkinter How to separate 2 sets of radio buttons
39,185,158
<p>My first question here.</p> <p>I'm currently writing a GUI with Tkinter in Python 3.5.</p> <p>I have a settings frame in my application and I have radio buttons to let the user change them. There is no problem when I have only one set of radio buttons but when I add a second set of radio buttons, Python thinks that they all belong to the same set and the user can pick only one of the 6 radio buttons (I want the user to be able to pick a total of two, 1 for each set). Is there a way to tell Tkkinter/Python that there are 2 sets of radio buttons? I searched Stack Overflow with a few keywords, but most of the questions are about how to get values from radio buttons and none of them answer my question.</p> <p>Here is a example code of radio buttons, to help you imagine the situation:</p> <pre><code>import tkinter as tk #I'm not writing things like frames or stuff, this is just to #tell you how my radio buttons are categorized #I want these to be separate: s1r1=tk.Radiobutton(root,text="Red") #Set 1-Radiobutton 1 s1r2=tk.Radiobutton(root,text="Green") #Set 1-Radiobutton 2 s1r3=tk.Radiobutton(root,text="Blue") #Set 1-Radiobutton 3 #than these: s2r1=tk.Radiobutton(root,text="1") #Set 2-Radiobutton 1 s2r2=tk.Radiobutton(root,text="2") #Set 2-Radiobutton 2 s2r3=tk.Radiobutton(root,text="3") #Set 2-Radiobutton 3 </code></pre> <p>Thanks a lot!</p>
0
2016-08-27T19:52:22Z
39,185,249
<p>You didn't bind two different variables to your button groups. Each <code>Radiobutton</code> group has to be associated with a single <code>StringVar()</code> or <code>IntVar()</code>.</p> <pre><code>v1 = tk.StringVar() v2 = tk.StringVar() # Group 1 s1r1=tk.Radiobutton(root,text="Red", variable=v1) s1r2=tk.Radiobutton(root,text="Green", variable=v1) s1r3=tk.Radiobutton(root,text="Blue", variable=v1) # Group 2 s2r1=tk.Radiobutton(root,text="1", variable=v2) s2r2=tk.Radiobutton(root,text="2", variable=v2) s2r3=tk.Radiobutton(root,text="3", variable=v2) </code></pre>
2
2016-08-27T20:02:36Z
[ "python", "tkinter", "radio-button" ]
Pass variable into AppleScript from python
39,185,160
<p>Can someone show me how to pass a variable into an Applescript using osascript in python? I've seen some documentation/samples on doing this but I'm not understanding it at all. </p> <p>Here is my python code:</p> <pre><code># I want to pass this value into my apple script below myPythonVariable = 10 cmd = """ osascript -e ' tell application "System Events" set activeApp to name of first application process whose frontmost is true if "MyApp" is in activeApp then set stepCount to myPythonVariableIPassIn repeat with i from 1 to stepCount DoStuff... end repeat end if end tell ' """ os.system(cmd) </code></pre>
0
2016-08-27T19:52:33Z
39,192,929
<p>String concatenation with the <strong>+</strong> operator</p> <pre><code>myPythonVariable = 10 cmd = """ osascript -e ' tell application "System Events" set activeApp to name of first application process whose frontmost is true if "MyApp" is in activeApp then set stepCount to """ + str(myPythonVariable) + """ repeat with i from 1 to stepCount -- do something end repeat end if end tell ' """ </code></pre> <hr> <p>Or, string formatting with the <strong>{}</strong> :</p> <pre><code>myPythonVariable = 10 cmd = """ osascript -e ' tell application "System Events" set activeApp to name of first application process whose frontmost is true if "MyApp" is in activeApp then set stepCount to {0} repeat with i from 1 to stepCount -- do something end repeat end if end tell ' """.format(myPythonVariable) </code></pre> <p><strong>{0}</strong> is the place-holder for the first variable, <strong>{1}</strong> is the place-holder for the second variable, ....</p> <p>For multiple variables: </p> <blockquote> <p>.format(myPythonVariable, var2, var3)</p> </blockquote> <hr> <p>Or, string formatting with the <strong>%s</strong> operator</p> <pre><code>myPythonVariable = 10 cmd = """ osascript -e ' tell application "System Events" set activeApp to name of first application process whose frontmost is true if "MyApp" is in activeApp then set stepCount to %s repeat with i from 1 to stepCount -- do something end repeat end if end tell ' """ % myPythonVariable </code></pre> <p>For multiple variables: </p> <blockquote> <p>% (myPythonVariable, var2, var3)</p> </blockquote>
1
2016-08-28T15:36:51Z
[ "python", "applescript", "osascript" ]
Flask admin overrides password when user model is changed
39,185,230
<p>I am currently diving into a flask project and try to use flask-admin for the first time. Everything is working fine so far, but one thing really bothers me: Whenever I edit my User model the users password gets overwritten. I am following the advice given in the second answer of <a href="http://stackoverflow.com/questions/28970076/how-to-use-flask-admin-for-editing-modelview">this question</a> to prevent flask-admin from re-hashing my password. Unfortunately the emptied password field still gets written to the database.</p> <p>I tried to get the current password from the <code>User</code>-Model which is given as a parameter to the <code>on_model_change</code> method, but somehow the password seems to be already overwritten at that point (or it is not the actual database model I am looking at here - I am a little bit confused here).</p> <p>Here is what my code looks like:</p> <h2>User-Model</h2> <pre><code>class User(UserMixin, SurrogatePK, Model): """A user of the app.""" __tablename__ = 'users' username = Column(db.String(80), unique=True, nullable=False) email = Column(db.String(80), unique=True, nullable=False) #: The hashed password password = Column(db.String(128), nullable=True) created_at = Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) first_name = Column(db.String(30), nullable=True) last_name = Column(db.String(30), nullable=True) active = Column(db.Boolean(), default=False) is_admin = Column(db.Boolean(), default=False) def __init__(self, username="", email="", password=None, **kwargs): """Create instance.""" db.Model.__init__(self, username=username, email=email, **kwargs) if password: self.set_password(password) else: self.password = None def __str__(self): """String representation of the user. Shows the users email address.""" return self.email def set_password(self, password): """Set password""" self.password = bcrypt.generate_password_hash(password) def check_password(self, value): """Check password.""" return bcrypt.check_password_hash(self.password, value) def get_id(self): """Return the email address to satisfy Flask-Login's requirements""" return self.id @property def full_name(self): """Full user name.""" return "{0} {1}".format(self.first_name, self.last_name) @property def is_active(self): """Active or non active user (required by flask-login)""" return self.active @property def is_authenticated(self): """Return True if the user is authenticated.""" if isinstance(self, AnonymousUserMixin): return False else: return True @property def is_anonymous(self): """False, as anonymous users aren't supported.""" return False </code></pre> <h2>Flask-Admin UserView</h2> <pre><code>class UserView(MyModelView): """Flask user model view.""" create_modal = True edit_modal = True def on_model_change(self, form, User, is_created): if form.password.data is not None: User.set_password(form.password.data) else: del form.password def on_form_prefill(self, form, id): form.password.data = '' </code></pre> <p>Any help is highly appreciated. Thanks in advance,</p> <p>oneiro</p>
0
2016-08-27T20:00:10Z
39,190,347
<p>Might be easier to override the <code>get_edit_form</code> method and delete the password field entirely from the edit form. </p> <pre><code>class UserView(MyModelView): def get_edit_form(self): form_class = super(UserView, self).get_edit_form() del form_class.password return form_class </code></pre> <p>Another alternative would be to remove the model password field entirely from the form and use a dummy password field that can then be used to populate the model's password. By removing the real password field Flask-Admin will not step on our password data. Example :</p> <pre><code>class UserView(MyModelView): form_excluded_columns = ('password') # Form will now use all the other fields in the model # Add our own password form field - call it password2 form_extra_fields = { 'password2': PasswordField('Password') } # set the form fields to use form_columns = ( 'username', 'email', 'first_name', 'last_name', 'password2', 'created_at', 'active', 'is_admin', ) def on_model_change(self, form, User, is_created): if form.password2.data is not None: User.set_password(form.password2.data) </code></pre>
0
2016-08-28T10:29:41Z
[ "python", "flask", "flask-admin" ]
Use pip to Install to a different interpreter
39,185,255
<p>I downloaded Python2.7 a while ago to my C:\ directory. After that I downloaded pip to install packages. After that I installed the Anaconda interpreter to a different directory within my user. I prefer to use the Anaconda interpreter but every time I install a package with pip it is put in C:\Python27\Lib\site-packages. Is there any way I can change the install command with pip or some pip config file so that it installs packages to C:\path_to_anaconda_interpreter_in_user\Lib\site-packages?</p>
1
2016-08-27T20:03:35Z
39,185,406
<p>What you could do is create a symbolic link.</p> <p>Or in your case, on windows, a shortcut.</p> <p>So in your case : <code>C:\path_to_anaconda_interpreter_in_user\Lib\site-packages</code> would be a shortcut leading to <code>C:\Python27\Lib\site-packages</code></p> <p>(right click python27/lib/site-packages, click 'create shortcut' and move it into your anaconda lib directory)</p> <p><strong>Edit :</strong></p> <p>See Eryksun's comment below</p>
0
2016-08-27T20:20:41Z
[ "python", "windows", "pip" ]
bypass validation for form field django
39,185,272
<pre><code> class PostForm(forms.ModelForm): description = forms.CharField(widget=PagedownWidget(show_preview=False)) class Meta: model = Post fields = [ 'title', 'image', 'video', 'description', 'public', 'tags', ] </code></pre> <p>I am trying to bypass the required field for 'video' but having difficulty doing so. Any suggestions would be appreciated.</p> <p>this is my models.py, hopefully is should help with knowing how to go on this. </p> <pre><code> from django.db import models from django.db.models import Count, QuerySet, F from django.utils import timezone from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.db.models.signals import pre_save from django.utils.text import slugify from markdown_deux import markdown from django.utils.safestring import mark_safe from embed_video.fields import EmbedVideoField from taggit.managers import TaggableManager from comments.models import Comment def upload_location(instance, filename): return "%s/%s" %(instance.slug, filename) class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1 ) title = models.CharField(max_length=75) slug = models.SlugField(unique=True) video = EmbedVideoField() image = models.ImageField( upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) description = models.TextField() tags = TaggableManager() public = models.BooleanField(default=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) created = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"slug": self.slug}) class Meta: ordering = ["-created", "-updated" ] def get_markdown(self): description = self.description markdown_text = markdown(description) return mark_safe(markdown_text) @property def comments(self): instance = self qs = Comment.objects.filter_by_instance(instance) return qs @property def get_content_type(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) return content_type def create_slug(instance, new_slug=None): slug = slugify(instance.title) if new_slug is not None: slug = new_slug qs = Post.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_post_receiver, sender=Post) </code></pre>
-1
2016-08-27T20:05:39Z
39,185,391
<p>from <a href="https://pypi.python.org/pypi/django-embed-video" rel="nofollow">the docs</a> it looks like it should support empty now since version 0.3, i would suggest trying</p> <pre><code>video = EmbedVideoField(null=True,blank=True) </code></pre> <p>the docs say it should function like a URL field, so just the standard notation should be all you need.</p> <p>good luck!</p>
0
2016-08-27T20:19:17Z
[ "python", "django" ]
Are HSV values stored as VSH in numpy array?
39,185,277
<p>since RGB is stored as BGR ,does the same happens in the case of HSV ?</p> <p>I am making a project where i take input from webcam and convert it to HSV colour, to track object of a specific colour.</p>
0
2016-08-27T20:06:19Z
39,216,745
<p>No. It's HSV mode.</p> <p>Read the below code and its run on a sample image.</p> <pre><code>int main() { // Load your Red colored image cv::Mat frame = imread("test.png"); // Split each channel cv::Mat rgbChannels[3]; cv::split(frame, rgbChannels); cv::imshow("RGB", frame); // Check value of your Red, Blue and Green Channel double minVal, maxVal; // Note: Blue is first channel cv::minMaxLoc(rgbChannels[0], &amp;minVal, &amp;maxVal); std::cout &lt;&lt; "Blue: Min = " &lt;&lt; minVal &lt;&lt; ", Max = " &lt;&lt; maxVal &lt;&lt; std::endl; cv::minMaxLoc(rgbChannels[1], &amp;minVal, &amp;maxVal); std::cout &lt;&lt; "Green: Min = " &lt;&lt; minVal &lt;&lt; ", Max = " &lt;&lt; maxVal &lt;&lt; std::endl; cv::minMaxLoc(rgbChannels[2], &amp;minVal, &amp;maxVal); std::cout &lt;&lt; "Red: Min = " &lt;&lt; minVal &lt;&lt; ", Max = " &lt;&lt; maxVal &lt;&lt; std::endl; std::cout &lt;&lt; "*******************************" &lt;&lt; std::endl; cv::Mat hsv; cv::Mat hsvChannels[3]; // Convert BGR image to HSV. Dont use CV_RGB2HSV. cv::cvtColor(frame, hsv, CV_BGR2HSV); // Split each channel cv::split(hsv, hsvChannels); // **Display HSV image: Note: When displaying opencv does not display image as Red image** // This is because imshow will just take first channel which is hue and treat it as Blue, second channel as // Green, and last channel as Red. cv::imshow("HSV", hsv); cv::minMaxLoc(hsvChannels[0], &amp;minVal, &amp;maxVal); std::cout &lt;&lt; "Hue: Min = " &lt;&lt; minVal &lt;&lt; ", Max = " &lt;&lt; maxVal &lt;&lt; std::endl; cv::minMaxLoc(hsvChannels[1], &amp;minVal, &amp;maxVal); std::cout &lt;&lt; "Saturation: Min = " &lt;&lt; minVal &lt;&lt; ", Max = " &lt;&lt; maxVal &lt;&lt; std::endl; cv::minMaxLoc(hsvChannels[2], &amp;minVal, &amp;maxVal); std::cout &lt;&lt; "Value: Min = " &lt;&lt; minVal &lt;&lt; ", Max = " &lt;&lt; maxVal &lt;&lt; std::endl; waitKey(0); return 0; } </code></pre> <p><a href="http://i.stack.imgur.com/YVZsA.png" rel="nofollow"><img src="http://i.stack.imgur.com/YVZsA.png" alt="Red Image"></a></p> <p><strong>Output:-</strong></p> <pre><code>Blue: Min = 36, Max = 36 Green: Min = 28, Max = 28 Red: Min = 237, Max = 237 ******************************* Hue: Min = 179, Max = 179 Saturation: Min = 225, Max = 225 Value: Min = 237, Max = 237 </code></pre> <p><strong>Output Explanation</strong> Using this <a href="http://www.rapidtables.com/convert/color/rgb-to-hsv.htm" rel="nofollow">tool</a>, the RGB value (237, 28, 36) maps to HSV (358, 88.2, 92.9). Since, HUE ranges from 0 to 359, the value crosses 1-byte bound of allowing only 256 values. The HUE is divided by 2 to range from [0,179] in opencv to use less memory. The hue value 358 divided by 2 maps to 179 which is the first channel. Also, saturation and value are just normalized to scale 0-255. Thus as you can see saturation maps to second and value maps to third channel.</p>
1
2016-08-29T23:37:15Z
[ "python", "opencv", "numpy", "colors" ]
Python3 always shows ImportError message
39,185,360
<p>Whenever I try to run a script the python interpreter always shows an <code>ImportError</code> message such as (e.g.) <code>No module named 'setuptools'</code>. So, I tried install (or to satisfy this requirement) with <code>apt-get</code>... I do this for both Python 2.7 and Python 3.5 until <code>Requirement already satisfied</code>.</p> <p>First of all, I don't work with Python 2.7, but it's the defaul version for the interpreter. So, how could I solve this problem to work with Python 3.5? I tried this:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print(sys.path) ['', '/usr/local/lib/python35.zip', '/usr/local/lib/python3.5', '/usr/local/lib/python3.5/plat-linux', '/usr/local/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/site-packages'] </code></pre> <p>This was for <strong>Python3</strong>, for Python2 I did the same to compare the paths and I got this:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print(sys.path) ['', '/usr/local/lib/python2.7/dist-packages/pygame-1.9.2b8-py2.7-linux-x86_64.egg', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0'] </code></pre> <p>Now... Should it work if I use the <code>append()</code> method to add all the paths of Python2 to the paths in Python3? Also, I've been considered to completely uninstall Python2, but I know this will cause more problems in my system that the one I try to solve.</p>
0
2016-08-27T20:15:55Z
39,185,377
<p>try :</p> <pre><code>python3.5 -m pip install setuptools </code></pre>
2
2016-08-27T20:17:35Z
[ "python", "python-2.7", "python-3.x", "pip", "importerror" ]
Python3 always shows ImportError message
39,185,360
<p>Whenever I try to run a script the python interpreter always shows an <code>ImportError</code> message such as (e.g.) <code>No module named 'setuptools'</code>. So, I tried install (or to satisfy this requirement) with <code>apt-get</code>... I do this for both Python 2.7 and Python 3.5 until <code>Requirement already satisfied</code>.</p> <p>First of all, I don't work with Python 2.7, but it's the defaul version for the interpreter. So, how could I solve this problem to work with Python 3.5? I tried this:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print(sys.path) ['', '/usr/local/lib/python35.zip', '/usr/local/lib/python3.5', '/usr/local/lib/python3.5/plat-linux', '/usr/local/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/site-packages'] </code></pre> <p>This was for <strong>Python3</strong>, for Python2 I did the same to compare the paths and I got this:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print(sys.path) ['', '/usr/local/lib/python2.7/dist-packages/pygame-1.9.2b8-py2.7-linux-x86_64.egg', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0'] </code></pre> <p>Now... Should it work if I use the <code>append()</code> method to add all the paths of Python2 to the paths in Python3? Also, I've been considered to completely uninstall Python2, but I know this will cause more problems in my system that the one I try to solve.</p>
0
2016-08-27T20:15:55Z
39,186,569
<p>From your description of the problem, you have likely been installing the Python 2 versions of the packages you want with <code>apt</code> and/or <code>pip</code>. <code>sudo apt-get install python-django</code>, for example, will install the Python 2 version of Django, while <code>sudo apt-get install python3-django</code> installs the Py3 version. </p> <p>You will eventually run into a situation where you need to use <code>pip</code>, as a package you want won't be in the Debian/Ubuntu repositories. In that case, make sure you're using the right <code>pip</code>. Try running</p> <pre><code>pip -V </code></pre> <p>and</p> <pre><code>pip3 -V </code></pre> <p>to see which Python versions are attached when you call <code>pip</code>, then use the appropriate one for the version of Python you wish to target.</p> <p>Finally, <em>under no circumstances whatsoever</em> should you add the Python 2 paths to Python 3's <code>sys.path</code>.</p> <hr> <h2>EDIT</h2> <p>Here is my <code>sys.path</code> on Ubuntu 16.04 using the system's Python 3.5.2:</p> <pre><code>$ python3 Python 3.5.2 (default, Jul 5 2016, 12:43:10) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sys &gt;&gt;&gt; from pprint import pprint as pp &gt;&gt;&gt; pp(sys.path) ['', '/usr/local/lib/python3.5/dist-packages/pandas-0.18.1-py3.5-linux-x86_64.egg', '/usr/local/lib/python3.5/dist-packages/github3.py-1.0.0a4-py3.5.egg', '/usr/local/lib/python3.5/dist-packages/uritemplate.py-0.3.0-py3.5.egg', '/usr/lib/python3/dist-packages', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/dist-packages'] &gt;&gt;&gt; print(sys.executable) /usr/bin/python3 &gt;&gt;&gt; </code></pre> <p>You'll notice that the paths are <code>dist-packages</code> paths, while you have <code>site-packages</code>. From a user's perspective, there's very little difference between the two, so don't worry about it. I also changed some of my paths on purpose (it's a long story).</p>
2
2016-08-27T23:02:21Z
[ "python", "python-2.7", "python-3.x", "pip", "importerror" ]
Should PYTHONPATH include ./build/*?
39,185,417
<p>Running</p> <pre><code>$ python setup.py build_ext </code></pre> <p>with the usual Cython extension configuration creates a <code>build</code> directory and places the compiled modules deep within it.</p> <p>How is the Python interpreter supposed to find them now? Should <code>PYTHONPATH</code> include those sub-sub-directories? It seems kludgy to me. Perhaps this is meant to work differently?</p>
1
2016-08-27T20:21:44Z
39,185,484
<p>Presumably, when you write a package containing Cython code, <a href="http://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html" rel="nofollow">your <code>setup.py</code> will contain something similar to this</a>:</p> <pre><code>setup( ext_modules = cythonize("example.pyx") ) </code></pre> <p>(there are some variations, but that's the general idea). When you run </p> <pre><code>python setup.py install </code></pre> <p>or </p> <pre><code>python setup.py install --user </code></pre> <p>You will see it creates binary files (with extensions based on your OS - on mine it will be <code>example.so</code>) and copies them to the standard installation directory (also depending on your OS). </p> <p>These binary files are therefore already in the import path of your Python distribution, and it can <code>import</code> them like regular modules. </p> <p>Consequently, you do not need to add the build directory to the path. Just install (possibly with <code>--user</code>, or use virtualenv, if you're developing), and let the extensions be imported the regular way.</p>
1
2016-08-27T20:30:23Z
[ "python", "python-2.7", "cython", "distutils", "pythonpath" ]
Should PYTHONPATH include ./build/*?
39,185,417
<p>Running</p> <pre><code>$ python setup.py build_ext </code></pre> <p>with the usual Cython extension configuration creates a <code>build</code> directory and places the compiled modules deep within it.</p> <p>How is the Python interpreter supposed to find them now? Should <code>PYTHONPATH</code> include those sub-sub-directories? It seems kludgy to me. Perhaps this is meant to work differently?</p>
1
2016-08-27T20:21:44Z
39,185,529
<p>You will find the information here <a href="https://docs.python.org/3.5/install/" rel="nofollow">https://docs.python.org/3.5/install/</a></p> <p>Build is an intermediary result before python actually install the module. Put in pythonpath the paths to the library that is, for instance:</p> <pre><code>&lt;dir&gt;/local/lib/python </code></pre> <p>if you use the "home" installation technique and dir is the directory you have chosen, ex </p> <pre><code>/home/user2 </code></pre>
1
2016-08-27T20:35:55Z
[ "python", "python-2.7", "cython", "distutils", "pythonpath" ]
Is it possible to use jQuery and Django on the same page?
39,185,436
<p>I'm trying to just a jQuery function to show a table on a Django page. When I test the script on jsfiddle, it works great but it's not working on my Django site. Do I need to import something into Django to make it work?</p> <p>This is what I have thus far:</p> <p>html file:</p> <pre><code>&lt;table class="panel"&gt; &lt;tr&gt; &lt;td colspan=3 class="tblheader"&gt;&lt;h1&gt;Statistics&lt;/h1&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;button class="spoiler"&gt;Click for Spoilers&lt;/button&gt; </code></pre> <p>javascript file:</p> <pre><code>$(document).ready(function() { $('.spoiler').click(function() { $('.panel').slideToggle('slow'); }); }); </code></pre>
-1
2016-08-27T20:23:46Z
39,185,494
<p>You should add reference to jquery script from your Django html template, for example </p> <pre><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"&gt;&lt;/script&gt; </code></pre> <p>More information on <a href="http://jquery.com/download/" rel="nofollow">jquery site</a> </p>
-1
2016-08-27T20:31:58Z
[ "javascript", "jquery", "python", "django" ]
ImportError: No module named stdio, any way to start fresh with python?
39,185,453
<p>I'm getting the error </p> <pre><code>Traceback (most recent call last): File "ghs.py", line 1, in &lt;module&gt; import stdio ImportError: No module named stdio </code></pre> <p>When I try to run my script. I can run my script on other machines just fine. I have installed python using homebrew. And I've tried everything I can think of to get it to recognize my modules! I've uninstalled and reinstalled using brew. I've tried changing the path (though I don't fully understand this). I get no issues using brew doctor. </p> <p>I've also tried using a python virtual environment but to no avail.</p> <p>Any ideas on how to fix this issue or else 'start fresh' from a fresh version of python?</p>
0
2016-08-27T20:26:23Z
39,185,593
<p>When you import a module, Python looks for it at the directory your code is, and the directory in which the built-in libraries are (C:\Users\pc\AppData\Local\Programs\Python\Python35-32\Lib in my case, I'm using Windows 10 and Python 3.5). If it can't find it, it raises ImportError.</p> <p>I couldn't find a module named stdio in my computer. I also know some C++ and as far as I know, stdio is the library for inputs and outputs(prints). In python, there is no need to import such a library.</p> <p>You can use try,except statement to test if your code works without importing the module like this.</p> <pre><code>try: import stdio except: #rest of your code goes here </code></pre> <p>You will need to indent your whole code however this can be done easily with a text editor in which you can edit more than one line at a time.</p>
-3
2016-08-27T20:44:59Z
[ "python" ]
comparison of negative numbers turn out wrong
39,185,489
<p>I am doing a test of position bounding boxes, but when comparing negative (south or west) positions with other negative positions it turns the result upside down.</p> <pre><code>if minlat &gt; maxlat: minlat, maxlat = swap(minlat, maxlat) if minlon &gt; maxlon: minlon, maxlon = swap(minlon, maxlon) </code></pre> <p>This works fine when comparing latitudes on northern hemisphere or positions on southern with northern hemisphere, but when comparing positions on southern hemisphere it turns them around (i.e., -20.4 is less than -20.8). Is there a simple solution to this, or must I make a different test if both values are less than 0?</p>
-1
2016-08-27T20:31:10Z
39,185,522
<p>generally you'll want to compare the absolute values rather than the actual values in this scenario, try</p> <pre><code>if abs(minlat) &gt; abs(maxlat): </code></pre> <p>good luck!</p>
0
2016-08-27T20:35:22Z
[ "python", "python-2.7" ]
comparison of negative numbers turn out wrong
39,185,489
<p>I am doing a test of position bounding boxes, but when comparing negative (south or west) positions with other negative positions it turns the result upside down.</p> <pre><code>if minlat &gt; maxlat: minlat, maxlat = swap(minlat, maxlat) if minlon &gt; maxlon: minlon, maxlon = swap(minlon, maxlon) </code></pre> <p>This works fine when comparing latitudes on northern hemisphere or positions on southern with northern hemisphere, but when comparing positions on southern hemisphere it turns them around (i.e., -20.4 is less than -20.8). Is there a simple solution to this, or must I make a different test if both values are less than 0?</p>
-1
2016-08-27T20:31:10Z
39,186,376
<p><code>if float(minlat) &gt; float(maxlat):</code></p> <p>Making sure the compared numbers are actually numbers and not string objects. Comparing string objects using less than or greater than can have strange results.</p>
0
2016-08-27T22:29:54Z
[ "python", "python-2.7" ]
Convert import string to float with numpy's loadtext
39,185,612
<p>I'm attempting to import text from a flat file and to convert it to float values within a single line. I've seen <a href="http://stackoverflow.com/questions/8420143/valueerror-could-not-convert-string-to-float-id">this post</a> which has the same error, but I haven't found which characters are invalid in my input file. Or do I have a syntax error?</p> <p>Import as a string an print the result:</p> <pre><code>data = np.loadtxt(file, delimiter='\t', dtype=str) print(data[0:2]) ... [["b'Time'" "b'Percent'"] ["b'99'" "b'0.067'"]] </code></pre> <p>Attempt to import as float:</p> <pre><code># Import data as floats and skip the first row: data_float data_float = np.loadtxt(data, delimiter='\t', dtype=float, skiprows=1) </code></pre> <p>It throws the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; data_float = np.loadtxt(data, delimiter='\t', dtype=float, skiprows=1) File "&lt;stdin&gt;", line 848, in loadtxt items = [conv(val) for (conv, val) in zip(converters, vals)] File "&lt;stdin&gt;", line 848, in &lt;listcomp&gt; items = [conv(val) for (conv, val) in zip(converters, vals)] ValueError: could not convert string to float: b'["b\'99\'" "b\'0.067\'"]' </code></pre> <p>By the way, I've also seen <a href="http://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal">this post</a> which explains the <code>b</code> character, but I don't think that's the issue.</p> <p>An additional troubleshooting step as suggested by the first answer:</p> <pre><code>data = np.loadtxt(file, delimiter="\tb'", dtype=str) </code></pre> <p>Returns:</p> <pre><code>array(["b'Time\\tPercent'", "b'99\\t0.067'", "b'99\\t0.133'", "b'99\\t0.067'", "b'99\\t0'", "b'99\\t0'", "b'0\\t0.5'", "b'0\\t0.467'", "b'0\\t0.857'", "b'0\\t0.5'", "b'0\\t0.357'", "b'0\\t0.533'", "b'5\\t0.467'", "b'5\\t0.467'", "b'5\\t0.125'", "b'5\\t0.4'", "b'5\\t0.214'", "b'5\\t0.4'", "b'10\\t0.067'", "b'10\\t0.067'", "b'10\\t0.333'", "b'10\\t0.333'", "b'10\\t0.133'", "b'10\\t0.133'", "b'15\\t0.267'", "b'15\\t0.286'", "b'15\\t0.333'", "b'15\\t0.214'", "b'15\\t0'", "b'15\\t0'", "b'20\\t0.267'", "b'20\\t0.2'", "b'20\\t0.267'", "b'20\\t0.437'", "b'20\\t0.077'", "b'20\\t0.067'", "b'25\\t0.133'", "b'25\\t0.267'", "b'25\\t0.412'", "b'25\\t0'", "b'25\\t0.067'", "b'25\\t0.133'", "b'30\\t0'", "b'30\\t0.071'", "b'30\\t0'", "b'30\\t0.067'", "b'30\\t0.067'", "b'30\\t0.133'"], dtype='&lt;U16') </code></pre>
0
2016-08-27T20:47:22Z
39,185,675
<p>Could you try:</p> <pre><code>data = np.loadtxt(file, delimiter="\tb'", dtype=str) </code></pre> <p>To signify that the actual delimiter seems to include the characters "b'"?</p>
1
2016-08-27T20:56:16Z
[ "python", "python-3.x", "ipython" ]
Convert import string to float with numpy's loadtext
39,185,612
<p>I'm attempting to import text from a flat file and to convert it to float values within a single line. I've seen <a href="http://stackoverflow.com/questions/8420143/valueerror-could-not-convert-string-to-float-id">this post</a> which has the same error, but I haven't found which characters are invalid in my input file. Or do I have a syntax error?</p> <p>Import as a string an print the result:</p> <pre><code>data = np.loadtxt(file, delimiter='\t', dtype=str) print(data[0:2]) ... [["b'Time'" "b'Percent'"] ["b'99'" "b'0.067'"]] </code></pre> <p>Attempt to import as float:</p> <pre><code># Import data as floats and skip the first row: data_float data_float = np.loadtxt(data, delimiter='\t', dtype=float, skiprows=1) </code></pre> <p>It throws the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; data_float = np.loadtxt(data, delimiter='\t', dtype=float, skiprows=1) File "&lt;stdin&gt;", line 848, in loadtxt items = [conv(val) for (conv, val) in zip(converters, vals)] File "&lt;stdin&gt;", line 848, in &lt;listcomp&gt; items = [conv(val) for (conv, val) in zip(converters, vals)] ValueError: could not convert string to float: b'["b\'99\'" "b\'0.067\'"]' </code></pre> <p>By the way, I've also seen <a href="http://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal">this post</a> which explains the <code>b</code> character, but I don't think that's the issue.</p> <p>An additional troubleshooting step as suggested by the first answer:</p> <pre><code>data = np.loadtxt(file, delimiter="\tb'", dtype=str) </code></pre> <p>Returns:</p> <pre><code>array(["b'Time\\tPercent'", "b'99\\t0.067'", "b'99\\t0.133'", "b'99\\t0.067'", "b'99\\t0'", "b'99\\t0'", "b'0\\t0.5'", "b'0\\t0.467'", "b'0\\t0.857'", "b'0\\t0.5'", "b'0\\t0.357'", "b'0\\t0.533'", "b'5\\t0.467'", "b'5\\t0.467'", "b'5\\t0.125'", "b'5\\t0.4'", "b'5\\t0.214'", "b'5\\t0.4'", "b'10\\t0.067'", "b'10\\t0.067'", "b'10\\t0.333'", "b'10\\t0.333'", "b'10\\t0.133'", "b'10\\t0.133'", "b'15\\t0.267'", "b'15\\t0.286'", "b'15\\t0.333'", "b'15\\t0.214'", "b'15\\t0'", "b'15\\t0'", "b'20\\t0.267'", "b'20\\t0.2'", "b'20\\t0.267'", "b'20\\t0.437'", "b'20\\t0.077'", "b'20\\t0.067'", "b'25\\t0.133'", "b'25\\t0.267'", "b'25\\t0.412'", "b'25\\t0'", "b'25\\t0.067'", "b'25\\t0.133'", "b'30\\t0'", "b'30\\t0.071'", "b'30\\t0'", "b'30\\t0.067'", "b'30\\t0.067'", "b'30\\t0.133'"], dtype='&lt;U16') </code></pre>
0
2016-08-27T20:47:22Z
39,185,776
<p>Thanks to everyone who took a look at my question. I restarted IPython and was now able to execute the same code without any problems. Here's the code that worked which is identical to above. </p> <pre><code>data_float = np.loadtxt(file, delimiter='\t', dtype=float, skiprows=1) </code></pre> <p>Result:</p> <pre><code>In [1]: data_float Out[1]: array([[ 9.90000000e+01, 6.70000000e-02], [ 9.90000000e+01, 1.33000000e-01], [ 9.90000000e+01, 6.70000000e-02], [ 9.90000000e+01, 0.00000000e+00], [ 9.90000000e+01, 0.00000000e+00], [ 0.00000000e+00, 5.00000000e-01], [ 0.00000000e+00, 4.67000000e-01], [ 0.00000000e+00, 8.57000000e-01], [ 0.00000000e+00, 5.00000000e-01], [ 0.00000000e+00, 3.57000000e-01], [ 0.00000000e+00, 5.33000000e-01], [ 5.00000000e+00, 4.67000000e-01], [ 5.00000000e+00, 4.67000000e-01], [ 5.00000000e+00, 1.25000000e-01], [ 5.00000000e+00, 4.00000000e-01], [ 5.00000000e+00, 2.14000000e-01], [ 5.00000000e+00, 4.00000000e-01], [ 1.00000000e+01, 6.70000000e-02], [ 1.00000000e+01, 6.70000000e-02], [ 1.00000000e+01, 3.33000000e-01], [ 1.00000000e+01, 3.33000000e-01], [ 1.00000000e+01, 1.33000000e-01], [ 1.00000000e+01, 1.33000000e-01], [ 1.50000000e+01, 2.67000000e-01], [ 1.50000000e+01, 2.86000000e-01], [ 1.50000000e+01, 3.33000000e-01], [ 1.50000000e+01, 2.14000000e-01], [ 1.50000000e+01, 0.00000000e+00], [ 1.50000000e+01, 0.00000000e+00], [ 2.00000000e+01, 2.67000000e-01], [ 2.00000000e+01, 2.00000000e-01], [ 2.00000000e+01, 2.67000000e-01], [ 2.00000000e+01, 4.37000000e-01], [ 2.00000000e+01, 7.70000000e-02], [ 2.00000000e+01, 6.70000000e-02], [ 2.50000000e+01, 1.33000000e-01], [ 2.50000000e+01, 2.67000000e-01], [ 2.50000000e+01, 4.12000000e-01], [ 2.50000000e+01, 0.00000000e+00], [ 2.50000000e+01, 6.70000000e-02], [ 2.50000000e+01, 1.33000000e-01], [ 3.00000000e+01, 0.00000000e+00], [ 3.00000000e+01, 7.10000000e-02], [ 3.00000000e+01, 0.00000000e+00], [ 3.00000000e+01, 6.70000000e-02], [ 3.00000000e+01, 6.70000000e-02], [ 3.00000000e+01, 1.33000000e-01]]) </code></pre>
1
2016-08-27T21:10:03Z
[ "python", "python-3.x", "ipython" ]
Convert import string to float with numpy's loadtext
39,185,612
<p>I'm attempting to import text from a flat file and to convert it to float values within a single line. I've seen <a href="http://stackoverflow.com/questions/8420143/valueerror-could-not-convert-string-to-float-id">this post</a> which has the same error, but I haven't found which characters are invalid in my input file. Or do I have a syntax error?</p> <p>Import as a string an print the result:</p> <pre><code>data = np.loadtxt(file, delimiter='\t', dtype=str) print(data[0:2]) ... [["b'Time'" "b'Percent'"] ["b'99'" "b'0.067'"]] </code></pre> <p>Attempt to import as float:</p> <pre><code># Import data as floats and skip the first row: data_float data_float = np.loadtxt(data, delimiter='\t', dtype=float, skiprows=1) </code></pre> <p>It throws the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; data_float = np.loadtxt(data, delimiter='\t', dtype=float, skiprows=1) File "&lt;stdin&gt;", line 848, in loadtxt items = [conv(val) for (conv, val) in zip(converters, vals)] File "&lt;stdin&gt;", line 848, in &lt;listcomp&gt; items = [conv(val) for (conv, val) in zip(converters, vals)] ValueError: could not convert string to float: b'["b\'99\'" "b\'0.067\'"]' </code></pre> <p>By the way, I've also seen <a href="http://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal">this post</a> which explains the <code>b</code> character, but I don't think that's the issue.</p> <p>An additional troubleshooting step as suggested by the first answer:</p> <pre><code>data = np.loadtxt(file, delimiter="\tb'", dtype=str) </code></pre> <p>Returns:</p> <pre><code>array(["b'Time\\tPercent'", "b'99\\t0.067'", "b'99\\t0.133'", "b'99\\t0.067'", "b'99\\t0'", "b'99\\t0'", "b'0\\t0.5'", "b'0\\t0.467'", "b'0\\t0.857'", "b'0\\t0.5'", "b'0\\t0.357'", "b'0\\t0.533'", "b'5\\t0.467'", "b'5\\t0.467'", "b'5\\t0.125'", "b'5\\t0.4'", "b'5\\t0.214'", "b'5\\t0.4'", "b'10\\t0.067'", "b'10\\t0.067'", "b'10\\t0.333'", "b'10\\t0.333'", "b'10\\t0.133'", "b'10\\t0.133'", "b'15\\t0.267'", "b'15\\t0.286'", "b'15\\t0.333'", "b'15\\t0.214'", "b'15\\t0'", "b'15\\t0'", "b'20\\t0.267'", "b'20\\t0.2'", "b'20\\t0.267'", "b'20\\t0.437'", "b'20\\t0.077'", "b'20\\t0.067'", "b'25\\t0.133'", "b'25\\t0.267'", "b'25\\t0.412'", "b'25\\t0'", "b'25\\t0.067'", "b'25\\t0.133'", "b'30\\t0'", "b'30\\t0.071'", "b'30\\t0'", "b'30\\t0.067'", "b'30\\t0.067'", "b'30\\t0.133'"], dtype='&lt;U16') </code></pre>
0
2016-08-27T20:47:22Z
39,185,908
<p>The problem is that your numbers are quoted. That is, the field is <code>'99'</code>, rather than <code>99</code>. There are two ways you can do this. You can provide converter functions that strip the quotes and return a float. Or you can use the <code>csv</code> module to load your data in and then pass that data to <code>numpy</code>.</p> <p>Using converter functions</p> <pre><code>import numpy as np from io import StringIO data = """'x'\t'y' '1'\t'2.5'""" arr = np.loadtxt(StringIO(data), dtype=float, delimiter="\t", skiprows=1, converters=dict.fromkeys([0, 1], (lambda s: float(s.strip(b"'")))) ) </code></pre> <p>Using <code>csv</code></p> <pre><code>import csv import numpy as np from io import StringIO data = """'x'\t'y' '1'\t'2.5'""" reader = csv.reader(StringIO(data), quotechar="'", delimiter="\t") next(reader) # skip headers arr = np.array(list(reader), dtype=float) </code></pre> <p>In both examples I've uses <code>StringIO</code> so you can easily see the contents of the "file". You can of course pass the filename or file object to these functions.</p>
1
2016-08-27T21:28:51Z
[ "python", "python-3.x", "ipython" ]
Python if and elif not working, giving error
39,185,705
<p>I'm new in Python and doing an online tutorial. I have an assignment that I can not accomplish. My problem is that when I run this code, the <code>minimum</code> variable stays the same to <code>None</code> and does not record the new value input.</p> <pre><code>maximum = None minimum = None while True: try: num2 = raw_input('Type here ') if num2 == 'done':break else: num = int(num2) if num &lt;= minimum: minimum = num print minimum elif num &gt;= maximum: maximum = num print maximum except: print 'Invalid Entry' print 'Maximum is %d' % maximum print 'Minimum is %d' % minimum </code></pre>
0
2016-08-27T21:00:22Z
39,185,762
<p>Your problem is that your are checking if <code>(some number) &lt;= None</code> You cannot compare numbers with <code>None</code>. Instead, <code>minimum=float("inf")</code> and <code>maximum=float("-inf")</code> would set minimum to infinity, and maximum to negative infinity. That way, the first number entered would be less than infinity, setting it to <code>minimum</code>, and greater than negative infinity (setting it to <code>maximum</code>). Note that <code>elif maximum &gt;= num</code> would need to be changed to <code>if maximum &gt;= num</code> (to handle the first entered number).</p>
0
2016-08-27T21:07:15Z
[ "python", "python-2.7", "if-statement" ]
Python if and elif not working, giving error
39,185,705
<p>I'm new in Python and doing an online tutorial. I have an assignment that I can not accomplish. My problem is that when I run this code, the <code>minimum</code> variable stays the same to <code>None</code> and does not record the new value input.</p> <pre><code>maximum = None minimum = None while True: try: num2 = raw_input('Type here ') if num2 == 'done':break else: num = int(num2) if num &lt;= minimum: minimum = num print minimum elif num &gt;= maximum: maximum = num print maximum except: print 'Invalid Entry' print 'Maximum is %d' % maximum print 'Minimum is %d' % minimum </code></pre>
0
2016-08-27T21:00:22Z
39,185,803
<pre><code>import sys maximum = None minimum = sys.maxsize while True: try: num2 = raw_input('Type here ') if num2 == 'done':break else: num = int(num2) minimum = min(minimum, num) maximum = max(maximum, num) except: print 'Invalid Entry' if maximum is None: minimum = None print 'Maximum is %d' % maximum print 'Minimum is %d' % minimum </code></pre>
0
2016-08-27T21:13:57Z
[ "python", "python-2.7", "if-statement" ]
Python if and elif not working, giving error
39,185,705
<p>I'm new in Python and doing an online tutorial. I have an assignment that I can not accomplish. My problem is that when I run this code, the <code>minimum</code> variable stays the same to <code>None</code> and does not record the new value input.</p> <pre><code>maximum = None minimum = None while True: try: num2 = raw_input('Type here ') if num2 == 'done':break else: num = int(num2) if num &lt;= minimum: minimum = num print minimum elif num &gt;= maximum: maximum = num print maximum except: print 'Invalid Entry' print 'Maximum is %d' % maximum print 'Minimum is %d' % minimum </code></pre>
0
2016-08-27T21:00:22Z
39,185,804
<p>You are comparing <code>None</code> and <code>int</code>, Python does not know how to do that. Instead, you should do:</p> <pre><code>maximum = float('-inf') minimum = float('inf') </code></pre> <p>Any <code>int</code> would be greater than <code>-infinity</code> and lower than <code>infinity</code>, so things will work fine. Same thing can not be said about zeroes, so don't use those.</p> <p>Also, look up <code>min</code> and <code>max</code> <a href="https://docs.python.org/2/library/functions.html" rel="nofollow">builtins</a>.</p>
0
2016-08-27T21:14:04Z
[ "python", "python-2.7", "if-statement" ]
What the numpy array stores when i convert a grayscale image into a numpy array?
39,185,781
<p>I converted a 32 x 32 grayscale image into a numpy array using this procedure </p> <pre><code>image = Image.open('bn2.bmp') nparray=np.array(image) </code></pre> <p>when I print the numpy array, it prints 6 different matrix. When I printed the size of the numpy array, it showed me 3072. I suppose that the calculation is something like 3 x 32 x 32 . But I would like to know why, what is the numpy array storing? </p>
1
2016-08-27T21:10:49Z
39,185,964
<p>Looking at the documentation on the page <a href="http://scikit-image.org/docs/dev/user_guide/numpy_images.html" rel="nofollow">A crash course on NumPy for images</a></p> <p>If you use <code>shape</code>, </p> <pre><code>nparray.shape </code></pre> <p>this will give the dimensions of the image as something like</p> <pre><code>(32, 32, 3) </code></pre> <p>which gives the size you found (32 x 32 x 3 = 3072)</p> <p>What this shows is that your image is a 32-by-32 pixel image with three channels (red, green, and blue). If it were grayscale, the size would be 32 x 32 = 1024, corresponding to a shape of:</p> <p><code>(32, 32)</code></p> <p>Incidentally, to convert your image to grayscale, you would need to use something like <a href="http://scikit-image.org/docs/dev/api/skimage.color.html#rgb2gray" rel="nofollow"><code>rgb2gray</code></a> (link to documentation).</p>
0
2016-08-27T21:37:12Z
[ "python", "numpy", "image-processing" ]
sl4a startActivity find out packagename and classname
39,185,785
<p>So I'm trying to start WhatsApp with a predefined message in sl4a using Python. This is my code:</p> <pre><code>import android droid = android.Android() droid.startActivity("android.intent.action.SEND", None, "text/plain", {'com.whatsapp.locale.extras.TEXT':"sl4a test"}, False, "com.whatsapp", "classname" ) </code></pre> <p>I don't know if the packagename is right, and I don't know what the classname should be. The syntax is:</p> <pre><code>startActivity( action (String), uri (String) (optional), type (String) MIME type/subtype of the URI (optional), extras (JSONObject) a Map of extras to add to the Intent (optional), wait (Boolean) block until the user exits the started activity (optional), packagename (String) name of package. If used, requires classname to be useful (optional), classname (String) name of class. If used, requires packagename to be useful (optional), ) </code></pre>
0
2016-08-27T21:11:36Z
39,186,187
<p>Nevermind I just figured out that I could set WhatsApp as the standard app in the dialog so I don't have to specify the packagename anyway.</p>
0
2016-08-27T22:06:11Z
[ "android", "python", "whatsapp", "sl4a" ]
How do most people do console.log debugging in Python?
39,185,797
<p>In Node.js when I want to quickly check the value of something rather than busting out the debugger and stepping through, I quickly add a console.log(foo) and get a beautiful:</p> <pre><code>{ lemmons: "pie", number: 9, fetch: function(){..} elements: { fire: 99.9 } } </code></pre> <p>Very clear! In Python I get this:</p> <pre><code>class LinkedList: head = None tail = None lemmons = 99 </code></pre> <p><code>&lt;__main__.LinkedList instance at 0x105989f80&gt;</code> or with <code>vars()</code>,</p> <p><code>{}</code></p> <p>or with <code>dir()</code>, </p> <p><code>['_LinkedList__Node', '__doc__', '__module__', 'append', 'get_tail', 'head', 'lemmons', 'remove', 'tail']</code></p> <p>Yuck! Look at all that nonsense - I thought python was supposed to be fast, beautiful and clean? Is this really how people do it? Do they implement customer <strong>str</strong> and custom <strong>repr</strong> for everything? Because that seems kind of crazy too..</p>
1
2016-08-27T21:13:05Z
39,185,974
<p>You can print your objects &amp; Python classes in a lot of different ways, here's a simple one:</p> <pre><code>class LinkedList: head = None tail = None lemmons = 99 def __str__(self): return str(vars(LinkedList)) print LinkedList() </code></pre> <p>I'd recommend you start for getting familiar with <a href="http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python"><strong>str</strong> and <strong>repr</strong></a> operators. In any case, this is a little example and with python there are tons of ways to pretty print object &amp; classes</p>
0
2016-08-27T21:38:54Z
[ "python", "class", "debugging", "object", "tostring" ]
How do most people do console.log debugging in Python?
39,185,797
<p>In Node.js when I want to quickly check the value of something rather than busting out the debugger and stepping through, I quickly add a console.log(foo) and get a beautiful:</p> <pre><code>{ lemmons: "pie", number: 9, fetch: function(){..} elements: { fire: 99.9 } } </code></pre> <p>Very clear! In Python I get this:</p> <pre><code>class LinkedList: head = None tail = None lemmons = 99 </code></pre> <p><code>&lt;__main__.LinkedList instance at 0x105989f80&gt;</code> or with <code>vars()</code>,</p> <p><code>{}</code></p> <p>or with <code>dir()</code>, </p> <p><code>['_LinkedList__Node', '__doc__', '__module__', 'append', 'get_tail', 'head', 'lemmons', 'remove', 'tail']</code></p> <p>Yuck! Look at all that nonsense - I thought python was supposed to be fast, beautiful and clean? Is this really how people do it? Do they implement customer <strong>str</strong> and custom <strong>repr</strong> for everything? Because that seems kind of crazy too..</p>
1
2016-08-27T21:13:05Z
39,186,873
<p>The expectation is that you <a href="https://docs.python.org/2/howto/logging.html#using-arbitrary-objects-as-messages" rel="nofollow">implement your own <code>__str__</code> method</a> so that you can pick what is important to log in your diags.</p> <p>However, there is the option to log the whole object dictionary in a "pretty" format using a couple of lines of code. For example:</p> <pre><code>from pprint import pformat class A(object): def __init__(self): self.foo = 1 self.bar = {"hello": "world"} self._private = 0 a = A() print pformat(vars(a)) # You can also pass pformat to your logger if that's what you have. </code></pre> <p>This will return something like this (depending on how much data you have and thw <code>width</code> constraint):</p> <pre><code>{'_private': 0, 'bar': {'hello': 'world'}, 'foo': 1} </code></pre>
0
2016-08-28T00:08:18Z
[ "python", "class", "debugging", "object", "tostring" ]
Nervana Neon AttributeError: 'NoneType' object has no attribute 'sizeI'
39,185,835
<p>I'm a trying to do fprop with Nervana Neon, however, when I go to run model fprop I get the following error:</p> <blockquote> <p>AttributeError: 'NoneType' object has no attribute 'sizeI'</p> </blockquote> <p>I am following their example for fprop very close. I've trained the model using their <code>ImageLoader</code> and now I want to utilize the results in a system. I've tried using <code>model.get_outputs(ArrayIterator(myData))</code> but still issues. Any thoughts?</p> <pre><code>xdev = np.zeros((3 * 224 * 224, batch_size), dtype=np.float32) xbuf = np.zeros((3 * 224 * 224, batch_size), dtype=np.float32) img = to_neon(new_img) # function to flatten image to (3 * 224 * 224, ) xbuf[:,0] = img[:, 0] model = model.load_params("/path/to/params.p") out = model.fprop(xdev) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-35-fc650f5dcbc4&gt; in &lt;module&gt;() ----&gt; 1 out = model.fprop(xdev) /root/neon/neon/models/model.pyc in fprop(self, x, inference) 213 Tensor: the output of the final layer in the model 214 """ --&gt; 215 return self.layers.fprop(x, inference) 216 217 def bprop(self, delta): /root/neon/neon/layers/container.pyc in fprop(self, inputs, inference, beta) 248 x = l.fprop(x, inference, beta=beta) 249 else: --&gt; 250 x = l.fprop(x, inference) 251 252 if inference: /root/neon/neon/layers/layer.pyc in fprop(self, inputs, inference, beta) 787 self.inputs = inputs 788 self.be.fprop_conv(self.nglayer, inputs, self.W, self.outputs, beta=beta, --&gt; 789 bsum=self.batch_sum) 790 return self.outputs 791 /root/neon/neon/backends/nervanagpu.pyc in fprop_conv(self, layer, I, F, O, X, bias, bsum, alpha, beta, relu, brelu, slope, repeat) 1936 repeat: used in benchmarking 1937 """ -&gt; 1938 assert layer.sizeI == I.size 1939 assert layer.sizeF == F.size 1940 assert layer.sizeO == O.size AttributeError: 'NoneType' object has no attribute 'sizeI' </code></pre>
0
2016-08-27T21:17:41Z
39,186,472
<p>Working backwards on your stacktrace...</p> <p>The problem comes from an attempt to dereference the <code>sizeI</code> attribute of a <code>layer</code> object when <code>layer</code> is <code>None</code>:</p> <p><code>-&gt; 1938 assert layer.sizeI == I.size</code></p> <p>I'd call that a bug in the neon library (<code>backends/nervanagpu.py</code>)- it should have above that 1938 line something like:</p> <pre><code> assert isinstance(layer, TheExpectedLayerClass) </code></pre> <p>A similar check could have been added even earlier, in <code>layers/layer.py</code>, before line 788:</p> <pre><code> assert isinstance(self.nglayer, TheExpectedLayerClass) </code></pre> <p>But often hitting such bugs in 3rd party libs are simply indications that the library is not used in the way it was intended to. The bugs simply <em>obscure</em> the real cause by not making the proper checks earlier, where maybe it's clear what's missing. </p> <p>So check the docs/tutorials, maybe you're missing some init/setup step, some additional argument somewhere, etc. Or, if you're more familiar with neon, keep going backwards on the stacktrace until you find what's missing.</p>
0
2016-08-27T22:46:26Z
[ "python", "deep-learning" ]
Intersection of 2 lists which contain non-hashables
39,185,978
<p>What is the most efficient way to find the intersection of 2 lists when both lists contain non-hashables?</p> <p>Basically, let's say I have the following lists (which I completely made up):</p> <pre><code>A = [&lt;foo.bar object at 0x7f267c664080&gt;, &lt;foo.bar object at 0x7f267c664099&gt;] B = [&lt;foo.bar object at 0x7f267c664080&gt;, &lt;foo.bar object at 0x123456789101&gt;] </code></pre> <p>We can see that the first element of <code>A</code> is the same as the first element of <code>B</code>. </p> <p>I can do the simple thing by creating a for loop:</p> <pre><code>intersection = [] for obj_a in A: for obj_b in B: if ( (obj_a == obj_b) and (obj_a not in intersection) ): intersection.extend(obj_a) </code></pre> <p>but I'm just wondering if there is a more efficient, cooler, or simpler way. For example, there is:</p> <pre><code>C = [1, 2, 3] D = [3, 4, 5] set(C).intersection(set(D)) </code></pre> <p>...but obviously I can't use <code>set</code> or <code>frozenset</code> for non-hashables because I get</p> <pre><code>TypeError: unhashable type: foo.bar </code></pre> <p>Is there anything like this for non-hashables?</p>
0
2016-08-27T21:39:28Z
39,185,991
<p>Hashing is what makes the <code>set</code> efficient. If you can't hash, then you can't take advantage of that efficiency - you have to compare every object with every other object and you get an O(n²) algorithm instead of an amortized O(n) one.</p> <p>However, if you care only about object <em>identity</em> and not equality, then you can make dicts mapping the object ids to the objects, and take the intersection of the ids:</p> <pre><code>&gt;&gt;&gt; class foo(object): pass ... &gt;&gt;&gt; f = foo() &gt;&gt;&gt; A = [foo(), foo(), f] &gt;&gt;&gt; B = [foo(), f, foo(), foo()] &gt;&gt;&gt; [a for a in A if id(a) in (set(map(id, A)) &amp; set(map(id, B))] [&lt;__main__.foo object at 0x100a7e9d0&gt;] </code></pre> <p>If you want a more code-efficient solution or you do care about object equality, then <a href="http://stackoverflow.com/a/39186008/15055">@Neil's answer</a> should suffice.</p>
1
2016-08-27T21:41:30Z
[ "python" ]
Intersection of 2 lists which contain non-hashables
39,185,978
<p>What is the most efficient way to find the intersection of 2 lists when both lists contain non-hashables?</p> <p>Basically, let's say I have the following lists (which I completely made up):</p> <pre><code>A = [&lt;foo.bar object at 0x7f267c664080&gt;, &lt;foo.bar object at 0x7f267c664099&gt;] B = [&lt;foo.bar object at 0x7f267c664080&gt;, &lt;foo.bar object at 0x123456789101&gt;] </code></pre> <p>We can see that the first element of <code>A</code> is the same as the first element of <code>B</code>. </p> <p>I can do the simple thing by creating a for loop:</p> <pre><code>intersection = [] for obj_a in A: for obj_b in B: if ( (obj_a == obj_b) and (obj_a not in intersection) ): intersection.extend(obj_a) </code></pre> <p>but I'm just wondering if there is a more efficient, cooler, or simpler way. For example, there is:</p> <pre><code>C = [1, 2, 3] D = [3, 4, 5] set(C).intersection(set(D)) </code></pre> <p>...but obviously I can't use <code>set</code> or <code>frozenset</code> for non-hashables because I get</p> <pre><code>TypeError: unhashable type: foo.bar </code></pre> <p>Is there anything like this for non-hashables?</p>
0
2016-08-27T21:39:28Z
39,186,008
<p>A simple solution using list comprehension: <code>intersection = [element for element in A if element in B</code> checks if two elements of the same <em>value</em> are there. For example, for <code>[1, 2, 3]</code> and <code>[0, 1, 5]</code>, it will return <code>[1]</code>.</p>
0
2016-08-27T21:43:36Z
[ "python" ]
Converting 2D Numpy array to a list of 1D columns
39,185,985
<p>What would be the best way of converting a 2D numpy array into a list of 1D columns?</p> <p>For instance, for an array:</p> <pre><code>array([[ 0, 5, 10], [ 1, 6, 11], [ 2, 7, 12], [ 3, 8, 13], [ 4, 9, 14]]) </code></pre> <p>I would like to get:</p> <pre><code>[array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9]), array([10, 11, 12, 13, 14])] </code></pre> <p>This works:</p> <pre><code>[a[:, i] for i in range(a.shape[1])] </code></pre> <p>but I was wondering if there is a better solution using pure Numpy functions?</p>
0
2016-08-27T21:40:23Z
39,186,077
<p>Well, here's <em>another</em> way. (I assume x is your original 2d array.)</p> <pre><code>[row for row in x.T] </code></pre> <p>Still uses a Python list generator expression, however.</p>
0
2016-08-27T21:53:15Z
[ "python", "numpy" ]
Converting 2D Numpy array to a list of 1D columns
39,185,985
<p>What would be the best way of converting a 2D numpy array into a list of 1D columns?</p> <p>For instance, for an array:</p> <pre><code>array([[ 0, 5, 10], [ 1, 6, 11], [ 2, 7, 12], [ 3, 8, 13], [ 4, 9, 14]]) </code></pre> <p>I would like to get:</p> <pre><code>[array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9]), array([10, 11, 12, 13, 14])] </code></pre> <p>This works:</p> <pre><code>[a[:, i] for i in range(a.shape[1])] </code></pre> <p>but I was wondering if there is a better solution using pure Numpy functions?</p>
0
2016-08-27T21:40:23Z
39,186,088
<p>I can't think of any reason you would need </p> <pre><code>[array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9]), array([10, 11, 12, 13, 14])] </code></pre> <p>Instead of</p> <pre><code>array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) </code></pre> <p>Which you can get simply with <code>a.T</code></p> <p><sup>If you really need a list, then you can use <code>list(a.T)</code></sup></p>
3
2016-08-27T21:54:39Z
[ "python", "numpy" ]
Converting 2D Numpy array to a list of 1D columns
39,185,985
<p>What would be the best way of converting a 2D numpy array into a list of 1D columns?</p> <p>For instance, for an array:</p> <pre><code>array([[ 0, 5, 10], [ 1, 6, 11], [ 2, 7, 12], [ 3, 8, 13], [ 4, 9, 14]]) </code></pre> <p>I would like to get:</p> <pre><code>[array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9]), array([10, 11, 12, 13, 14])] </code></pre> <p>This works:</p> <pre><code>[a[:, i] for i in range(a.shape[1])] </code></pre> <p>but I was wondering if there is a better solution using pure Numpy functions?</p>
0
2016-08-27T21:40:23Z
39,186,135
<p>Here is one way:</p> <pre><code>In [20]: list(a.T) Out[20]: [array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9]), array([10, 11, 12, 13, 14])] </code></pre> <p>Here is another one:</p> <pre><code>In [40]: [*map(np.ravel, np.hsplit(a, 3))] Out[40]: [array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9]), array([10, 11, 12, 13, 14])] </code></pre>
1
2016-08-27T22:00:39Z
[ "python", "numpy" ]
CodingBat has22 why is this solution wrong?
39,185,999
<pre><code>def has22(nums): if nums[len(nums) - 1] == 2: if nums[len(nums) - 2] == 2: return True else: for n in range(len(nums) - 3): if nums[n] == 2 : if nums[n + 1] == 2: return True else: return False </code></pre> <p>I need to return True if the array contains a 2 next to a 2 somewhere. But it gives me an error that says:"list index out of range". What should i change?</p> <p>I'm pretty new to the stuff, so probably my code is one of the longest ways to solve it, but i appreciate any help. Thank you!</p>
-1
2016-08-27T21:42:34Z
39,186,589
<p>I think the error you report can only happen if <code>nums</code> is an empty list. In that situation, <code>nums[len(nums) - 1]</code> is not a valid index (as there are no valid indexes into an empty list).</p> <p>For this problem, there's really not much point to special casing the last two items in the list. You can make your code much simpler by handling all the cases with one loop:</p> <pre><code>def has22(nums): for n in range(len(nums) - 1): # the loop body will not run if len(nums) &lt; 2 if nums[n] == nums[n + 1] == 2: # you can chain comparison operators return True return False # this is at top level (after the loop), not an `else` clause of the if </code></pre> <p>As the comment says, the loop body where I use list indexes won't run if the length of the list is less than 2. That's because the <code>range</code> will be empty, and iterating on an empty sequence does nothing.</p> <p>A slightly fancier approach would be to use <code>zip</code> on two iterators of <code>num</code> that are offset by one place. This is more advanced Python stuff, so if you don't understand it yet, don't worry too much about it:</p> <pre><code>def has22_fancy(nums): iters = [iter(nums), iter(nums)] next(iters[1], None) return any(a == b == 2 for a, b in zip(*iters)) </code></pre> <p>This approach to iterating over pairs using <code>zip</code> is inspired by the <a href="https://docs.python.org/3/library/itertools.html#itertools-recipes" rel="nofollow"><code>itertools</code> documentation</a>, where it's given in the <code>pairwise</code> recipe:</p> <pre><code>def pairwise(iterable): "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return zip(a, b) </code></pre>
1
2016-08-27T23:05:55Z
[ "python" ]
Why is my code not working? (Beginner programmer, python 1st language)
39,186,000
<p>I need some major improvements in my programming/coding and it's already been a month of this computer language field.</p> <p>Right now I'm trying to create a class with 3 functions (lunch, breakfast, and dinner) and let's say I want to call the function lunch and add 'Strawberry' to the lunch list; it's supposed to add 1 to the list count (<code>list_count</code>) for amount of foods entered in the list count so far, and adds 'strawberry' to the dictionary. </p> <p>So what I'm trying to do is I created a blank dictionary list (<code>lunch_list</code>) and created a starting count of food items (<code>lunch_count</code>)</p> <p>So if I call lunch in the Food class, I'm trying to make the result like this:</p> <pre><code>list_count: 1 lunch_name: Strawberry lunch_list = {1:'Strawberry'} </code></pre> <p>I was ready to write this script but after writing this I confused myself a lot more. I feel lost. This is going to be embarassing for me but here is my code:</p> <pre><code>class Food(): lunch_count = 0 lunch_list = {} def __init__(self, food_name): self.food_name = food_name def lunch(self, lunch_count): lunch_count += 1 lunch_list[lunch_count] = self.food_name return lunch_list strawberry = Food('Strawberry') print strawberry.lunch('Strawberry') </code></pre>
1
2016-08-27T21:42:54Z
39,186,215
<p>It doesn't seem like your 'Strawberry' parameter matches the lunch_count parameter in your lunch function. In the lunch method, you then can increment it by one every time you call lunch, rather than adding it as a parameter.</p> <p>If you are new to Python, I would recommend <a href="https://learnpythonthehardway.org/book/" rel="nofollow">Learn Python the Hard Way</a>.</p> <pre><code>class Food(): lunch_count = 0 lunch_list = {} def __init__(self, food_name): self.food_name = food_name def lunch(self): Food.lunch_count += 1 Food.lunch_list[Food.lunch_count] = self.food_name return Food.lunch_list strawberry = Food('Strawberry') print strawberry.lunch() </code></pre>
0
2016-08-27T22:09:20Z
[ "python" ]
Why is my code not working? (Beginner programmer, python 1st language)
39,186,000
<p>I need some major improvements in my programming/coding and it's already been a month of this computer language field.</p> <p>Right now I'm trying to create a class with 3 functions (lunch, breakfast, and dinner) and let's say I want to call the function lunch and add 'Strawberry' to the lunch list; it's supposed to add 1 to the list count (<code>list_count</code>) for amount of foods entered in the list count so far, and adds 'strawberry' to the dictionary. </p> <p>So what I'm trying to do is I created a blank dictionary list (<code>lunch_list</code>) and created a starting count of food items (<code>lunch_count</code>)</p> <p>So if I call lunch in the Food class, I'm trying to make the result like this:</p> <pre><code>list_count: 1 lunch_name: Strawberry lunch_list = {1:'Strawberry'} </code></pre> <p>I was ready to write this script but after writing this I confused myself a lot more. I feel lost. This is going to be embarassing for me but here is my code:</p> <pre><code>class Food(): lunch_count = 0 lunch_list = {} def __init__(self, food_name): self.food_name = food_name def lunch(self, lunch_count): lunch_count += 1 lunch_list[lunch_count] = self.food_name return lunch_list strawberry = Food('Strawberry') print strawberry.lunch('Strawberry') </code></pre>
1
2016-08-27T21:42:54Z
39,186,237
<pre><code>class Food(): lunch_count = 0 lunch_list = {} def __init__(self, food_name): self.lc = None self.food_name = food_name def lunch(self): Food.lunch_count += 1 self.lc = Food.lunch_count Food.lunch_list[Food.lunch_count] = self.food_name return Food.lunch_list strawberry = Food('Strawberry') result = strawberry.lunch() print strawberry.lc print strawberry.food_name print result </code></pre>
0
2016-08-27T22:12:15Z
[ "python" ]
Why is my code not working? (Beginner programmer, python 1st language)
39,186,000
<p>I need some major improvements in my programming/coding and it's already been a month of this computer language field.</p> <p>Right now I'm trying to create a class with 3 functions (lunch, breakfast, and dinner) and let's say I want to call the function lunch and add 'Strawberry' to the lunch list; it's supposed to add 1 to the list count (<code>list_count</code>) for amount of foods entered in the list count so far, and adds 'strawberry' to the dictionary. </p> <p>So what I'm trying to do is I created a blank dictionary list (<code>lunch_list</code>) and created a starting count of food items (<code>lunch_count</code>)</p> <p>So if I call lunch in the Food class, I'm trying to make the result like this:</p> <pre><code>list_count: 1 lunch_name: Strawberry lunch_list = {1:'Strawberry'} </code></pre> <p>I was ready to write this script but after writing this I confused myself a lot more. I feel lost. This is going to be embarassing for me but here is my code:</p> <pre><code>class Food(): lunch_count = 0 lunch_list = {} def __init__(self, food_name): self.food_name = food_name def lunch(self, lunch_count): lunch_count += 1 lunch_list[lunch_count] = self.food_name return lunch_list strawberry = Food('Strawberry') print strawberry.lunch('Strawberry') </code></pre>
1
2016-08-27T21:42:54Z
39,186,640
<p>Easier to read and understand.</p> <pre><code>lunch_count=0 lunch_item="" lunch_menu={} while lunch_item != "quit": lunch_item=input("Enter Item: ") menu_item=str(lunch_item) lunch_count+=1 lunch_menu.update({lunch_count:menu_item}) print(lunch_menu) else: print("exiting") </code></pre> <p>Wrap this in a function and it adds an item and the count gets updated along with the newly entered string</p> <p>Using python 3.5.2</p> <p>If you like my answer please click the green arrow. Thanks.</p>
0
2016-08-27T23:17:08Z
[ "python" ]
Python urllib2 proxy setting issue
39,186,031
<p>I've looked through some of the other posts on this and I hope I'm not duplicating, but I'm stuck on a real headscratcher with setting a proxy server for urllib2. I'm running the below: </p> <pre><code> file, site = argv uri = 'https://'+site http_proxy_server = "http://newyork.wonderproxy.com" http_proxy_port = "11001" http_proxy_user = "user" http_proxy_passwd = "password" http_proxy_full_auth_string = "http://%s:%s@%s:%s" % (http_proxy_user, http_proxy_passwd, http_proxy_server, http_proxy_port) proxy_handler = urllib2.ProxyHandler({"http": http_proxy_full_auth_string}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) html = opener.open(uri).read() print html, 'it opened!' </code></pre> <p>I'm running this against an IP info site, but try as I might the response always comes out with my non-proxy IP address. When I manually set my proxy through system settings I do get a different response, so I've confirmed it's not an issue with the proxy criteria itself.</p> <p>Any help that could be offered would be much appreciated!</p>
0
2016-08-27T21:46:04Z
39,186,645
<p>Well this is a bit silly, but I tried a different example and my connection is working fine now.</p> <pre><code> import urllib2 proxlist= ['minneapolis.wonderproxy.com', 'newyork.wonderproxy.com'] ports = [0,1,2,3] for prox in proxlist: for port in ports: proxy = urllib2.ProxyHandler({'http': 'http://user:password@%s:1100%s'%(prox,port)}) auth = urllib2.HTTPBasicAuthHandler() opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) urllib2.install_opener(opener) try: conn = urllib2.urlopen('http://www.howtofindmyipaddress.com/') return_str = conn.read() str_find = '&lt;span style="font-size: 80px; color: #22BB22; font-family: Calibri,Arial;"&gt;' strt = return_str.find(str_find)+len(str_find) print prox, port, return_str[strt:return_str.find('&lt;/span',strt)-1] except urllib2.URLError: print prox, port, 'That\'s a no go' </code></pre> <p>Only difference I can see is that the second one used HTTPHandler instead of Proxy, as I have an apparently solution I'm not too worried, but woudl still be interested to know why I had this issue in the first place.</p>
0
2016-08-27T23:17:38Z
[ "python", "proxy", "urllib2" ]
Python urllib2 proxy setting issue
39,186,031
<p>I've looked through some of the other posts on this and I hope I'm not duplicating, but I'm stuck on a real headscratcher with setting a proxy server for urllib2. I'm running the below: </p> <pre><code> file, site = argv uri = 'https://'+site http_proxy_server = "http://newyork.wonderproxy.com" http_proxy_port = "11001" http_proxy_user = "user" http_proxy_passwd = "password" http_proxy_full_auth_string = "http://%s:%s@%s:%s" % (http_proxy_user, http_proxy_passwd, http_proxy_server, http_proxy_port) proxy_handler = urllib2.ProxyHandler({"http": http_proxy_full_auth_string}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) html = opener.open(uri).read() print html, 'it opened!' </code></pre> <p>I'm running this against an IP info site, but try as I might the response always comes out with my non-proxy IP address. When I manually set my proxy through system settings I do get a different response, so I've confirmed it's not an issue with the proxy criteria itself.</p> <p>Any help that could be offered would be much appreciated!</p>
0
2016-08-27T21:46:04Z
39,441,442
<p>Your question sets the proxy URL to</p> <p><code>http://user:password@http://newyork.wonderproxy.com:11001</code></p> <p>which isn't valid. If you changed <code>http_proxy_server</code> to <code>newyork.wonderproxy.com</code> then your first solution might work better.</p>
0
2016-09-11T22:56:41Z
[ "python", "proxy", "urllib2" ]
Styling ModelMultipleChoiceField Django
39,186,043
<p>I'm having trouble styling my django form with a ModelMultipleChoiceField.</p> <p>Heres my form:</p> <pre><code>class SkriptenSelect(forms.Form): skripten = StyledModelMultipleChoiceField( queryset=None, widget=forms.CheckboxSelectMultiple, ) def __init__(self, *args, **kwargs): choices = kwargs.pop('choices') super(SkriptenSelect, self).__init__(*args, **kwargs) self.fields['skripten'].queryset = choices class StyledModelMultipleChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return mark_safe('&lt;ul class="list-inline" style="display: inline;"&gt;' \ '&lt;li&gt;{name}&lt;/li&gt;' \ '&lt;li&gt;{semester}&lt;/li&gt;' \ '&lt;li&gt;professor&lt;/li&gt;' \ '&lt;/ul&gt;'.format(name=escape(obj.name), semester=escape(obj.prefix)) ) </code></pre> <p>And I used this for html:</p> <pre><code>&lt;form action="." method="post"&gt; &lt;ul class="list-group"&gt; {% for skript in result_form.skripten %} &lt;li class="list-group-item"&gt; {{ skript }} &lt;/li&gt; {% endfor %} &lt;/ul&gt; {% csrf_token %} &lt;input type="submit" value="Submit Selected" /&gt; </code></pre> <p></p> <p>This requires me to put my HTML in my forms file, which is not a very mvc way. Also it restricts me heavily in how i can style the list (i.e making table of the model instance fields)</p> <p>Is there anyway to make this smarter? I'd like to access {{ skript.name }}, {{ skript.checkbox }} or something in my {% for skript in result_form.skripten %} loop, but thats sadly not possible...</p>
0
2016-08-27T21:48:40Z
39,186,752
<p>You can use <code>render_to_string</code>. It loads a template and renders it with a context. Returns a string.</p> <pre><code>from django.template.loader import render_to_string rendered = render_to_string('my_template.html', {'foo': 'bar'}) </code></pre> <p>For various variants you can make various StyledModelMultipleChoiceField subclasses OR pass the desired template_name when initialising the class. Eg:</p> <pre><code>&gt;&gt;&gt; class FooField: ... def __init__(self, template_name='default.html'): ... self.template_name = template_name ... &gt;&gt;&gt; x = FooField('table.html') &gt;&gt;&gt; x.template_name 'table.html' </code></pre> <p>Use <code>self.template_name</code> where appropriate:</p> <pre><code>def label_from_instance(self, obj) return render_to_string(self.template_name, {'foo': obj.foo}) </code></pre> <p>If you want to display multiple instances, use a <a href="https://docs.djangoproject.com/en/1.10/topics/forms/formsets/" rel="nofollow">formset</a>.</p>
0
2016-08-27T23:39:03Z
[ "python", "html", "django" ]
pandas group by confusion -- unhashable type
39,186,067
<p>Using Pandas data frame group by feature and I want to group by column <code>c_b</code> and calculate unique count for column <code>c_a</code> and column <code>c_c</code>. My expected results are,</p> <p><strong>Expected results</strong>,</p> <pre><code>c_b,c_a_unique_count,c_c_unique_count python,2,2 c++,2,2 </code></pre> <p>Met with strange error about <code>unhashable type</code>, does anyone have any ideas? Thanks.</p> <p><strong>Input file</strong>,</p> <pre><code>c_a,c_b,c_c,c_d hello,python,numpy,0.0 hi,python,pandas,1.0 ho,c++,vector,0.0 ho,c++,std,1.0 go,c++,std,0.0 </code></pre> <p><strong>Source code</strong>,</p> <pre><code>sample = pd.read_csv('123.csv', header=None, skiprows=1, dtype={0:str, 1:str, 2:str, 3:float}) sample.columns = pd.Index(data=['c_a', 'c_b', 'c_c', 'c_d']) sample['c_d'] = sample['c_d'].astype('int64') sampleGroup = sample.groupby('c_b') results = sampleGroup.count()[:,[0,2]] results.to_csv(derivedFeatureFile, index= False) </code></pre> <p><strong>Error message</strong>,</p> <pre><code>Traceback (most recent call last): File "/Users/foo/personal/featureExtraction/kaggleExercise.py", line 134, in &lt;module&gt; unitTest() File "/Users/foo/personal/featureExtraction/kaggleExercise.py", line 129, in unitTest results = sampleGroup.count()[:,[0,2]] File "/Users/foo/miniconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 1997, in __getitem__ return self._getitem_column(key) File "/Users/foo/miniconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 2004, in _getitem_column return self._get_item_cache(key) File "/Users/foo/miniconda2/lib/python2.7/site-packages/pandas/core/generic.py", line 1348, in _get_item_cache res = cache.get(item) TypeError: unhashable type </code></pre>
-1
2016-08-27T21:52:26Z
39,186,332
<p>For the number of unique elements in each group, you can use:</p> <pre><code>df.groupby('c_b')['c_a', 'c_d'].agg(pd.Series.nunique) </code></pre> <hr> <pre><code>df.groupby('c_b')['c_a', 'c_d'].agg(pd.Series.nunique) Out: c_a c_d c_b c++ 2 2 python 2 2 df.groupby('c_b', as_index=False)['c_a', 'c_d'].agg(pd.Series.nunique) Out: c_b c_a c_d 0 c++ 2 2 1 python 2 2 </code></pre>
1
2016-08-27T22:24:50Z
[ "python", "python-2.7", "pandas", "dataframe", "group-by" ]
Positive Negative - Simple Python exercise
39,186,071
<p>Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative.</p> <p>I finally figured it out.</p> <pre><code>def pos_neg(a, b, negative): if negative: return (a &lt; 0 and b &lt; 0) else: return (a &gt; 0 and b &lt; 0) or (a &lt; 0 and b &gt; 0) </code></pre> <p>But... why do I return those two lines instead of True? How do I know to do this in a similar situation?</p>
-4
2016-08-27T21:52:50Z
39,186,097
<p>You are not returning those two lines. You are returning the values that those two lines <em>evaluate to</em>. In your cases, those are boolean expressions that will evaluate to either true or false. That final boolean value is what your function returns.</p>
1
2016-08-27T21:55:42Z
[ "python" ]
Positive Negative - Simple Python exercise
39,186,071
<p>Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative.</p> <p>I finally figured it out.</p> <pre><code>def pos_neg(a, b, negative): if negative: return (a &lt; 0 and b &lt; 0) else: return (a &gt; 0 and b &lt; 0) or (a &lt; 0 and b &gt; 0) </code></pre> <p>But... why do I return those two lines instead of True? How do I know to do this in a similar situation?</p>
-4
2016-08-27T21:52:50Z
39,186,360
<p>Python evaluates whatever expression follows the <code>return</code> statement, and the result of the evaluation is what is returned. You have used two boolean expressions:</p> <pre><code>(a &lt; 0 and b &lt; 0) </code></pre> <p>This evaluates to True if both a &lt; 0 and b &lt; 0; otherwise it evaluates to False</p> <pre><code>(a &gt; 0 and b &lt; 0) or (a &lt; 0 and b &gt; 0) </code></pre> <p>This evaluates to True if either of the parentheses evaluate to True; otherwise it evaluates to False</p> <p>which is what you want. So <code>pos_neg</code> automatically returns either True or False depending on the specified inputs.</p> <p>Perhaps you were thinking of testing each condition for True/False, then using an <code>if</code> statement to <code>return True</code> if the condition is True and to <code>return False</code> if the condition is False. That would work, but would be unnecessarily long and complex. Here, you are just returning with whatever the boolean value of each expression works out to be, whether it's <code>True</code> or <code>False</code>.</p>
1
2016-08-27T22:28:10Z
[ "python" ]
Django form - using variable from database
39,186,161
<p>I have the following form which is working perfectly:</p> <pre><code># coding=utf-8 from django import forms from straightred.models import StraightredTeam from straightred.models import UserSelection class SelectTwoTeams(forms.Form): cantSelectTeams = UserSelection.objects.filter(campaignno=102501349) currentTeams = StraightredTeam.objects.filter(currentteam = 1).exclude(teamid__in=cantSelectTeams.values_list('teamselectionid', flat=True)) team_one = forms.ModelChoiceField(queryset = currentTeams) team_two = forms.ModelChoiceField(queryset = currentTeams) </code></pre> <p>However, as you can see the campaignno is hard written into the query. Ideally I would like to select the maximum campaignno from a mysql table and use that as the campaigno instead of the 102501349 as above. The mysql table and model is as follows:</p> <p>mySQL table:</p> <pre><code>mysql&gt; desc straightred_userselection; +-------------------+----------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------------+----------------------+------+-----+---------+----------------+ | userselectionid | int(11) | NO | PRI | NULL | auto_increment | | campaignno | varchar(36) | NO | | NULL | | | teamselection1or2 | smallint(5) unsigned | NO | | NULL | | | fixtureid | int(11) | YES | MUL | NULL | | | teamselectionid | int(11) | NO | MUL | NULL | | | user_id | int(11) | NO | MUL | NULL | | +-------------------+----------------------+------+-----+---------+----------------+ </code></pre> <p>Django Model:</p> <pre><code>class StraightredSeason(models.Model): seasonid = models.IntegerField(primary_key = True) seasonyear = models.CharField(max_length = 4) seasonname = models.CharField(max_length = 36) def __unicode__(self): return self.seasonid class Meta: managed = True db_table = 'straightred_season' </code></pre> <p>I hope this makes sense but if you require any more information then just ask :)</p> <p>I appreciate any assistance in advance, many thanks, Alan.</p>
0
2016-08-27T22:02:37Z
39,191,129
<p>Got there in the end :)</p> <p>I used the following: </p> <pre><code>campaignnoquery = UserSelection.objects.filter(user=349).order_by('-campaignno')[:1] for x in campaignnoquery: test2 = x.campaignno </code></pre> <p>I can then use test2 as the variable.</p>
0
2016-08-28T12:11:28Z
[ "python", "mysql", "django" ]
Model comparison in PyMC3
39,186,183
<p>I am new to PyMC3 and am trying to implement the hierarchical model from Kruschke (2015) section 12.2.2 (model comparison). </p> <p>I succeeded in defining the full model and then looking at the differences of posterior parameter values (determine whether difference can credibly be said to be zero).</p> <p>I also tried to explicitly do the comparison in the model as shown in the book (defining a full model and a restricted model and sampling these using a categorical distribution). </p> <p>Basically I try to implement the below JAGS model definition in PyMC3.<BR> <a href="http://nbviewer.jupyter.org/github/JWarmenhoven/DBDA-python/blob/master/Notebooks/Chapter%2012.ipynb" rel="nofollow">http://nbviewer.jupyter.org/github/JWarmenhoven/DBDA-python/blob/master/Notebooks/Chapter%2012.ipynb</a><BR> But I don't know how I can use the model index to select the (pseudo) priors. Any pointers?</p> <p>JAGS:</p> <pre><code>model { for ( s in 1:nSubj ) { nCorrOfSubj[s] ~ dbin( theta[s] , nTrlOfSubj[s] ) theta[s] ~ dbeta( aBeta[CondOfSubj[s]] , bBeta[CondOfSubj[s]] ) } for ( j in 1:nCond ) { # Use omega[j] for model index 1, omega0 for model index 2: aBeta[j] &lt;- ( equals(mdlIdx,1)*omega[j] + equals(mdlIdx,2)*omega0 ) * (kappa[j]-2)+1 bBeta[j] &lt;- ( 1 - ( equals(mdlIdx,1)*omega[j] + equals(mdlIdx,2)*omega0 ) ) * (kappa[j]-2)+1 omega[j] ~ dbeta( a[j,mdlIdx] , b[j,mdlIdx] ) } omega0 ~ dbeta( a0[mdlIdx] , b0[mdlIdx] ) for ( j in 1:nCond ) { kappa[j] &lt;- kappaMinusTwo[j] + 2 kappaMinusTwo[j] ~ dgamma( 2.618 , 0.0809 ) # mode 20 , sd 20 } # Constants for prior and pseudoprior: aP &lt;- 1 bP &lt;- 1 # a0[model] and b0[model] a0[1] &lt;- .48*500 # pseudo b0[1] &lt;- (1-.48)*500 # pseudo a0[2] &lt;- aP # true b0[2] &lt;- bP # true # a[condition,model] and b[condition,model] a[1,1] &lt;- aP # true a[2,1] &lt;- aP # true a[3,1] &lt;- aP # true a[4,1] &lt;- aP # true b[1,1] &lt;- bP # true b[2,1] &lt;- bP # true b[3,1] &lt;- bP # true b[4,1] &lt;- bP # true a[1,2] &lt;- .40*125 # pseudo a[2,2] &lt;- .50*125 # pseudo a[3,2] &lt;- .51*125 # pseudo b[1,2] &lt;- (1-.40)*125 # pseudo b[2,2] &lt;- (1-.50)*125 # pseudo b[3,2] &lt;- (1-.51)*125 # pseudo b[4,2] &lt;- (1-.52)*125 # pseudo # Prior on model index: mdlIdx ~ dcat( modelProb[] ) modelProb[1] &lt;- .5 modelProb[2] &lt;- .5 } </code></pre> <p>PyMC3:</p> <pre><code>with pmc.Model() as model_1: # constants aP, bP = 1, 1 # Pseudo- and true hyperpriors per model a0 = [.48*500, aP] b0 = [(1-.48)*500, bP] # Lower level pseudo- and true priors per model/condition combination a = np.c_[np.tile(aP, 4), [(.40*125), (.50*125), (.51*125), (.52*125)]] b = np.c_[np.tile(bP, 4), [(1-.40)*125, (1-.50)*125, (1-.51)*125, (1-.52)*125]] # Prior on model index [0,1] m_idx = pmc.Categorical('m_idx', np.asarray([.5, .5])) # Priors on concentration parameters kappa = pmc.Gamma('kappa', 2.618, 0.0809, shape=nCond) # omega0 omega0 = pmc.Beta('omega0', a0[m_idx], b0[m_idx]) # omega (condition specific) omega = pmc.Beta('omega', a[:,m_idx], b[:,m_idx], shape=nCond) # theta aBeta = pmc.switch(eq(m_idx, 0), omega0 * kappa[cond_idx]+1, omega[cond_idx] * kappa[cond_idx]+1) bBeta = pmc.switch(eq(m_idx, 0), (1-omega0) * kappa[cond_idx]+1, (1-omega[cond_idx]) * kappa[cond_idx]+1) theta = pmc.Beta('theta', aBeta[cond_idx], bBeta[cond_idx], shape=df.index.size) # Likelihood y = pmc.Binomial('y', n=df.nTrlOfSubj.values, p=theta, observed=df.nCorrOfSubj) Applied log-transform to kappa and added transformed kappa_log_ to model. </code></pre> <p>Output:</p> <pre><code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-40-74e77ccc6ce9&gt; in &lt;module&gt;() 8 9 # omega0 ---&gt; 10 omega0 = pmc.Beta('omega0', a0[m_idx], b0[m_idx]) 11 12 # omega (condition specific) TypeError: list indices must be integers or slices, not FreeRV </code></pre> <p><strong>UPDATED</strong><br> After correcting the pseudopriors (missing parenthesis) the results look much better. However, I am not sure whether the pmc.Beta() function works well with arrays as arguments for a and b. <a href="http://nbviewer.jupyter.org/github/JWarmenhoven/DBDA-python/blob/master/Notebooks/Chapter%2012.ipynb" rel="nofollow">http://nbviewer.jupyter.org/github/JWarmenhoven/DBDA-python/blob/master/Notebooks/Chapter%2012.ipynb</a></p>
1
2016-08-27T22:05:56Z
39,199,113
<p>The error you are getting is because you are trying to index a list using a tensor. One way to solve this will be to turn the list into a tensor. </p> <pre><code>import theano.tensor as tt a0 = tt.as_tensor([.48*500, aP]) </code></pre> <p>Alternatively you can use <code>pmc.switch()</code> to choose between priors and pseudopriors, something like:</p> <pre><code>a0 = pm.switch(m_idx, .48*500, aP) </code></pre> <p>I did not check your code thoroughly, but notice you have</p> <pre><code>pmc.switch(eq(m_idx, 0)....) </code></pre> <p>Instead, you should write </p> <pre><code>pmc.switch(pmc.eq(m_idx, 0)....) </code></pre> <p>or may be:</p> <pre><code>pmc.switch(m_idx)....) </code></pre> <p>Since 0 evaluates as <code>False</code> and 1 evaluates as <code>True</code>.</p> <p>Also you have</p> <pre><code>omega = pmc.Beta('omega0'...) </code></pre> <p>And you should have </p> <pre><code>omega = pmc.Beta('omega'...) </code></pre> <p>Your question made me realize I forgot to <a href="https://github.com/aloctavodia/Doing_bayesian_data_analysis" rel="nofollow">port</a> a pseudoprior example. I will do it ASAP.</p> <p><strong>EDITED</strong></p> <p>Here if the full model</p> <pre><code>with pmc.Model() as model_1: # constants aP, bP = 1., 1. # Pseudo- and true hyperpriors per model a0 = tt.as_tensor([aP, .48*500]) b0 = tt.as_tensor([bP, (1-.48)*500]) # Lower level pseudo- and true priors per model/condition combination a = tt.as_tensor(np.c_[[(.40*125), (.50*125), (.51*125), (.52*125)], np.tile(aP, 4)]) b = tt.as_tensor(np.c_[[((1-.40)*125), ((1-.50)*125), ((1-.51)*125), ((1-.52)*125)], np.tile(bP, 4)]) # Prior on model index [0,1] m_idx = pmc.Categorical('m_idx', p=np.array([.5, .5])) # Priors on concentration parameters kappa = pmc.Gamma('kappa', 2.618, 0.0809, shape=nCond) # omega0 omega0 = pmc.Beta('omega0', a0[m_idx], b0[m_idx]) # omega (condition specific) omega = pmc.Beta('omega', a[:,m_idx], b[:,m_idx], shape=nCond) # theta aBeta = pmc.switch(pmc.eq(m_idx, 0), omega0 * kappa+1, omega * kappa+1) bBeta = pmc.switch(pmc.eq(m_idx, 0), (1-omega0) * kappa+1, (1-omega) * kappa+1) theta = pmc.Beta('theta', aBeta, bBeta, shape=nCond) # Likelihood y = pmc.Binomial('y', n=df.nTrlOfSubj.values, p=theta[cond_idx], observed=df.nCorrOfSubj) trace = pmc.sample(1000) </code></pre> <p>Notice that your code had several issues, like missing parenthesis in the definition of the variable <code>b</code> and the order of the prior and pseudopriors was inverted. Additionally I change the code in ordet to let <code>aBeta</code>, <code>bBeta</code> and <code>theta</code>have shape=nCond, and then in the likellihood define <code>p</code> as <code>p=theta[cond_idx]</code>. </p> <p>I did not check the results against Kruschke's book, but the trace look reasonable.</p>
1
2016-08-29T05:36:27Z
[ "python", "bayesian", "pymc3" ]
What is web.session.Session in the python web.py module
39,186,201
<p>I'm currently learning Python and can't work out what the <code>web.session.Session</code> is in the follow game program:</p> <pre><code>app = web.application(urls, globals()) session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'room': None}) </code></pre> <p>What are <code>app</code>, <code>Diskstore</code>, and <code>initializer</code>?</p>
1
2016-08-27T22:07:53Z
39,234,533
<p>This <code>web.session</code> module gives you the session support, </p> <ul> <li><p><code>initializer</code> - You can set the initial session which is not mandatory.</p> <p>eg: <code>initializer={'room': None}</code> sets the initial session of room to None.</p></li> <li><p><code>DiskStore</code> makes the session to save in disk whereas <code>DBStore</code> stores session in databases.</p></li> <li><code>app</code> gives the application instance created as <code>web.application(urls, globals())</code> with URLs which mapped to the relevant classes.</li> </ul> <p>Refer <a href="http://webpy.org/cookbook/sessions" rel="nofollow">this</a>.</p>
0
2016-08-30T18:20:36Z
[ "python", "web.py" ]
How to add instance variable to Scrapy CrawlSpider?
39,186,207
<p>I am running a CrawlSpider and I want to implement some logic to stop following some of the links in mid-run, by passing a function to <code>process_request</code>.</p> <p>This function uses the spider's <strong>class</strong> variables in order to keep track of the current state, and depending on it (and on the referrer URL), links get dropped or continue to be processed:</p> <pre><code>class BroadCrawlSpider(CrawlSpider): name = 'bitsy' start_urls = ['http://scrapy.org'] foo = 5 rules = ( Rule(LinkExtractor(), callback='parse_item', process_request='filter_requests', follow=True), ) def parse_item(self, response): &lt;some code&gt; def filter_requests(self, request): if self.foo == 6 and request.headers.get('Referer', None) == someval: raise IgnoreRequest("Ignored request: bla %s" % request) return request </code></pre> <p>I think that if I were to run several spiders on the same machine, they would all use the same <strong>class</strong> variables which is not my intention.</p> <p>Is there a way to add <strong>instance</strong> variables to CrawlSpiders? Is only a single instance of the spider created when I run Scrapy?</p> <p>I could probably work around it with a dictionary with values per process ID, but that will be ugly...</p>
0
2016-08-27T22:08:25Z
39,188,109
<p>I think <a href="http://doc.scrapy.org/en/latest/topics/spiders.html#spider-arguments" rel="nofollow">spider arguments</a> would be the solution in your case.</p> <p>When invoking scrapy like <code>scrapy crawl some_spider</code>, you could add arguments like <code>scrapy crawl some_spider -a foo=bar</code>, and the spider would receive the values via its constructor, e.g.:</p> <pre><code>class SomeSpider(scrapy.Spider): def __init__(self, foo=None, *args, **kwargs): super(SomeSpider, self).__init__(*args, **kwargs) # Do something with foo </code></pre> <p>What's more, as <a href="https://github.com/scrapy/scrapy/blob/master/scrapy/spiders/__init__.py#L30" rel="nofollow"><code>scrapy.Spider</code> actually sets all additional arguments as instance attributes</a>, you don't even need to explicitly override the <code>__init__</code> method but just access the <code>.foo</code> attribute. :)</p>
1
2016-08-28T04:47:44Z
[ "python", "scrapy", "scrapy-spider" ]
More elegant conversion of Postgres data within pandas Dataframe
39,186,262
<p>I have some data in a PostgreSQL table.</p> <p>I am pulling the data back to a notebook via code like the following:</p> <pre><code>import numpy as np import pandas as pd %load_ext sql %sql postgresql://foo:foo@localhost:5432/barbar result_from_sql = %%sql SELECT Date, Year,Score, Cost FROM MyData; result_df = result_from_sql.DataFrame() </code></pre> <p>In the PostgreSQL table all columns were typed accurately but <code>result_df</code> is as follows:</p> <pre><code>result_df.dtypes date object year int64 score object cost object </code></pre> <p>Converting the date column was fine:</p> <pre><code>result_df['date'] = pd.to_datetime(result_df['date']) </code></pre> <p>As was ensuring all <code>None</code> values are now <code>NaN</code> values:</p> <pre><code>result_df.replace([None], [np.nan], inplace=True) </code></pre> <p>But to convert the columns score &amp; cost to numeric I need to execute the following 3 lines of code:</p> <pre><code>s = ['score', 'cost'] result_df[s] = pd.to_numeric(result_df[s].astype(str), errors = 'coerce') result_df[s] = result_df[s].apply(pd.to_numeric, errors='coerce') </code></pre> <p>If I use only lines 1 and 2 then the typing is still object - if I use only lines 1 and 3 then all the data is converted to <code>NaN</code> as if all the data has not coerced.</p> <p>Why do I have to use this code and is there a more elegant solution?</p>
0
2016-08-27T22:16:13Z
39,187,676
<p>you can use the following solution to parse to numeric:</p> <hr> <pre><code>s = ['score', 'cost'] result_df[s] = result_df[s].astype(float) # incase you wanted to parse them to floats </code></pre> <p>let me know if this works </p>
1
2016-08-28T03:08:27Z
[ "python", "postgresql", "pandas" ]
Tkinter - Make status bar longer than window
39,186,503
<p>I was working on a Tkinter GUI with a status bar at the bottom to display instructions or the file paths on hover over a specific widget, especially if the file path was too long to write in the given section. Is there any way that the status bar could extends past the window in the case of a long name? (Like maybe a window without the top bar?)</p> <p>The status bar is cut off at the end: <a href="http://i.stack.imgur.com/hzAt2.png" rel="nofollow"><img src="http://i.stack.imgur.com/hzAt2.png" alt="Status bar is cut off"></a></p> <p>What I want the status bar to look like: <a href="http://i.stack.imgur.com/d9IU3.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/d9IU3.jpg" alt="enter image description here"></a></p> <p>I've seen other applications where the status bar can extend past the window but I was wondering if that was possible in Tkinter. Any help would be appreciated!</p>
1
2016-08-27T22:51:48Z
39,189,008
<p>Yes, it's possible:</p> <pre><code>from tkinter import * root = Tk() root.geometry("800x500-500+50") root.config(bg="lightblue") stslabel = Label(root, anchor=W, text="Process another input file to get citations. blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah" ) stslabel.pack(fill=X, side=BOTTOM) </code></pre> <p>All you need to do is using the most proper geometry manager (<code>pack</code> in this case) for the <code>label</code> widget that is intended to show a status (<code>ststlabel</code>); then adding some options to the geometry manager: <code>fill</code> makes it extended as you stretch the window horizontally; and <code>side</code> puts it at the very bottom of the screen which means it will always stay there (until you make the geometry of any of preceding widgets to bottom. Otherwise, it'll be replaced with that).</p> <p>Now we got it! But there is a problem that it doesn't show the beginning of the status text. To solve this add an <code>anchor</code> option to the status label and change its value to <code>W</code> since we want to see the beginning (the most left side) of the text. And <code>W</code> which stands for "West", <i>does</i> it.</p>
0
2016-08-28T07:36:37Z
[ "python", "tkinter" ]
Flask, MySQL and SQLAlchemy quering ID error
39,186,521
<p>I get a weird error when I try to query an item by id. I have tried all suggestion I have found and only when doing raw query I get a proper result.</p> <p>Part of the Traceback:</p> <pre><code> File "C:\Users\pgsid\Envs\xo\lib\site-packages\flask\app.py", line 1988, in wsgi_app response = self.full_dispatch_request() File "C:\Users\pgsid\Envs\xo\lib\site-packages\flask\app.py", line 1641, in full_dispatch_requ`est rv = self.handle_user_exception(e) File "C:\Users\pgsid\Envs\xo\lib\site-packages\flask\app.py", line 1544, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\pgsid\Envs\xo\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\pgsid\Envs\xo\lib\site-packages\flask\app.py", line 1625, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "xow.py", line 24, in get_user a = User.get_item(user_id) File "C:\Users\pgsid\xo\xow\models\users.py", line 57, in get_item result = User.query.filter_by(id=idd).first() File "C:\Users\pgsid\Envs\xo\lib\site-packages\sqlalchemy\orm\query.py", line 2659, in first ret = list(self[0:1]) File "C:\Users\pgsid\Envs\xo\lib\site-packages\sqlalchemy\orm\query.py", line 2457, in __getitem__ return list(res) File "C:\Users\pgsid\Envs\xo\lib\site-packages\sqlalchemy\orm\loading.py", line 86, in instances util.raise_from_cause(err) File "C:\Users\pgsid\Envs\xo\lib\site-packages\sqlalchemy\util\compat.py", line 202, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File "C:\Users\pgsid\Envs\xo\lib\site-packages\sqlalchemy\orm\loading.py", line 71, in instances rows = [proc(row) for row in fetch] File "C:\Users\pgsid\Envs\xo\lib\site-packages\sqlalchemy\orm\loading.py", line 428, in _instance loaded_instance, populate_existing, populators) File "C:\Users\pgsid\Envs\xo\lib\site-packages\sqlalchemy\orm\loading.py", line 486, in _populate_full dict_[key] = getter(row) TypeError: an integer is required </code></pre> <p>The query is <code>result = User.query.filter_by(id=idd).first()</code> with idd of type <code>int</code>.</p> <p>The type of the ID field in MySQL db is <code>INT</code> </p> <p>and the model is like this</p> <pre><code>class User(db.Model): __tablename__ = 'user' id = db.Column('id', db.INT, primary_key=True) name = db.Column(db.VARCHAR, index=True) post = db.Column(db.VARCHAR, nullable=True) type = db.Column(db.VARCHAR) url = db.Column(db.VARCHAR, nullable=True) subtype = db.Column(db.VARCHAR, nullable=True) tel = db.Column(db.VARCHAR, nullable=True) address = db.Column(db.VARCHAR, nullable=True) latitude = db.Column(db.FLOAT) longitude = db.Column(db.FLOAT) deleted = db.Column(db.Boolean, default=False, index=True) children = db.relationship("Children") </code></pre> <p>The database is initialized as such:</p> <pre><code>app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:test@localhost/mydb' db = SQLAlchemy(app) </code></pre> <p>What could be wrong? Any suggestions?</p>
0
2016-08-27T22:55:47Z
39,187,997
<p>Turns out it was the fact that in the MySQL schema for some reason deleted was defined as a <code>BIT</code> type. </p> <p>All type combinations in SQLAlchemy failed. I had to change the schema to make it into a <code>TINYINT(1)</code></p>
0
2016-08-28T04:24:47Z
[ "python", "mysql", "flask", "sqlalchemy" ]