input_text
stringlengths
1
40.1k
target_text
stringlengths
1
29.4k
How do you run your own code alongside Tkinter's event loop? My little brother is just getting into programming and for his Science Fair project he is doing a simulation of a flock of birds in the sky He is gotten most of his code written and it works nicely but the birds need to move <them>every moment</them> Tkinter however hogs the time for its own event loop and so his code will not run Doing `root mainloop()` runs runs and keeps running and the only thing it runs is the event handlers Is there a way to have his code run alongside the mainloop (without multithreading it is confusing and this should be kept simple) and if so what is it? Right now he came up with an ugly hack tying his `move()` function to `<b1-motion&gt;` so that as long as he holds the button down and wiggles the mouse it works But there is got to be a better way
Use the `after` method on the `Tk` object: ````from tkinter import * root = Tk() def task(): print("hello") root after(2000 task) # reschedule event in 2 seconds root after(2000 task) root mainloop() ```` Here is the declaration and documentation for the `after` method: ````def after(self ms func=None *args): """Call function once after given time MS specifies the time in milliseconds FUNC gives the function which shall be called Additional parameters are given as parameters to the function call Return identifier to cancel scheduling with after_cancel """ ````
Who designed Parry Hall?
null
Recursive Function To Help Clear Tiles (Field Of View) I am attempting to teach myself python and have hit a rough spot once it has come to recursion I have done the classic recursive functions (factorial fibonacci numbers ) but I am going back over old code and trying to convert most of my iterative functions to recursive functions for practice This is the wall that I have hit: I made a dungeon crawler a while back and I am trying to replace a for loop I used to reveal the squares near my sprite So when the sprite is placed he/she sees the tile he/she is on as well as the adjacent and diagonal squares (9 in total including the one the avatar is on) The other tiles making up the room are hidden This I deemed view radius 1 For view radius 2 I wanted the char to see radius 1 squares plus all the tiles adjacent to those tiles At the time I could not figure out how to do it with a for loop so I just implemented a simpler scheme I feel this visibility function could be written recursively but I am having a hard time coming up with a base case and what my recursive step would be My for loop just took avatar pos and iterated over a range to avatar pos radius and I did that for the x y coordinates As far as translating this over to a recursive function I am really confused I have done many searches trying to get a lead but only come up with complicated subjects such as: FOV using recursive shadowcasting which is way beyond me Any help would be greatly appreciated
How about something like this: ````def visible(pos radius seen): if radius == 1: # base case seen add( ) yield else: for center in visible(pos radius-1 seen): for x in visible(center 1 seen): if x not in seen: seen add(x) yield x ```` `seen` would be a `set` Each time you call `visible` "from the outside" you would supply an empty set: ````visible(pos radius set()) ```` The `seen` set could also be initialized to implement fog of war (or at least oddly unseeable squares ;) )
How to integrate celery with Django when settings needs to be injected in? I am working on a new project where every developer has his own settings file In order to run Django I have to load it like this: ````python manage py runserver --settings="databank_web settings dqs dev_houman" ```` I have now to integrate Celery 3 1 into the project and this approach is causing me a lot of headache I have followed all the steps to integrate the Celery into Django as described <a href="http://docs celeryproject org/en/latest/django/first-steps-with-django html#using-celery-with-django" rel="nofollow">here </a> I can run Django as usual but now I have to run celery with my custom Django environment as described in this <a href="http://stackoverflow com/questions/21864876/celery-3-1-9-django-integration-specifying-settings-file-without-using-djceler">solution </a> ````DJANGO_SETTINGS_MODULE='databank_web settings dqs dev_houman' celery -A databank_web worker -l info ```` This seems to get a step further but I get this error message: ````File "/Users/houman/git/venv/lib/python2 7/site-packages/django/contrib/admin/sites py" line 3 in <module&gt; from django contrib admin import ModelAdmin actions ImportError: cannot import name actions ```` I did some research and followed <a href="http://stackoverflow com/a/24188232/92153">this solution</a> in order to narrow it down: ````import os os environ setdefault("DJANGO_SETTINGS_MODULE" "databank_web settings dqs dev_houman") from django contrib admin import ModelAdmin actions ```` This was meant to clarify which error is throwing however it seems to work just fine So I am clueless why this is failing within Django environment So why am I getting those `ImportError: cannot import name actions` errors? Much appreciated
It sounds more like a circular dependency If you followed the guide you should have created a new file called `celery py` In `celery py` ````from __future__ import absolute_import import os from celery import Celery from django conf import settings # set the default Django settings module for the 'celery' program os environ setdefault('DJANGO_SETTINGS_MODULE' 'proj settings') app = Celery('proj') app config_from_object('django conf:settings') app autodiscover_tasks(lambda: settings INSTALLED_APPS) ```` Comment out `os environ setdefault('DJANGO_SETTINGS_MODULE' 'proj settings')` because this is trying to overwrite whatever you pass outside the scope Then set the `DJANGO_SETTINGS_MODULE` variable outside the file
python: unpacking a string to a list The answer to <a href="http://stackoverflow com/questions/335695/lists-in-configparser">a question on multiple-value elements in a config file</a> (which exactly fits my needs) suggests to "unpack the string from the config" I read the doc for <a href="http://docs python org/tutorial/controlflow html#unpacking-argument-lists" rel="nofollow">unpacking arguments lists</a> suggested in several places but I fail to understand how this relates to my problem I am sure this must be obvious: having a string `str = "123 456"` how can I transform it into the list `[123 456]` (the number of elements separated by a comma in the string may vary) Thank you
The easiest way would be to use <a href="http://docs python org/library/stdtypes html#str split" rel="nofollow">`split()`</a> ````unpacked = str split(' ') ````
In what year was Candide released?
null
In the film Dick Tracy, who did Madonna starred as?
Breathless Mahoney
change colormap labels in mayavi/mlab I am doing a quiver3d plot with vector length scaled by log(length)+5 in order to visualize a large range of lengths between 0 and 1 Is there however a way to change the colormap back to the original values while showing a logarithmic scale? I would like to do this purely in python because if have problems running the mayavi GUI <img src="http://i stack imgur com/y28pu png" alt="trying to change this to logarithmic">
I do not know of a nice way to do it but I can think of a hacky one that might well be the easiest thing to do: create an invisible dummy object with the right colormap and display the colorbar from that object
Python strip() not working inside a function I am trying to use `strip()` to trim off the space before and after a string It works fine for ````str1 = " abdced " str1 strip() ```` However when I use it inside a function it is not working: ````def func(str1): return str1 strip() print func(" abdwe ") ```` It will not trim off any space Anyone can tell what is happening? Thanks!
`strip` is not an in-place method meaning it returns a value which must be reassigned like so: ````str1 = str1 strip() # the string is reassigned to the returned stripped string ````
At what point were all members of the household named on a census?
1850
How much had the Chinese government designated by May 16?
$772 million
When did New York City annex part of Pelham?
1895
How many votes were there in total on the Everton fan site about the new crest?
null
Random guessing in Python I have 40 cards 10 yellow 10 red 10 blue and 10 green I need to pick 25 random cards and then give them to 500 people Each one needs to guess the right color for each of the 25 cards This is what I have done so far: ```` import random nSuits = 4 # yellow/red/blue/green nCards = 25 # Number of random cards nPlayers = 500 def Random_guess(): randomCards = [random randrange(nSuits) for i in range(nCards)] randomGuesses = [random randrange(nSuits) for i in range (nPlayers)] ```` The `randomCards` works fine according to the she will but I cannot find a way to attribute the random cards to each player and to their guess from the 4 colors Any suggestion?
if i understand correctly each player needs 25 guesses (one for each card): ````randomGuesses = [[random randrange(nSuits) for i in range (nCards)] for j in range(nPlayers)] ```` this will produce a list with nPlayer nested lists each with nCards "guesses" ````randomGuesses[i][j] ```` is the j'th guess of the i'th player
Facing issues while parsing XML with namespaces in python while using lxml I am trying to access and modify a tag deep with in the hierarchy of an XML I have used quite a few options to reach it Please help me accessing and modifying the tag Here is my XML : ````<soapenv:Envelope xmlns:soapenv="http://schemas xmlsoap org/soap/envelope/" xmlns:cre="http://www code com/abc/V1/createCase"&gt; <soapenv:Header&gt;<wsse:Security xmlns:wsse="http://docs oasis-open org/2" xmlns:wsu="http://docs oasis-open org/a xsd"&gt;</wsse:Security&gt; </soapenv:Header&gt; <soapenv:Body xmlns:wsu="http://docs oasis-open org/30 xsd" wsu:Id="id-14"&gt; <cre:createCase&gt; <cre:Request&gt; <cre:ServiceAttributesGrp&gt; <cre:MinorVer&gt;?</cre:MinorVer&gt; </cre:ServiceAttributesGrp&gt; <cre:CreateCaseReqGrp&gt; <cre:Language&gt;English</cre:Language&gt; <cre:CustFirstNm&gt;Issue</cre:CustFirstNm&gt; <cre:CustLastNm&gt;Detection</cre:CustLastNm&gt; <cre:AddlDynInfoGrp&gt; <cre:AddlDynInfo&gt; <cre:FieldNm&gt;TM3</cre:FieldNm&gt; <cre:FieldVal&gt;</cre:FieldVal&gt; </cre:AddlDynInfo&gt; <cre:AddlDynInfo&gt; <cre:FieldNm&gt;PM417</cre:FieldNm&gt; <cre:FieldVal&gt;Not Defined</cre:FieldVal&gt; </cre:AddlDynInfo&gt; </cre:AddlDynInfoGrp&gt; <cre:CreateCriteriasGrp&gt; <cre:CreateCriterias&gt; <cre:CriteriaNm&gt;CriticalReqDtlValidationReqd</cre:CriteriaNm&gt; </cre:CreateCriterias&gt; </cre:CreateCriteriasGrp&gt; </cre:CreateCaseReqGrp&gt; </cre:Request&gt; </cre:createCase&gt; </soapenv:Body&gt; </soapenv:Envelope&gt; ```` I have to access and modify the value of "FieldVal" tag in "AddlDynInfo" Tag where the corresponding value of "FieldNm" tag value is "PM417" (since there are two occurances of "AddlDynInfo" tag As of now I am stuck on the parent tag only as I could not access it : ````tree = etree parse(template_xml) root = tree getroot() for msgBody in root[1]: for createCase in msgBody: for request in createCase: print request for CreateCaseReqGrp in request findall('{cre}CreateCaseReqGrp' namespaces=root nsmap): print CreateCaseReqGrp ````
Defined <a href="http://lxml de/xpathxslt html#namespaces-and-prefixes" rel="nofollow">namespaces and XPaths</a> make this quite easy Your case would be something like this: ````ns = { 'soapenv': 'http://schemas xmlsoap org/soap/envelope/' 'cre': 'http://www code com/abc/V1/createCase' } for casereq in root xpath( 'soapenv:Body/cre:createCase/cre:Request/' 'cre:CreateCaseReqGrp/cre:AddlDynInfoGrp/cre:AddlDynInfo' namespaces=ns): print casereq xpath('cre:FieldNm/text()' namespaces=ns) print casereq xpath('cre:FieldVal/text()' namespaces=ns) ````
Python Script to run other Python Scripts I have a Python Script that I am trying to write to run other Python Scripts The goal is to be able to have a script I run all the time to execute my other scripts overnight (I tried this using a batch file and it would execute them but they would not create the csv files for some reason) Here is the code I have now ````import time import subprocess from threading import Timer fileRan = False #Function to launch other python files def runFiles(): print('Running Scripts Now') subprocess call("cmd" "report1 py" she will=True) subprocess call("cmd" "report2 py" she will=True) subprocess call("cmd" "report3 py" she will=True) subprocess call("cmd" "report4 py" she will=True) subprocess call("cmd" "report5 py" she will=True) subprocess call("cmd" "report6 py" she will=True) #Function to check current system time against time reports should run def checkTime(fileRan): startTime = '15:20' endTime = '15:25' print('Current Time Is: ' time strftime('%H:%M' time localtime())) print(fileRan) if startTime < time strftime('%H:%M' time localtime()) < endTime and fileRan is False: runFiles() fileRan = True return fileRan #Timer itself t = Timer(60 0 checkTime(fileRan)) t start() ```` It will make the first pass and print the current time and the state of fileRan just fine It appears to break either when I make the second check or when it tried to execute the files Here is the error I am getting: ````Exception in thread Thread-1: Traceback (most recent call last): File "C:\Python34\lib\threading py" line 921 in _bootstrap_inner self run() File "C:\Python34\lib\threading py" line 1187 in run self function(*self args **self kwargs) TypeError: 'NoneType' object is not callable ```` Any help I could get would be great!
Your subprocess call() is incorrect see the proper syntax here: <a href="https://docs python org/2/library/subprocess html" rel="nofollow">https://docs python org/2/library/subprocess html</a> ````subprocess call(["python" "report1 py"] she will=True) ```` There are also other tools to do this for you such as <a href="http://unixgeeks org/security/newbie/unix/cron-1 html" rel="nofollow">cron</a>
Convert DICOM to TIFF I am new to Python so forgive my ignorance If I do not have all the info correct I am trying raster through a directory and convert all the DICOM files within to TIFF files I have gotten the search functionality to work but I am having a hard time saving the images as TIFFs I am using the pydicom libraries to read in the DICOM and manipulate the header information Also I have tried using the save_as function in pydicom to save to TIFF but I would rather use the save function in PIL to properly set the compression of the TIFF I think the problem is that I cannot/do not understand how to extract the actual image data from a DICOM and place it in a new image Any Help would be greatly appreciated Cheers Python 2 7 PIL 1 1 7 Pydicom 0 9 6
If you know how to use `PIL` to save image data as ` tiff` <a href="http://code google com/p/pydicom/source/browse/source/dicom/contrib/pydicom_PIL py" rel="nofollow">this example</a> should help you to pass image data from `pydicom` to `PIL` (there is more <a href="http://code google com/p/pydicom/wiki/ViewingImages#Using_pydicom_with_Python_Imaging_Library_%28PIL%29" rel="nofollow">here in the comments</a>)
How do I add two polygons in Python using Shapely? I do not know how to add two polygons in Python using Shapely By adding I mean for instance if I was adding two squares with height 4 and width 2 and they had the same coordinates it should return a square that has height 8 and width 2 I have tried using MultiPolygons and also using union between the two polygons but I am not able to get the desired accumulative height result Does anybody know how to do what I described? Or are there any other Python modules out there that will allow me to do the same?
Have you tried the union function? Beware if the polygons do not intersect it will return a MultiPolygon An example: ````from shapely geometry import Polygon p1 = Polygon([(0 0) (1 0) (1 1) (0 1)]) p2 = Polygon([(0 1) (1 1) (2 1) (2 2)]) newp = p1 union(p2) ````
using json loads in python with an output from php json_encode In my php script I have run the following ````//PHP script to send json data to python $t = new test(); $t>testname1 = $testname; $t>jmx1=$jmx; #$jsondata=json_encode($t); $output=shell_exec('python /var/www/metro/run py' escapeshellarg(json_encode($jsondata)) ); ```` Example of the json output as the following ````"{"testname1":"fairul" "jmx1":"1562638904 jmx"}" ```` I would like to use json loads from the argument argv1 above in order to access it in python ````import sys json # Load the data that PHP sent us try: data = json loads(sys argv[1]) except: result = data['testname1'] # Send it to stdout (to PHP) print json dumps(result) ```` Not sure why i could only get NULL output
You encoded the data <them>twice</them>; encode it just once: ````$t>jmx1=$jmx; $jsondata=json_encode($t); $output=shell_exec('python /var/www/metro/run py ' escapeshellarg($jsondata) ); ```` In Python drop the blanked `except` handler and move the setting `result` <them>out</them> of the exception handler Here I moved it into the `try` instead catching either the `IndexError` when `sys argv[1]` does not exist `ValueError` thrown by a bad JSON string `TypeError` when trying to index something that is not a dictionary or the `KeyError` thrown for a missing key: ````import sys json # Load the data that PHP sent us try: data = json loads(sys argv[1]) result = data['testname1'] except (ValueError TypeError IndexError KeyError) as e: print json dumps({'error': str(e)}) sys exit(1) print json dumps(result) ````
How do I simulate biased die in python? I want to simulate N-sided biased die? ````def roll(N bias): '''this function rolls N dimensional die with biasing provided''' # do something return result &gt;&gt; N=6 &gt;&gt; bias=( 0 20 0 20 0 15 0 15 0 14 0 16 ) &gt;&gt; roll(N bias) 2 ````
More language agnostic but you could use a lookup table Use a random number in the range 0-1 and lookup the value in a table: ````0 00 - 0 20 1 0 20 - 0 40 2 0 40 - 0 55 3 0 55 - 0 70 4 0 70 - 0 84 5 0 84 - 1 00 6 ````
Bottle framework caches my template even in debug mode There is a similar question on here but the answers are over 2 years old and I cannot get it to work If I am missing something - please let me know <a href="http://stackoverflow com/questions/9073645/bottle-py-caching-templates-despite-being-in-debug-mode">Bottle py caching templates despite being in debug mode</a> Whenever the browser points to 0 0 0 0:8080/16boxes I need to prevent caching The Bottle docs say when in Debug mode caching is disabled but that is not the case for me unfortunately Here is my hello py code in question: ````@route('/16boxes') def send_static(): response set_header('Cache-control' 'no-cache must-revalidate') return template (resource_path('16boxes html') globalVar0 = globalVar0) run(host='0 0 0 0' port=8080 debug=True) ```` I open up terminal and run: `python hello py` It does not cache when I run it on my Mac/Chrome - but when I use Windows and Internet Explorer - it uses a cached version How can I prevent this? In my 16boxes html I even have the following in my : ````<meta http-equiv="Cache-control" content="no-cache no-store must-revalidate"&gt; <meta http-equiv="Expires" content="0" /&gt; <meta http-equiv="Pragma" content="no-cache"&gt; ````
Your problem is that your JavaScript onload event does not fire when the page loads as a result of browser caching <a href="http://docs jquery com/Events/ready#fn" rel="nofollow">jQuery's ready</a> event was created for just this sort of issue
I have this function that is supposed to count points but it does not add them I have this function that is supposed to count points but it does not add them: ````def Correct(totalPoints): print "Correct" totalPoints = totalPoints+1 print "You have" totalPoints "points" ```` Here is an example of what I use it in: ````elif answer == 'nba': NBAQues = random randint(0 len(NBA1)-1) NBAVar = NBA1[NBAQues] print NBAVar NBAAnswer = raw_input() NBAAnswer = NBAAnswer lower() if NBAAnswer == NBA2[NBAQues]: print Correct(totalPoints) elif NBAAnswer != NBA2[NBAQues]: print "False The correct answer was" NBA2[NBAQues] NBA1 remove(NBAVar) NBA2 remove(NBA2[NBAQues]) print "Choose another " ````
`totalPoints` is being cloned inside your function To do what you want you should set `totalPoints` based on the function result like so: ````def Correct(totalPoints): print "Correct" totalPoints = totalPoints+1 print "You have" totalPoints "points" return totalPoints totalPoints = Correct(totalPoints) ```` This ignores why you would want such a function in the first place but it should work
Python pandas slice dataframe by multiple index ranges What is the pythonic way to slice a dataframe by more index ranges (eg by `10:12` and `25:28`)? I want this in a more elegant way: ````df = pd DataFrame({'a':range(10 100)}) df iloc[[i for i in range(10 12)] [i for i in range(25 28)]] ```` Result: ```` a 10 20 11 21 25 35 26 36 27 37 ```` Something like this would be more elegant: ````df iloc[(10:12 25:28)] ```` Thank you!
You can use numpy's <a href="http://docs scipy org/doc/numpy/reference/generated/numpy r_ html" rel="nofollow">r_</a> "slicing trick": ````df = pd DataFrame({'a':range(10 100)}) df iloc[pd np r_[10:12 25:28]] ```` Gives: ```` a 10 20 11 21 25 35 26 36 27 37 ````
Python Audio Streaming in P2P I wanted to do a pet project that works sort of like Skype sending audio between 2 computers in P2P what module exist in python to create a project like that and how does the audio stream works in theory? how does the data transfers in live between 2 computers?
You can use python to do this but too keep things simple I would break the problem down into smaller manageable parts - `audio` There are many python audio modules take a look <a href="http://wiki python org/moin/Audio/" rel="nofollow">here</a> I guess you will want one that can handle streams rather than ` mp3` or ` wav` files - `P2P` You will need to learn up on TCP/IP - in particular `socket` can help with this (<a href="http://docs python org/2/library/socket html" rel="nofollow">docs</a>) but it can be quite complicated It sounds like a fun project good luck!
Why does PolyCollection always closed? Hello everyone I tried to plot polygons through matplotlib collections polycollection However the polygons is always closed even when I set closed=Fasle How can I not close my polygons? Sample code is given below ````import matplotlib from matplotlib collections import PolyCollection import matplotlib pyplot as plt import numpy as np if __name__ == '__main__': xy = np random rand(12) reshape(2 3 2) p=PolyCollection(xy closed=False) fig = plt figure() ax1 = fig add_subplot(111) ax1 add_collection(p) ````
It is actually not closing the polygon when close = False However when you are "filling" the polygon it automatically fills up to the border where it would be closed Consider the following revised code ````import matplotlib from matplotlib collections import PolyCollection import matplotlib pyplot as plt import numpy as np if __name__ == '__main__': xy = np random rand(8) reshape(1 4 2) p=PolyCollection(xy closed=False edgecolors = 'red' facecolors = 'white') fig = plt figure() ax1 = fig add_subplot(111) ax1 add_collection(p) ```` By setting the edgecolor to something noticeable like red and the facecolor=white you can clearly see that the when closed=False the polygon is not closed In this case closed means drawing the final edge between the first and last coordinates However if the facecolor is something like blue it of course has to "close" the polygon to fill the space otherwise there would be no constraints on where the face begins and ends
Codecademy battleship function I am supposed to create a `5x5` grid of `['OF]`s I tried the following code: ````board = [] def filler(x): c = ['OF] * 5 for i in c: board append(i) print (c) filler(c) ```` Which creates the 5x5 grid that they ask for What I cannot figure out is why is the grid not being added to board? Is there something wrong with my for loop? I looked at this <a href="http://stackoverflow com/questions/21434430/codeacademy-battleship">page</a> and noticed that no one suggests a function which is something I also do not understand Is a function not appropriate for this exercise (or is it just my function that is not appending correctly?)
That does not create a 5x5 grid You first create a flat `list` of `['OF 'OF 'OF 'OF 'OF]` then you iterate over it and append each element to the board making `board` an equal `list` The `x` parameter in the function is never used You should throw the whole thing out and just do this: ````def create_board(size): return [['OF for column in range(size)] for row in range(size)] board = create_board(5) ```` This uses nested comprehensions to create a 2D `list` of the size you want Demo: ````&gt;&gt;&gt; for row in board: print(*row) O O O O O O O O O O O O O O O O O O O O O O O O O ````
How to do zero down time schema migrations for large tables I am looking for a solution that is compatible with django mysql/postgres to do online migrations The best solution I have seen is <a href="https://github com/soundcloud/lhm" rel="nofollow">Large Hadron Migrator</a> but LHM is a rails application and I would need to keep the ORMs in sync by hand the second best tool I have looked at is <a href="http://www percona com/doc/percona-toolkit/2 1/pt-online-schema-change html" rel="nofollow">pt-online-schema-change</a> but I am not quite sure on how to integrate it with django's migration tool There are alternatives like the tool <a href="https://www facebook com/note php?note_id=430801045932&amp;_fb_noscript=1" rel="nofollow">OnlineSchemaChange php</a> from facebook and <a href="https://github com/freels/table_migrator" rel="nofollow">TableMigrator</a> from twitter but both seem inactive I have also stumbled upon <a href="https://code google com/p/openarkkit/" rel="nofollow">oak</a> but did not really into it So the question is How can I make django migrations (1 7 not south) for large tables that can potentially hog IO without dowtime
If that is on option: <strong>Migrate your application to MySQL 5 6</strong> - migrations are way less painless since MySQL 5 6 supports online DDL just like PostgreSQL and it will release you from many headaches migrating big tables Here is a list of what is possible: <a href="http://dev mysql com/doc/refman/5 6/en/innodb-create-index-overview html" rel="nofollow">http://dev mysql com/doc/refman/5 6/en/innodb-create-index-overview html</a> For older versions of MySQL there is really no silver bullet that will do magic for you with South &amp; Django my advise is to Google for a migration pattern known as <strong>Expand/Contract</strong> I have used pt-online-schema-change with big success also on older MySQL 5 5/
Calling functions by array index in Python I have a bunch of functions in Python out1 out2 out3 etc and would like to call them based on an integer I pass in ````def arryofPointersToFns (value): #call outn where n = value ```` Is there an easy way to do this?
tl;dr: Write an `out(n)` function rather than `out1() out2() outN(n)` and do not bother with this hack I cannot imagine a reasonable scenario where this question would come up in practice Please reconsider the architecture of the problem; there is likely to be a much better way to do this (because storing them in a list implies there is nothing meaningful about the functions except the index; for example I can only imagine that you would want to do this if you were creating a bunch of dynamically-generated thunks where their temporal ordering matters or something similar) Especially any novice users you are reading this answer consider making a more general function that can handle everything or associating to each function some more identifying information or sticking it as part of a class etc That said this is how you would do it ````myFuncs = [f0 f1 f2] myFuncs[2]( ) #calls f2 ```` or ````myFuncs = {'alice':f1 'bob':f2} myFuncs['alice']( ) ```` this is just the following two steps in one step: ````myFuncs = [f0 f1 f2] f = myFuncs[i] f() ```` or if you do not have a registry of functions 'myFunc' like the OP said above you can use globals() though it is extremely hackish form and to be avoided (unless you want those functions to be available in your module namespace in which case maybe it is fine but this is probably rarely the case and you would probably rather define those functions in a submodule then `from mysubmodule import *` them which is in turn slightly frowned upon): ````def fN(n): return globals()['f'+str(n)] def f2(): print("2 was called!") fN(2)( ) #calls f2 ```` <hr> here are two other ideas (added after answer was accepted and first two comments): You can also create a decorator like this: ````&gt;&gt;&gt; def makeRegistrar(): registry = {} def registrar(func): registry[func __name__] = func return func # normally a decorator returns a wrapped function # but here we return func unmodified after registering it registrar all = registry return registrar ```` and use it like so: ````&gt;&gt;&gt; reg = makeRegistrar() &gt;&gt;&gt; @reg def f1(a): return a+1 &gt;&gt;&gt; @reg def f2(a b): return a+b &gt;&gt;&gt; reg all {'f1': <function f1 at 0x7fc24c381958&gt; 'f2': <function f2 at 0x7fc24c3819e0&gt;} ```` then you can call reg all['f1'] You could adapt the `reg` decorator to keep track of the indexing and do something like: ````registry = [] index = int(re regextofindthenumber(func __name__)) if not index==len(registry): raise Exception('Expected def f{} but got def f{}') else: registry[index] = func ```` Alternatively to avoid `globals()` you could define a class: ````class Funcs(object): def f1(): def f2(): def num(n): [code goes here] ```` If your number of functions is small you could get away with `['f1' 'f2' 'f3'][i]` Of course without further information all these suggestions are just ignoring the real problem: this situation should never come up and is a possibly a sign of a serious architecture flaw when you would probably rather have something (to use your example) like: ````# a possibly-better world def out(n): # output to N whatever that means ```` rather than ````# what you have now def out1(): # output to 1 def out2(): # output to 2 def outN(n): # ??? ````
Printing object attributes based on user input in Python 3x First of all I would like to say i am a Python beginner (or programming beginner for that matter) and I am trying to figure out how to print attributes from a object based on user input This is the code I have so far: ````class Customer: "De klasse customer" def __init__(self naam adres woonplaats email): self naam = naam self adres = adres self woonplaats = woonplaats self email = email input1 = input ("Enter the object name") print(input1 naam) ## ** << This is what i like to know** a = Customer('Name1' 'address' 'Utrecht' 'Email1@hotmail com') b = Customer('Name2' 'Bonestaak' 'Maarssen' 'Bijjaapishetaltijdraakhotmail com') ```` So I basically want this: `print(a naam)` to work but the 'a' must be entered by a user Did some searching but no success so far
You can use the `locals` function: ````&gt;&gt;&gt; a = {1:'abc'} &gt;&gt;&gt; obj = raw_input('Obj?&gt; ') Obj?&gt; a &gt;&gt;&gt; print locals()[obj][1] abc &gt;&gt;&gt; ```` This is however an <strong>highly</strong> insecure construct (there are other things in locals!) <hr> A cleaner way would be to: ````customers = { 'a' : Customer('Name1' 'address' 'Utrecht' 'Email1@hotmail com') 'b' : Customer('Name2' 'Bonestaak' 'Maarssen' 'Bijjaapishetaltijdraakhotmail com') } customer = raw_input('Customer? &gt; ') print customers[customer] naam ```` You will need to handle `KeyError` properly though!
What part of the Olympic area was not damaged?
venues
Saving a PIL generated PNG Image on a server with PHP I have got a python Image object from a screen capture that I want to save on a server running PHP I want to do all of this without at all saving the image on the user's computer so I want to send the PHP script an encoding it can understand which I can get from the PIL Image instance So far I have tried saving the Image to a buffer (in python) and sending the data to the PHP function file_put_contents but the resulting file is not a correct png image (I have just saved the PNG encoding string to a file with a png extension ) Here is my code <strong>Client</strong> ````# shot is an Image instance buff = StringIO() shot save(buff 'PNG') args = {'filename':'eg png' 'image': buff getValue()} data = urllib urlencode(args) request = urllib2 Request(self uploadURL data) urllib2 urlopen(request) read() ```` <strong>Server</strong> ````# 'filename' arg ends in png 'image' arg is the upload parameter ^ $filename = 'images/' $_POST['filename']; file_put_contents($filename $_POST['image']); ```` I take it I need to convert the image data with PHP before I try to write it to file but I am not sure how I have done this before by saving the Image to file and sending the binary content in base 64 but I do not wish to save the Image on the client's computer at all Thanks! Disclaimer: This question and my perception on encoding feels entirely 'icky' to me so sorry for being such a huge noob / horrible misunderstanding
The PHP side is more complex I guess that the upload is done with an HTTP POST file If it is then `$_POST['image']` is not the whole content of the uploaded file See <a href="http://www php net/manual/en/features file-upload post-method php" rel="nofollow">http://www php net/manual/en/features file-upload post-method php</a> and `move_uploaded_file()`
Importing Ghostscript in Python on Windows 8 I have been trying to import ghostscript into Python in order to convert pdf files to a tiff format I am using Python version 2 7 10 on Windows 8 I have successfully downloaded and installed ghostscript using pip and it appears in the correct location ( \Anaconda\Lib\sitepackages) I have confirmed that other packages located in this directory can be imported into Python I am using the command `import ghostscript` When I do so I get an error message: <blockquote> RuntimeError: Can not find Ghostscript DLL in registry </blockquote> The traceback indicates that calling the file "ghoscript_init_ py" successfully imports _gsprint as gs However when the import function attempts to access "ghostscript_gsprint py" it produces the RuntimeError where it is unable to find the Ghostscript DLL I would be very grateful for any advice or tips Thanks!
As well as installing `ghostscript` python bindings from PyPI with `pip install ghostscript` you also need to install the correct Ghostscript program for your platform as described on the <a href="https://pypi python org/pypi/ghostscript" rel="nofollow">PyPI page</a> That page states that version 8 x is required but I am currently using 9 2 successfully The download links are <a href="http://ghostscript com/download/" rel="nofollow">here</a>
how to return an excel sheet and a string response using httpresponse Django Python I am currently returning a response page as a string but I also want to pass it as an excel file I am having trouble doing both This is my views py file: ````response = HttpResponse(htmlString) response = HttpResponse(mimetype='application/vnd ms-excel') response['Content-Disposition'] = 'attachment; filename=example1 xls' book save(response) return response ```` This only gives me the excel file and not the HtmlString which is because I am reassigning response but I do not know how to include both paramaters THanks in advance!!
A HTTP response (as in the HTTP protocol this is not limited to Django) will be treated by the browser either as a file or displayed in the browser (html plain text etc) You cannot return a response with both
Python interfacing with C library - How to have a null c pointer I have the following old c code ````const char *c[3]; c[0] = "ABC"; c[1] = "EFG"; c[2] = 0; c_function(c); ```` Now I need to use Python to call old c function I have the following code ````c_names = (c_char_p * 3)() c_names[0] = "ABC"; c_names[1] = "EFG"; // c[2] = 0?? libc = CDLL("c_library dll") libc c_function(c_names) ```` May I know what is the Python equivalent for `c[2] = 0;`?
````pointer = None ```` <a href="http://docs python org/library/ctypes html" rel="nofollow">http://docs python org/library/ctypes html</a> check 15 16 1 3 Calling functions
How to append even and odd chars python I want to convert all the even letters using one function and all the odd numbers using another function So each letter represents 0-25 correspsonding with a-z so a c e g i k m o q s you w y are even characters However only my even letters are converting correctly ````def encrypt(plain): charCount = 0 answer=[] for ch in plain: if charCount%2==0: answer append(pycipher Affine(7 6) encipher(ch)) else: answer append(pycipher Affine(3 0) encipher(ch)) return '' join(answer) ````
You never change `charCount` in your loop -- So it starts at `0` and stays at `0` which means that each `ch` will be treated as "even" Based on your update you actually want to check if the character is odd or even based on it is "index" in the english alphabet Having some sort of mapping of characters to numbers is helpful here You could build it yourself: ````alphabet = 'abcde ' # string ascii_lowercase? mapping = {k: i for i k in enumerate(alphabet)} ```` <them>OR</them> we can use the builtin `ord` noticing that `ord('a')` produces an odd result `ord('b')` is even etc ````def encrypt(plain): answer=[] for ch in plain: if ord(ch) % 2 == 1: # 'a' 'c' 'e' answer append(pycipher Affine(7 6) encipher(ch)) else: # 'b' would' 'f' answer append(pycipher Affine(3 0) encipher(ch)) return '' join(answer) ````
Read pipe (C/C++) no error but not all data In a C++ program I want to fetch some data that a python program can easily provide The C++ program invokes `popen()` reads the data (a serialized protobuf) and continues on This worked fine but has recently begun to fail with a shorter string received than sent <strong>I am trying to understand why I am not reading what I have written</strong> (despite no error reported) and how to generate further hypotheses Fwiw this is on linux (64 bit) and both processes are local Python is 2 7 <them>(It is true the data size has gotten large (now 17MB where once 500 KB) but this should not lead to failure although it is a sure signal I need to make some changes for the sake of efficiency )</them> On the python side I compute a dict of group_id mapping to group (a `RegistrationProgress` cf below): ````payload = RegistrationProgressArray() for group_id group in groups items(): payload group add() CopyFrom(group) payload num_entries = len(groups) print('{a} {p}' format(a=len(groups) p=len(payload group)) file=sys stderr) print(payload SerializeToString()) print('size={s}' format(s=len(payload SerializeToString())) file=sys stderr) ```` Note that `a` and `p` match (correctly!) on the python side The size will be about 17MB On the C++ side ````string FetchProtoFromXXXXX<string&gt;(const string&amp; command_name) { ostringstream fetch_command; fetch_command << /* */ ; if (GetMode(kVerbose)) { cout << "FetchProtoFromXXXXX()" << endl; cout << endl << fetch_command str() << endl << endl; } FILE* fp = popen(fetch_command str() c_str() "r"); if (!fp) { perror(command_name c_str()); return ""; } // There is sadly no even remotely portable way to create an // ifstream from a FILE* or a file descriptor So we do this the // C way which is of course just fine const int kBufferSize = 1 << 16; char c_buffer[kBufferSize]; ostringstream buffer; while (!feof(fp) &amp;&amp; !ferror(fp)) { size_t bytes_read = fread(c_buffer 1 kBufferSize fp); if (bytes_read < kBufferSize &amp;&amp; ferror(fp)) { perror("FetchProtoFromXXXXX() failed"); // Can we even continue? Let us try but expect that it // may set us up for future sadness when the protobuf // is not readable } buffer << c_buffer; } if (feof(fp) &amp;&amp; GetMode(kVerbose)) { cout << "Read EOF from pipe" << endl; } int ret = pclose(fp); const string out_buffer(buffer str()); if (ret || GetMode(kVerbose)) { cout << "Pipe closed with exit status " << ret << endl; cout << "Read " << out_buffer size() << " bytes " << endl; } return out_buffer; } ```` ) The size will be about 144KB The protobuf I am sending looks like this The `num_entries` was a bit of paranoia since it should be the same as `group_size()` which is the same as `group() size()` ````message RegistrationProgress { } message RegistrationProgressArray { required int32 num_entries = 1; repeated RegistrationProgress group = 2; } ```` Then what I run is ````array = FetchProtoFromXXXXX("my_command py"); cout << "size=" << array num_entries() << endl; if (array num_entries() != array group_size()) { cout << "Something is wrong: array num_entries() == " << array num_entries() << " != array group_size() == " << array group_size() << " " << array group() size() << endl; throw MyExceptionType(); } ```` and the output of running it is ````122 122 size=17106774 Read EOF from pipe Pipe closed with exit status 0 Read 144831 bytes size=122 Something is wrong: array num_entries() == 122 != array focus_group_size() == 1 1 ```` Inspecting the deserialized protobuf it appears that group is an array of length one containing only the first element of the array I expected
This ````buffer << c_buffer; ```` requires that `c_buffer` contain ASCIIZ content but in your case you are not NUL-terminating it Instead make sure the exact number of bytes read are captured (even if there are embedded `NUL`s): ````buffer write(c_buffer bytes_read); ````
Basic Flask: ImportError: cannot import name Flask I am following along with a <a href="http://blog miguelgrinberg com/post/the-flask-mega-tutorial-part-i-hello-world" rel="nofollow">Flask tutorial</a> and I am creating a `run py` file running chmod a+x run py and running the file as ` /run py` Unfortunately I get this: ````Traceback (most recent call last): File " /run py" line 3 in <module&gt; from app import app File "/Users/benjaminclayman/Desktop/microblog/app/__init__ py" line 1 in <module&gt; from flask import Flask ImportError: cannot import name Flask ```` For reference my run py file is: ````#!flask/bin/python from app import app app run(debug=True) ```` And when I run ````from flask import Flask ```` there is no issue (I do not get any error message) I looked at similar issues on SO and it looks like often it was having a file called `flask py` but I do not have one (AFAIK) Any idea what I did incorrectly?
Make your shebang ````#!/usr/bin/env python ```` and run again See <a href="http://stackoverflow com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script">this question</a>
How to extract Regression predictor of Scikit-learn to implement into C++? I did some training using Random Forest Regression (or any kind of regressions) of Scikit-learn and got the predictor: ````predictor = RandomForestRegressor(n_estimators=n_estimators) predictor fit(X_train Y_train) ```` How can I extract information in `predictor` to implement into C++ as a filter only for prediction? What I need is to build a "predictor" in C++ to get: `Y_predict = predictor(X_test)` without any training in C++
The <a href="http://scikit-learn org/stable/modules/generated/sklearn ensemble RandomForestRegressor html" rel="nofollow">sklearn documentation for RFR</a> says that you have ```` property estimators_ : list of DecisionTreeRegressor ```` From <a href="http://scikit-learn org/stable/modules/generated/sklearn tree DecisionTreeRegressor html" rel="nofollow">DecisionTreeRegressor</a> you can get the attributes you need specifically tree_ attribute
CSS/JavaScript manager for django Is there a CSS and/or JavaScript manager module for django? What I am looking for in functionality: - I would like to be able to define which stylesheets and javascript files to load on a per view basis (this by itself is easy to do in bare django but bear with me ) - I would like the plugin to automatically combine/optimize the "source" CSS/JS and insert the output into the appropriate view Does something like that exist?
Take a look at <a href="http://www allbuttonspressed com/projects/django-mediagenerator" rel="nofollow">django-mediagenerator</a>
Parse all item elements with children from RSS feed with beautifulsoup From an RSS feed how do you get a string of everything that is inside each <strong>item</strong> tag? Example input (simplified): ````<?xml version="1 0" encoding="UTF-8"?&gt; <rss version="2 0"&gt; <channel&gt; <title&gt;Test</title&gt; <item&gt; <title&gt;Hello world1</title&gt; <comments&gt;Hi there</comments&gt; <pubDate&gt;Tue 21 Nov 2011 20:10:10 0000</pubDate&gt; </item&gt; <item&gt; <title&gt;Hello world2</title&gt; <comments&gt;Good afternoon</comments&gt; <pubDate&gt;Tue 22 Nov 2011 20:10:10 0000</pubDate&gt; </item&gt; <item&gt; <title&gt;Hello world3</title&gt; <comments&gt;blue paint</comments&gt; <pubDate&gt;Tue 23 Nov 2011 20:10:10 0000</pubDate&gt; </item&gt; </channel&gt; </rss&gt; ```` I need a python function that takes this RSS file (I am using beautifulsoup now) and has a loop that goes through each item I need a variable that has a string of everything within each <strong>item</strong> Example first loop result: ````<title&gt;Hello world1</title&gt; <comments&gt;Hi there</comments&gt; <pubDate&gt;Tue 21 Nov 2011 20:10:10 0000</pubDate&gt; ```` This code gets me the first result but how do I get all the next ones? ````html_data = BeautifulSoup(xml) print html_data channel item ````
Since this is XML use <a href="http://www crummy com/software/BeautifulSoup/documentation html#Parsing%20XML" rel="nofollow">BeautifulStoneSoup</a>: ````import BeautifulSoup doc = BeautifulSoup BeautifulStoneSoup(xml) for item in doc findAll('item'): for elt in item: if isinstance(elt BeautifulSoup Tag): print(elt) ```` And here is how you could do the same thing with <a href="http://codespeak net/lxml/" rel="nofollow">lxml</a> (which for some reason I find much easier to use): ````import lxml etree as ET doc = ET fromstring(xml) for item in doc xpath('//item'): for elt in item xpath('descendant::*'): print(ET tostring(elt)) ````
Is there any module that allows Django/Python to work with gnupg? I was wondering if there is any django module or in such case any python module that will allow me to create my own application to manage the creation administration etc of GnuPG keys as well as the ability to sign and encrypt documents through this application? If there is no such module how can I do that? Thank you
<a href="http://py-gnupg sourceforge net/" rel="nofollow">GnuPGInterface</a> can <a href="http://sourceforge net/docman/display%5Fdoc php?docid=5499&amp;group%5Fid=29555" rel="nofollow">do all of that</a> -- it is essentially a Python wrapper around the GnuPG program <a href="http://pyme sourceforge net/" rel="nofollow">PyMe</a> might be easier to use as it is designed to wrap around GPGME (ME = Made Easy) From <a href="http://pyme sourceforge net/doc/pyme/index html" rel="nofollow">the PyME features page</a>: <blockquote> - Ability to sign encrypt decrypt and verify data - Ability to list keys export and import keys and manage the keyring </blockquote>
How to send a Facebook App Notification via the Graph API? I would like my Facebook canvas app to send an <a href="https://developers facebook com/docs/concepts/notifications/" rel="nofollow">App Notification</a> to a user's friend when they interact with the app Here is my server-side code (using App Engine and urllib) `conf FACEBOOK_APP_ACCESS_TOKEN` is an <a href="https://developers facebook com/docs/opengraph/howtos/publishing-with-app-token/" rel="nofollow">App Access Token</a> which I got by making a single call to the Graph API and then hardcoding the returned value as explained in the link The app access token looks something like: ````426547656256546|4fhe34FJdeV3WvfF6SNfehs7GfW ```` This is not my actual token: I have substituted numbers for other numbers capital letters for other capital letters etc so you can see the format ````url = 'https://graph facebook com/'+friendID+'/notifications' values = {'access_token' : conf FACEBOOK_APP_ACCESS_TOKEN 'href' : 'http://localhost:8080/' 'template' : '@['+userID+'] says hi '} data = urllib urlencode(values) req = urllib2 Request(url data) urllib2 urlopen(req) ```` `urlopen` gives the errors: ````WARNING Stripped prohibited headers from URLFetch request: ['Content-Length' 'Host'] ERROR HTTP Error 403: Forbidden ```` What do I need to correct in this code to successfully send an app notification?
App notifications can only be send from Canvas apps My app was set to `Website with Facebook Login` in the Facebook settings which does not allow notifications To solve the problem I just checked `App on Facebook` in addition to `Website with Facebook Login` (though I believe it works with only `App on Facebook` as well) and specified a canvas URL
How to see if section of python code completes within a given time I wish to find out if code (Say a function call) completes within a given time For example if I am calling a function with parameters that are elements of an array ```` #arr1 is some array #foo1 is an array that returns something for i in range(len(arr1)): res1 = foo1(arr1[i]) #calling the function ```` Is there some way by which I can stop foo1 executing and continue with the next iteration of the for loop if foo1 takes more than x seconds to return a value?
To do this cleanly and correctly you need cooperation from `foo1()` If you do not the best you can do is to run `foo1()` in the context of another process and to kill that process after a timeout
Average trend curve for data points in Python I would love to reproduce a plot similar to this: <img src="http://www brleader com/news/images/nothing1 jpg" alt=""> I mean I have a set of data points and I would love to have a curve which shows the average trend I tried adding random noise to the function y=2x ```` from scipy import interpolate x=arange(0 1 1e-3) noise=np random random(len(x)) y=2*x+noise ```` And then I used some of the Scipt function to interpolate data ```` xnew=arange(0 1 1e-1) f=interpolate UnivariateSpline(x y) g=interpolate interp1d(x y) plot(x y 'ro' xnew f(xnew) '-' xnew g(xnew) '--') show() ```` But the curve I get hardly resemble y=2*x I would love to have a smooth curve which average the data Which method/function can I use?
You can try <a href="http://www aps anl gov/bcda/dataVis/fit py html" rel="nofollow">fit py</a> a curve fitting package for Python
Django Binary or BLOB model field I have a C# program that inserts a pdf inside a MySQL database Now I want to retrieve that pdf via django but django's `models FileField` needs an "Upload To" parameter which means behind the scenes it actually stores the File on the file system rather than in the database Is there any way I can set up a django model so that I can store the pdf directly inside MySQL? Regards
I have been dealing with this same issue writing a pdf to a mediumblob field in mysql and retrieving via django I have set the mysql field type to a mediumblob and the django field type to textfield I have used a queryset and httpresponse to view the PDF objects in a browser (but not directly in django)
Printing a square dot board I need to make a program in python to print a square board consisting of dots The size is input by the user (between 2x2 and 9x9 squares) eg 4x4 = ```` ```` The program asks the user for the int value between 2-9 and prints the board eg board_size? 4
Here is your homework (being s the size of the square): ````print "\n" join ( [" " join ( [" " for i in range (s) ] ) for j in range (s) ] ) ```` Just scan the size s from stdin or wherever the user inputs it
How to get Riak 2 0 security working with riak-python-client? Riak 2 0 is installed on Ubuntu 14 04 with default settings Riak python client is taken from dev branch: <a href="https://github com/basho/riak-python-client/tree/feature/bch/security" rel="nofollow">https://github com/basho/riak-python-client/tree/feature/bch/security</a> <strong>Steps I made:</strong> 1 Enable security: ````&gt; riak-admin security enable ```` 2 Check status: ````&gt; riak-admin security status &gt; Enabled ```` 3 Add example user group and apply some basic permissions 4 Overall it looks like following: <strong>user:</strong> ````riak-admin security print-users ----------+---------------+----------------------------------------+------------------------------+ | username | member of | password | options | ----------+---------------+----------------------------------------+------------------------------+ | user_sec | group_sec |ce055fe0a2d621a650c293a56996ee504054ea1d| [] | ----------+---------------+----------------------------------------+------------------------------+ ```` <strong>user's grants:</strong> ````riak-admin security print-grants user_sec Inherited permissions (user/user_sec) --------------------+----------+----------+----------------------------------------+ | group | type | bucket | grants | --------------------+----------+----------+----------------------------------------+ | group_sec | default | * | riak_kv get | | group_sec |bucket_sec| * | riak_kv get | --------------------+----------+----------+----------------------------------------+ Cumulative permissions (user/user_sec) ----------+----------+----------------------------------------+ | type | bucket | grants | ----------+----------+----------------------------------------+ | default | * | riak_kv get | |bucket_sec| * | riak_kv get | ----------+----------+----------------------------------------+ ```` <strong>auth sources:</strong> ````riak-admin security print-sources --------------------+------------+----------+----------+ | users | cidr | source | options | --------------------+------------+----------+----------+ | user_sec | 0 0 0 0/32 | password | [] | | user_sec |127 0 0 1/32| trust | [] | --------------------+------------+----------+----------+ ```` <strong>simple python script I am trying to run (on the same host where Riak is running):</strong> ````import riak from riak security import SecurityCreds pbc_port = 8002 riak_host = "127 0 0 1" creds = riak security SecurityCreds('user_sec' 'secure_password') riak_client = riak RiakClient(pb_port=pbc_port host=riak_host protocol='pbc' security_creds=creds) bucket = riak_client bucket('test') data = bucket get("42") print data data ```` stack trace I am getting: python riak_test py ````Traceback (most recent call last): File "riak_test py" line 8 in <module&gt; data = bucket get("42") File "/usr/local/lib/python2 7/dist-packages/riak/bucket py" line 214 in get return obj reload(r=are pr=pr timeout=timeout) File "/usr/local/lib/python2 7/dist-packages/riak/riak_object py" line 307 in reload self client get(self r=are pr=pr timeout=timeout) File "/usr/local/lib/python2 7/dist-packages/riak/client/transport py" line 184 in wrapper return self _with_retries(pool thunk) File "/usr/local/lib/python2 7/dist-packages/riak/client/transport py" line 126 in _with_retries return fn(transport) File "/usr/local/lib/python2 7/dist-packages/riak/client/transport py" line 182 in thunk return fn(self transport *args **kwargs) File "/usr/local/lib/python2 7/dist-packages/riak/client/operations py" line 382 in get return transport get(robj r=are pr=pr timeout=timeout) File "/usr/local/lib/python2 7/dist-packages/riak/transports/pbc/transport py" line 148 in get if self quorum_controls() and pr: File "/usr/local/lib/python2 7/dist-packages/riak/transports/feature_detect py" line 102 in quorum_controls return self server_version &gt;= versions[1] File "/usr/local/lib/python2 7/dist-packages/riak/util py" line 148 in __get__ value = self fget(obj) File "/usr/local/lib/python2 7/dist-packages/riak/transports/feature_detect py" line 189 in server_version return LooseVersion(self _server_version()) File "/usr/local/lib/python2 7/dist-packages/riak/transports/pbc/transport py" line 101 in _server_version return self get_server_info()['server_version'] File "/usr/local/lib/python2 7/dist-packages/riak/transports/pbc/transport py" line 119 in get_server_info expect=MSG_CODE_GET_SERVER_INFO_RESP) File "/usr/local/lib/python2 7/dist-packages/riak/transports/pbc/connection py" line 51 in _request return self _recv_msg(expect) File "/usr/local/lib/python2 7/dist-packages/riak/transports/pbc/connection py" line 137 in _recv_msg raise RiakError(err errmsg) riak RiakError: 'Security is enabled please STARTTLS first' ```` When security is disabled the same script works perfectly fine: ````python riak_test py {you'question': you"what is the sense of universe?"} ```` I also tried to generate example certificates using this tool: <a href="https://github com/basho-labs/riak-ruby-ca" rel="nofollow">https://github com/basho-labs/riak-ruby-ca</a> and set them in riak conf: ````grep ssl /etc/riak/riak conf ## with the ssl config variable for example: ssl certfile = $(platform_etc_dir)/server crt ## Default key location for https can be overridden with the ssl ssl keyfile = $(platform_etc_dir)/server key ## with the ssl config variable for example: ssl cacertfile = $(platform_etc_dir)/ca crt ```` and use ca crt in python script: ````creds = riak security SecurityCreds('user_sec' 'secure_password' 'ca crt') ```` It did not change anything I am still getting the same exception I guess this problem might be trivial but I do not have any clue for now <strong>Update:</strong> I was using wrong param name Few commits ago it was: <strong>security_creds</strong> now it is called: <strong>credentials</strong> When I fixed this in my script SSL handshake was initialized Then next exceptions were caused by wrong SecurityCreds initialization Constructor is using named params so it should be: ````creds = riak security SecurityCreds(username='user_sec' password='secure_password' cacert_file='ca crt') ```` handshake is initialized but it is failing on this command: ````ssl_socket do_handshake() ```` from riak/transport/pbc/connection py (line 134) I am getting these 2 errors (randomly): ```` File "/home/gta/riak-python-client/riak/transports/pbc/connection py" line 77 in _init_security self _ssl_handshake() File "/home/gta/riak-python-client/riak/transports/pbc/connection py" line 145 in _ssl_handshake raise e OpenSSL SSL SysCallError: (104 'ECONNRESET') File "/home/gta/riak-python-client/riak/transports/pbc/connection py" line 77 in _init_security self _ssl_handshake() File "/home/gta/riak-python-client/riak/transports/pbc/connection py" line 145 in _ssl_handshake raise e OpenSSL SSL SysCallError: (-1 'Unexpected EOF') ```` I am also observing errors in Riak's logs (/var/log/riak/error log): ````2014-06-02 15:09:33 954 [error] <0 1995 1&gt; gen_fsm <0 1995 1&gt; in state wait_for_tls terminated with reason: {error {startls_failed {certfile badarg}}} 2014-06-02 15:09:33 955 [error] <0 1995 1&gt; CRASH REPORT Process <0 1995 1&gt; with 0 neighbours exited with reason: {error {startls_failed {certfile badarg}}} in gen_fsm:terminate/7 line 622 2014-06-02 15:09:33 955 [error] <0 28750 0&gt; Supervisor riak_api_pb_sup had child undefined started with {riak_api_pb_server start_link undefined} at <0 1995 1&gt; exit with reason {error {startls_failed {certfile badarg}}} in context child_terminated ```` This situation happens with both approaches: cacert (ca crt) and client cert (client crt)/key (client key) I tried various combinations of keys: - keys from tests/resource - keys generated with riak-ruby-ca script - keys generated with `make` in tests/resource - keys generated with helper script from pyOpenSSL - none of them work for me I am using <strong>riak_2 0 0beta1-1_amd64 deb</strong>
Thanks for the enthusiastic testing! The branch you pulled is an unreviewed work in progress and I have added some updates today I would try again with both the very latest 2 0 0 beta and the changes made to this branch There are some test certs in `riak/tests/resources` which would be useful to get started testing your configuration You will need to name your <strong>cacert</strong> parameter now too since several other options have been added The basic setup looks pretty good Try the latest and let me know how it works for you
How do I generate a histogram from a list of values using matplotlib? so I have been trying to plot a histogram using python with mathplotlib So I have got two datasets basically the heights of a sample of men and women as a list in python imported off a csv file The code that I am using: ````import csv import numpy as np from matplotlib import pyplot as plt men=[] women=[] with open('women csv' 'r') as f: r1=csv reader(f delimiter=' ') for row in r1: women+=[row[0]] with open('men csv' 'r') as f: r2=csv reader(f delimiter=' ') for row in r2: men+=[row[0]] fig = plt figure() ax = fig add_subplot(111) numBins = 20 ax hist(men numBins color='blue' alpha=0 8) ax hist(women numBins color='red' alpha=0 8) plt show() ```` and the error that I get: ````Traceback (most recent call last): File "//MEME/Users/Meme/Miniconda3/Lib/idlelib/test py" line 22 in <module&gt; ax hist(men numBins color='blue' alpha=0 8) File "\\MEME\Users\Meme\Miniconda3\lib\site-packages\matplotlib\__init__ py" line 1811 in inner return func(ax *args **kwargs) File "\\MEME\Users\Meme\Miniconda3\lib\site-packages\matplotlib\axes\_axes py" line 5983 in hist raise ValueError("color kwarg must have one color per dataset") ValueError: color kwarg must have one color per dataset ````
NOTE:assume your files contain multiple lines (comma separated) and the first entry in each line is the height The bug is when you append "data" into the `women` and `men` list `row[0]` is actually a string Hence matplotlib is confused I suggest you run this code before plotting (python 2): ````import csv import numpy as np from matplotlib import pyplot as plt men=[] women=[] import pdb; with open('women csv' 'r') as f: r1=csv reader(f delimiter=' ') for row in r1: women+=[(row[0])] with open('men csv' 'r') as f: r2=csv reader(f delimiter=' ') for row in r2: men+=[(row[0])] fig = plt figure() ax = fig add_subplot(111) print men print women #numBins = 20 #ax hist(men numBins color='blue' alpha=0 8) #ax hist(women numBins color='red' alpha=0 8) #plt show() ```` A sample output will be ````['1' '3' '3'] ['2' '3' '1'] ```` So in the loops you just do a conversion from string into float or integers e g `women = [float(row[0])]` and `men = [float(row[0])]`
PEP 424 __length_hint__() - Is there a way to do the same for generators or zips? Just came across this awesome `__length_hint__()` method for iterators from PEP 424 (<a href="https://www python org/dev/peps/pep-0424/" rel="nofollow">https://www python org/dev/peps/pep-0424/</a>) Wow! A way to get the iterator length without exhausting the iterator My questions: - Is there a simple explanation how does this magic work? I am just curious - Are there limitations and cases where it would not work? ("hint" just sounds a bit suspicious) - Is there a way to get the hint for zips and generators as well? Or is it something fundamental only to iterators? <strong>Edit:</strong> BY THE WAY I see that the `__length__hint__()` counts from current position to the end i e partially consumed iterator will report the remaining length Interesting
The purpose of this is basically just to facilitate more performant allocation of memory in Cython/C code For example imagine that a Cython module exposes a function that takes an iterable of custom `MyNetworkConnection()` objects and internally needs to create and allocate memory for data structures to represent them in the Cython/C code If we can get a rough estimate of the number of items in the iterator we can allocate a large enough slab of memory in one operation to accommodate all of them with minimal resizing If `__len__()` is implemented we know the exact length and can use that for memory allocation But often times we will not actually know the exact length so the estimate helps us improve performance by giving us a "ballpark figure" It is also surely useful in pure-Python code as well for example maybe a user-facing completion time estimate for an operation? For question 2 well it is a hint so you cannot rely on it to be exact You must still account for allocating new memory if the hint is too low or cleaning up if the hint is too high I am not personally aware of other limitations or potential problems For question 3 I see no reason why it would not work for Generators since a Generator <them>is an Iterator</them>: ````&gt;&gt;&gt; import collections &gt;&gt;&gt; def my_generator(): yield &gt;&gt;&gt; gen = my_generator() &gt;&gt;&gt; isinstance(gen collections Iterator) True ````
MultiIndex pivot table pandas python ````import pandas as pd data = pd read_excel(' /data xlsx') ```` the content looks like this: ````Out[57]: Block Concentration Name Replicate value 0 1 100 GlcNAc2 1 321 1 1 100 GlcNAc2 2 139 2 1 100 GlcNAc2 3 202 3 1 33 GlcNAc2 1 86 4 1 33 GlcNAc2 2 194 5 1 33 GlcNAc2 3 452 6 1 10 GlcNAc2 1 140 7 1 10 GlcNAc2 2 285 ```` ````1742 24 0 Print buffer 1 -9968 1743 24 0 Print buffer 2 -4526 1744 24 0 Print buffer 3 14246 ```` [1752 rows x 5 columns] Pivot table looks like this (only a part of the large table): ```` newdata = data pivot_table(index=["Block" "Concentration"] columns=["Name" "Replicate"] values="value") ```` <a href="http://i stack imgur com/19nyA png" rel="nofollow"><img src="http://i stack imgur com/19nyA png" alt="enter image description here"></a> <strong>my Questions:</strong> how do i fill the '0' concentration of 'GlcNAc2' and 'Man5GIcNAc2' with the 'print buffer' values? <strong>desired output:</strong> <a href="http://i stack imgur com/SCD3g png" rel="nofollow"><img src="http://i stack imgur com/SCD3g png" alt="enter image description here"></a> i have been searching online and have not really found anything similar I have not even found a way to point to the 'print buffer' values from the 'Name' column from the MultiIndex/advanced indexing chapters it says to use ````df xs('one' level='second') ```` but it does not work in my case it does not work with pivot table i am not sure why i am confused Is a pivot table multiindex??
If I understand correctly you want to duplicate the values with `Name == Print buffer` to columns with `Name == 'GlcNAc2'` and `'Man5GIcNAc2'` and `concentration = 0` A way of doing this is to duplicate the rows in the original dataset : ````selection = data[data["Name"] == "Print buffer"]' selection loc[: "Name"] = "GlcNAc2" data = pd concat([data selection]) selection loc[: "Name"] = "Man5GIcNAc2" data = pd concat([data selection]) ```` And then apply the pivot_table Remark : I am not sure that I understand your question I am confused by the fact that in your pictures the values `Block == 1` change from the first picture to the second Is it just a mistake or was that the core of your problem?
How many proposals have failed so far?
several
Optimizing removing duplicates in large files in Python I have one very large text file(27GB) that I am attempting to make smaller by removing lines that are duplicated in a second database that has several files of a more reasonable size(500MB-2GB) I have some functional code what I am wondering is is there any way I can optimize this code to run faster human clock time? At the moment on a small test run with a 1 5GB input and 500MB filter this takes 75~ seconds to complete I have gone through many iterations of this idea this one is currently best for time if anyone has ideas for making a better logical structure for the filter I would love to hear it past attempts that have all been worse than this one: Loading the filter into a set and cycling through the input searching for duplicates(about half as fast as this) loading the input into a set and running the filter through a difference_update(almost as fast as this but also doing the reverse of what I wanted) and loading both input and filter into sets in chunks and doing set differences(that was a horrible horrible idea that would work(maybe?) if my filters were smaller so I did not have to split them too ) So those are all the things I have tried All of these processes max out on CPU and my final version runs at about 25-50% disk I/O filter and output are on one physical disk input is on another I am running a dual core and have no idea if this particular script can be threaded never done any multithreading before so if that is a possibility I would love to be pointed in the right direction Information about the data! As said earlier the input is many times larger than the filter I am expecting a very small percentage of duplication The data is in lines all of which are under 20 ASCII characters long The files are all sorted I have already changed the order of the three logical statements based on the expectation that unique input lines will be the majority of the lines then unique filter then duplicates which on the 'best' case of having no duplicates at all saved me about 10% time Any suggestions? ````def sortedfilter(input filter output): file_input = open(input 'r') file_filter = open(filter 'r') file_output = open(output 'w') inline = file_input next() filterline = file_filter next() try: while inline and filterline: if inline < filterline: file_output write(inline) inline = file_input next() continue if inline &gt; filterline: filterline = file_filter next() continue if inline == filterline: filterline = file_filter next() inline = file_input next() except StopIteration: file_output writelines(file_input readlines()) finally: file_filter close() file_input close() file_output close() ````
You can do the string comparison operation only once per line by executing `cmp(inline filterline)`: - `-1` means `inline < filterline` - `0` means `inline == filterline` - `+1` means `inline < filterline` This might get you a few extra percent So something like: ```` while inline and filterline: comparison = cmp(inline filterline) if comparison == -1: file_output write(inline) inline = file_input next() continue if comparison == 1: filterline = file_filter next() continue if comparison == 0: filterline = file_filter next() inline = file_input next() ````
Where do I start if I want to customise the WxPython rich text control? Does anyone know of any articles or code samples to get me started customising the WxPython rich text control? I am trying to extend the rich text control to allow me to insert controls (buttons text boxes etc) into the editing area e g instead of just inserting images or formatted text I would like to be able to insert a control such as a button (similar to the output provided by the HTML controls but I need to provide an editable interface) Looking through the documentation for wxpython and wxWidgets it seems there is the infrastructure built into the controls to support this but I cannot find any help or examples to get me started
Download the wxpython demo from their site it should provide you with an in-depth example of a wxRichTextCtrl Without providing any information about your specific customizations there is not much else I can help with
C char array to Python List I have a C function as follows ````int ldv_read( int handle void* msg_p unsigned length ) ```` I need to pass a pointer as msg_p into C code and be able to print the data in Python If I was doing this in C/C++ I would do this as follows ````char buf[ 64 ]; buf[0] = 0x22;//This is needed to prepare for something else buf[1] = 0x0f; buf[2] = 0x61; pldv_read( handle buf sizeof( buf ) ); //iterate buf and print the data ```` How do I do this in Python? This is what I have so far in Python but this seems to be crashing if my C code try to write into the buf I am working on Win7 ````from ctypes import* ldv_open = windll wldv32 ldv_open ldv_open restype = c_int ldv_open argtypes = [c_char_p] deviceName = ('LDV/\\\\ \Lonusb8-4') handle = ldv_open(deviceName) buf = c_char * 1024 # <----clearly this is not a list do not know how to create a char list in Python ldv_read = windll wldv32 ldv_read ldv_read restype = c_int ldv_read argtypes = [c_int c_void_p c_uint] res = ldv_read( handle id(buf) len(buf) ) #how do I print my buf here? ````
Use <a href="https://docs python org/2/library/ctypes html#ctypes create_string_buffer" rel="nofollow">create_string_buffer</a>: ````buf = create_string_buffer("\x22\x0F\x61" 64) ldv_read = windll wldv32 ldv_read ldv_read restype = c_int ldv_read argtypes = [c_int c_void_p c_uint] res = ldv_read( handle buf len(buf) ) print(buf raw) ```` The reason it is crashing is that `id` returns the memory address <them>of the internal PyObject that holds the string</them>
In which year did Poland declassify most of its Warsaw Pact-era archives?
2005
How do I avoid "record alredy exists" form validation error using ModelForms in Django 1 6? Following the <a href="https://docs djangoproject com/en/1 6/topics/forms/modelforms/" rel="nofollow">ModelForm</a> docs and using this model: ````class ShippingLabel(models Model): """Record what shipping lables were printed list""" class Meta: db_table = 'shipping_labels' ordering = ('client' ) verbose_name = _('shipping label') verbose_name_plural = _('shipping labels') LAYOUT_LASER_2x2 = "1" LAYOUT_TICKET = "2" LAYOUT_LASER_1x1 = "3" LAYOUT_CHOICES = ( ( LAYOUT_LASER_1x1 _("Laser (1x1 sheet)") ) ( LAYOUT_LASER_2x2 _("Laser (2x2 sheet)") ) ( LAYOUT_TICKET _("Ticket (3-inch wide)") ) ) client = models ForeignKey(Company blank=False null=False unique=True help_text=_("Which Client to ship to?") verbose_name=_("client") ) store = models ForeignKey(Store blank=False null=False help_text=_("What store info should be used? (address logo phone etc)") verbose_name=_("store") ) packages = models CharField(_("Packages") max_length=30 blank=False null=False help_text=_("Total number of packages One label printed per package ") ) preprinted_form = models BooleanField(_("Pre-Printed Form") default=False help_text=_("Are you using pre-printed shipping label stickers?") ) layout = models CharField(_("Record Type") max_length=10 blank=False null=False choices=LAYOUT_CHOICES default=LAYOUT_LASER_1x1 help_text=_("Print on large labels (4 per Letter page) Laser large labels (1 per page) or ticket printer?") ) added_by = models CharField(_("Added By") max_length=30 blank=True null=True help_text=_("The User that created this order ") ) date_added = models DateTimeField(_('Date added') auto_now_add=True) date_modified = models DateTimeField(_('Date modified') auto_now=True) def get_absolute_url(self): return reverse('shipping:printship' args=[str(self id)]) def __unicode__(self): return unicode(self client) ```` I made this form template following their example (manual_label html): ````{% extends "admin/base_site html" %} {% load i18n %} {% load staticfiles %} {% block extrahead %} {{ block super}} <script src="{{ STATIC_URL }}js/jquery-1 11 1 js"&gt;</script&gt; {% endblock %} {% block content %} <form id="manual_label" method="post" action=""&gt; {% csrf_token %} {% for hidden in form hidden_fields %} {{ hidden }} {% endfor %} <table&gt; {{ form as_table }} </table&gt; <input type="submit" value="generar etiquetas autoadhesivas"/&gt; </form&gt; <p&gt; </p&gt; {% endblock %} ```` My app urls py: ````from django conf urls import patterns url from shipping views import printship pcustomer manual_label urlpatterns = patterns('' url(r'pcust/' pcustomer name='pcustomer') url(r'mlabel/([0-9]+)/$' manual_label name='manual_label') url(r'printlabel/([0-9]+)/$' printship name='printship') ) ```` My view (with lots of diagnostic logging): ````@login_required() def manual_label(request id): logger debug("SHIPPING VIEWS manual_label") if request method == 'POST': logger debug("SHIPPING VIEWS manual_label: POST!") client = get_object_or_404(Company pk=id) labelset = ShippingLabel objects filter(client=client) if len(labelset)&gt;0: # Pre-existing label update it: logger debug("SHIPPING VIEWS manual_label POST: Update a label!") label = labelset[0] form = ShipLabelForm(request POST instance=label) else: # New label: logger debug("SHIPPING VIEWS manual_label POST: Save New label!") form = ShipLabelForm(request POST) if form is_valid(): logger debug("SHIPPING VIEWS manual_label POST: form is valid") label = form save(commit=True) logger debug("SHIPPING VIEWS manual_label POST: label pk: " str(label id) ) logger debug("SHIPPING VIEWS manual_label POST: label client name: " str(label client name) ) logger debug("SHIPPING VIEWS manual_label: post return") return HttpResponseRedirect(reverse('shipping:printship' args=[str(label id)])) else: logger debug("SHIPPING VIEWS manual_label: GET!") client = get_object_or_404(Company pk=id) labelset = ShippingLabel objects filter(client=client) if len(labelset)&gt;0: # Pre-existing label load it: logger debug("SHIPPING VIEWS manual_label: Pre-Existing label load it ") label = labelset[0] form = ShipLabelForm(instance=label) else: # New label: label = ShippingLabel(client=client store=request user employee store added_by=request user get_username()) form = ShipLabelForm(instance=label) logger debug("SHIPPING VIEWS manual_label: get return") return render(request 'shipping/manual_label html' { 'title': you"Creación de etiquetas Manual Envios" 'form': form }) ```` My forms py definition: ````class ShipLabelForm(ModelForm): class Meta: model = ShippingLabel localized_fields = '__all__' fields = '__all__' widgets = { 'added_by': HiddenInput 'id': HiddenInput } ```` I added <strong><them>'id': HiddenInput </them></strong> to try and "force" record ID number to get sent out to the form in the theory that my error occurs because without the ID number Django will validate in "ADD" mode which will certainly trigger the "unique" flag I have on clients The <strong><them>manual_label</them></strong> view is called by a customer selection form passing in the client id The goal is to generate an ADD form if there is currently no shipping label for this client defined - which works And if a shipping label already exists I pre-load the form with its data The idea being I thought the form system would automatically do an UPDATE on the existing record In either case the saved shipping label record is used to generate the shipping labels desired This works in the admin view (using <them>view on site</them>) But I wanted to give the users a simpler system This works fine for <them>ADDing</them> new labels But when I try to <them>EDIT</them> an existing label I get a <strong>form validation error "<them>client already exists</them>"</strong> It seemed like such an easy thing to do So what am I missing tor doing wrong? As always thanks in advance
You should be using the `instance` argument when initializing the form both in the POST and GET blocks
Can Python Print Bits From what I can tell the random function is returning bits So why is type(key) giving me "string"? And if it is a string or if its bits how come I cannot print it out? If I print it out it gives nonesense characters that the computer cannot read ````def random(size=16): return open("/dev/urandom") read(size) key = random() print type(key) ````
In Python a stream of bytes (or bits) is represented as a string The nonsense characters that are printed out are a result of the fact that not all combinations of bits map to valid characters in the ASCII encoding: <a href="http://en wikipedia org/wiki/ASCII" rel="nofollow">http://en wikipedia org/wiki/ASCII</a> If you want to see the random bits as 1s and 0s you can convert each character to a number using `ord` and then format the number as binary: ````s = random() print "" join(map("{0:08b}" format map(ord list(s)))) # 8 bits per byte ```` If you are trying to generate random numbers why not use the <a href="https://docs python org/2/library/random html" rel="nofollow">random module</a> instead?
Unable to understand recursions and caching from Fibonacci code I am trying to understand recursions and caching much better and still I am making interesting progress(I am a bit slow at times) I am having small problems understanding this code: ````# Fibonacci recursive with result storage class FibonacciStorage: _storage = { 0:1 1:1 } @staticmethod def _fib(number): try: # is this already calculated return FibonacciStorage _storage[number] #searches dict and if value exists then return it except KeyError: result = FibonacciStorage _fib(number-1) FibonacciStorage _fib(number-2) #this is the actual Fibonacci Formula FibonacciStorage _storage[number] = result #adds result to dictionary #print FibonacciStorage _storage #this shows the storage list growing with each iteration return result @staticmethod def fib(number): #first function it has two asserts to basically make sure number is whole/positive and if its okay passes it to _fib(where the real work is done) # only do the assert statements once assert(isinstance(number int)) "Needs a whole number" assert(number&gt;0) "Needs a positive whole number" return FibonacciStorage _fib(number) # use a more readable name getFib = FibonacciStorage fib print getFib(50) ```` I found this code on the net and tried to comment each line to understand what it is actually doing I do not understand how this is a recursion it does loop through the code until the correct result is given but I do not see how its calling itself I thought it was this line at first: `result = FibonacciStorage _fib(number-1) FibonacciStorage _fib(number-2)` but I am confused because my `print FibonacciStorage _storage` line shows the storage cache growing and growing yet the line below it is a return function I suspect I do not understand how `return result` is actually somehow triggering the recursion again I am also not sure how the storage dictionary is making this program go so fast My simple recursions of the fib sequence take a long time(even when I save the data) but in this case if you do a `print getFib(200)` its instant How is the caching making it so fast? So to sum up two questions: 1) How is the recursion actually being triggered? If my print statement is being accessed on each loop? 2) How is caching speeding this up over other fib sequences? Is the class structure or @staticmethod making a difference? For example this seems instant while the ones on <a href="http://en literateprograms org/Fibonacci_numbers_(Python" rel="nofollow">http://en literateprograms org/Fibonacci_numbers_(Python</a>) have a slight delay 3) Maybe also out of intrest can a fibnocci type algo scale(split up and run in parallel) just out of intrest or are they limited to one process? Any insight would be helpful
(1) The recursive call is on this line: ````result = FibonacciStorage _fib(number-1) FibonacciStorage _fib(number-2) // here ^ and here ^ ```` You are right this is "the actual Fibonacci formula" which is recursive by definition (2) Caching is speeding it up immensely What is making a difference is the persistent object `_storage` which is saving you a <them>spectacular</them> amount of duplicate work Consider: ```` fib(4) / \ fib(3) fib(2) / \ / \ fib(2) fib(1) fib(1) fib(0) / \ fib(1) fib(0) ```` This is just `fib(4)` and you can already see the redundancy By simply caching the integer values of `fib(3)` and `fib(4)` you will reduce the number of calculations required for `fib(5)` from 7 to 1 And the savings only grow as you go higher
Django REST API to expose images I have a django app and I want to expose the model images such that when I request `/image/school_id/400` it will return the image of school with id `school_id` cropped and resized to a box 400x400 px Here is what I tried ````@api_view(['GET' 'POST']) def image_view(request school_id size): image = School objects get(school__pk=school_id) image resized_img = image #Handle resizing here return Response(resized_img content_type='*/*') ```` and all am getting is an error `'utf8' codec cannot decode byte 0xff in position 0: invalid start byte` How do i return the image? Am using Django-rest-framework <a href="http://www django-rest-framework org/api-guide/renderers#advanced-renderer-usage" rel="nofollow">http://www django-rest-framework org/api-guide/renderers#advanced-renderer-usage</a>
You are trying to return the raw image data and have Django REST Framework render the response As the response should not be different based on the chosen format you should be using a raw HttpResponse object ````return HttpResponse(resized_img content_type="image/png") ```` Note that the `content_type` should reflect the content type of the returned response which should match the content type of the image that is being resized <hr> The error that you are getting is because the `Renderer` classes are expecting text-based responses not image data Django REST Framework will not apply the custom renderers to `HttpResponse` classes only to Django REST Framework `Response` classes
Python: Simple WebServer not accessible from other interface than loopback? I have a simple question (well at lease I hope it is simple) I have downloaded a python script which is actually a simple webserver After I type into the browser 127 0 0 1:8080 the browser displays a message because the webserver knows how to handle GET requests I have a static IP however if I try my static ip address:8080 it does not work It cannot access the server Is it that ubuntu does not let it or? Anyways here is the code: ````import time import BaseHTTPServer HOST_NAME = 'example net' # !!!REMEMBER TO CHANGE THIS!!! PORT_NUMBER = 8080 # Maybe set this to 9000 class MyHandler(BaseHTTPServer BaseHTTPRequestHandler): def do_HEAD(s): s send_response(200) s send_header("Content-type" "text/html") s end_headers() def do_GET(s): """Respond to a GET request """ s send_response(200) s send_header("Content-type" "text/html") s end_headers() s wfile write("<html&gt;<head&gt;<title&gt;Title goes here </title&gt;</head&gt;") s wfile write("<body&gt;<p&gt;This is a test </p&gt;") # If someone went to "http://something somewhere net/foo/bar/" # then s path equals "/foo/bar/" s wfile write("<p&gt;You accessed path: %s</p&gt;" % s path) s wfile write("</body&gt;</html&gt;") if __name__ == '__main__': server_class = BaseHTTPServer HTTPServer httpd = server_class((HOST_NAME PORT_NUMBER) MyHandler) print time asctime() "Server Starts - %s:%s" % (HOST_NAME PORT_NUMBER) try: httpd serve_forever() except KeyboardInterrupt: pass httpd server_close() print time asctime() "Server Stops - %s:%s" % (HOST_NAME PORT_NUMBER) ````
BaseHTTPServer inherits from SocketServer TCPServer Let us look at its constructor: ````class TCPServer(BaseServer): def __init__(self server_address RequestHandlerClass bind_and_activate=True): BaseServer __init__(self server_address RequestHandlerClass) self socket = socket socket(self address_family self socket_type) if bind_and_activate: try: self server_bind() self server_activate() except: self server_close() raise ```` Ok so now let us look at this server_bind() method: ````def server_bind(self): if self allow_reuse_address: self socket setsockopt(socket SOL_SOCKET socket SO_REUSEADDR 1) self socket bind(self server_address) self server_address = self socket getsockname() ```` So you have bound the underlying socket of your HTTP server to the host 'example net' on port 8080 That means that your server is not bound on IP address my static ip address Try to put instead: HOST_NAME = 'my static ip address'
How would I use a attribute or a element that will split my data from adding with each other ````import quadratic ranges = int(input("what is the range")) for a in range (0 ranges): x= int (input ("what is x")) y= quadratic get_y_value (x) print (y) ```` I am importing a quadratic equation how would I be able to store the y values without adding this y value together Also I am not that confident with for loops and my teacher wants me to use for loops After storing the y values I want to display these values in a table of values ```` import quadratic temp=int mylist= [] maxranges = int(input("how high do you want to go")) minranges = int (input("how low do you want to go")) #note that you set the minimum threshold and that if you do enter a value under that low threshold it will be a incorrect response if minranges&gt;maxranges: temp=maxranges maxranges=minranges minranges = temp print (maxranges) print (minranges) for a in range (minranges maxranges): x= int (input ("what is x")) y= quadratic get_y_value (x) print (y) mylist append((x y)) print ("it is now in a chart have a look:" mylist) ```` *revised copy with the help of the mvps
You can store values in a list First create a list ````mylist = [] ```` Adding two values to the list ````y = 3 mylist append(y) y = 6 mylist append(y) ```` Printing the list ````print mylist [3 6] ````
Calculating correlations between every item in a list I am trying to calculate the Pearson correlation correlation between every item in my list I am trying to get the correlations between data[0] and data[1] data[0] and data[2] and data[1] and data[2] ````import scipy from scipy import stats data = [[1 2 4] [9 5 1] [8 3 3]] def pearson(x y): series1 = data[x] series2 = data[y] if x != y: return scipy stats pearsonr(series1 series2) h = [pearson(x y) for x y in range(0 len(data))] ```` This returns the error `TypeError: 'int' object is not iterable` on `h` Could someone please explain the error here? Thanks
<a href="http://docs python org/2/library/functions html#range" rel="nofollow">range</a> will return you a list of int values while you are trying to use it like it returning you a tuple Try <a href="http://docs python org/2/library/itertools html#itertools combinations" rel="nofollow">itertools combinations</a> instead: ````import scipy from scipy import stats from itertools import combinations data = [[1 2 4] [9 5 1] [8 3 3]] def pearson(x y): series1 = data[x] series2 = data[y] if x != y: return scipy stats pearsonr(series1 series2) h = [pearson(x y) for x y in combinations(len(data) 2)] ```` Or as @Marius suggested: ````h = [stats pearsonr(data[x] data[y]) for x y in combinations(len(data) 2)] ````
What is another name to reference the solo-color white LED method?
null
Who came to Great Britain in the 500's?
null
What set of skills is reliant on procedural memory?
motor skills
IndexError: too many indices Numpy Array with 1 row and 2 columns When I try to get just the first element of an array like this ````import numpy a = numpy array([1 2]) a[: 0] ```` I get this error ````--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-3-ed371621c46c&gt; in <module&gt;() ---> 1 a[: 0] IndexError: too many indices ```` I would like to find a way to do this while still using slicing because the full code opens and reads many different files using `numpy loadtxt()` all having two columns which vary from 1 to some N
Your array `a = numpy array([1 2])` only has <them>one</them> dimension: its shape is `(2 )` However your slice `a[: 0]` specifies selections for <them>two</them> dimensions This causes NumPy to raise the error To get the first element from `a` you only need to write `a[0]` (a selection for only one dimension is being made here) <hr> Looking at your <a href="http://stackoverflow com/questions/29191240/else-statement-does-not-return-to-loop">other question</a> if you want to ensure that the syntax `a[: 0]` always works you could ensure that `a` always has two dimensions When loading an array with `np loadtxt` use the `ndmin` parameter e g : ````np loadtxt(F skiprows=0 ndmin=2) ````
Override clean_email() method in Django-allauth How can i override the default `clean_email()` method in `allauth account forms BaseSignupForm` I tried the following in Forms py: ````from allauth account forms import BaseSignupForm class Extended_BaseSignupForm(BaseSignupForm): def clean_email(self): data = self cleaned_data['email'] if "@gmail com" not in data: # any check you need raise forms ValidationError("Must be a gmail address") if app_settings UNIQUE_EMAIL: if data and email_address_exists(data): raise forms ValidationError \ (_("A user is registered with this e-mail address ")) return data ```` The purpose of overriding is to prevent users from registering with disposable email IDs
Basically you need to override the URL to pass your form class to the view as keyword argument <a href="http://blog yourlabs org/post/19777151073/how-to-override-a-view-from-an-external-django-app" rel="nofollow">This article demonstrates how to override a form in an external view</a>
pandas value_counts for NA <a href="http://pandas pydata org/pandas-docs/stable/generated/pandas Series value_counts html" rel="nofollow">`pandas value_counts`</a> works for numeric arrays with `None`: ````&gt; s = pd Series([1 2 1 None]) &gt; vc = s value_counts(dropna=False) &gt; vc 1 0 2 2 0 1 NaN 1 dtype: int64 &gt; vc index Float64Index([1 0 2 0 nan] dtype='float64') &gt; vc[1] vc[float('NaN')] 2 1 ```` but not for strings: ````&gt; s = pd Series(['1' '2' '1' None]) &gt; vc = s value_counts(dropna=False) &gt; vc 1 2 2 1 NaN 1 dtype: int64 &gt; vc index Index([you'1' you'2' nan] dtype='object') &gt; [type(o) for o in vc index] [<type 'str'&gt; <type 'str'&gt; <type 'float'&gt;] ```` How come there is a `float` here?! ````&gt; vc['1'] 2 &gt; vc[float('NaN')] TypeError: cannot do label indexing on <class 'pandas indexes base Index'&gt; with these indexers [nan] of <type 'float'&gt; ```` How do I access counts for the `None` in `s`?
I was also surprised to see that `cv[np nan]` does not work but this does: `vc loc[np nan]`
Cannot escape a while loop Python 2 7 For some reason i cannot escape while loop i tried debugging it and looks like for loop is untouched and i do not understand why (it is fraction of mine tictactoe game code) ````users_main = [] computers_main = [] while True: computers_storage = [] users_storage = [] if 0==0: condition = True while condition: guess_y = int(raw_input('Enter coordinate y:')) -1 guess_x = int(raw_input('Enter coordinate x:')) -1 users_storage append(guess_y) users_storage append(guess_x) users_main append(users_storage) for a in computers_main: if a == users_storage: del users_storage[-2] del users_main[-1] condition = True break else: condition = False break break ````
````if 0 == 0 ```` is never going to be untrue ````while True: ```` While <them>what</them> is true?
How to sort a list of objects in Python based on an attribute of the objects? I have got a list of Python objects that I would like to sort by an attribute of the objects themselves The list looks like: ````&gt;&gt;&gt; ut [<Tag: 128&gt; <Tag: 2008&gt; <Tag: <&gt; <Tag: actionscript&gt; <Tag: addresses&gt; <Tag: aes&gt; <Tag: ajax&gt; ] ```` Each object has a count: ````&gt;&gt;&gt; ut[1] count 1L ```` I need to sort the list by number of counts descending I have seen several methods for this but I am looking for best practice in Python
````# To sort the list in place ut sort(key=lambda x: x count reverse=True) # To return a new list use the sorted() built-in function newlist = sorted(ut key=lambda x: x count reverse=True) ```` More on <a href="http://wiki python org/moin/HowTo/Sorting#Sortingbykeys">sorting by keys &raquo;</a>
Python Dictionary calls Dictionary but TypeError: string indices must be integers I would like to call another dictionary from the result of calling a dictionary However there is an error ````&gt;&gt;&gt; dict1 = {1:'apple' 2:'mango' 3:'pear'} &gt;&gt;&gt; dict2 = {'apple': 'jason' 'mango': 'mary' 'pear':'susan'} &gt;&gt;&gt; print(dict1[1]['apple']) Traceback (most recent call last): File "<stdin&gt;" line 1 in <module&gt; TypeError: string indices must be integers ```` The desired output is: `jason`
You need to pass the return value of the first lookup into a lookup for the second: ````dict2[dict1[1]] ```` `dict1` holds strings not the `dict2` dictionary so just pass that resulting string <them>to</them> `dict2` when looking up: ````&gt;&gt;&gt; dict1 = {1:'apple' 2:'mango' 3:'pear'} &gt;&gt;&gt; dict2 = {'apple': 'jason' 'mango': 'mary' 'pear':'susan'} &gt;&gt;&gt; dict1[1] 'apple' &gt;&gt;&gt; dict2['apple'] 'jason' &gt;&gt;&gt; dict2[dict1[1]] 'jason' ````
python program that prints number of characters words and lines in a file I am new to programming in Python and wanted help writing a python program that prints number of characters words and lines in a file For example say the name of the file is time txt
You have to learn about work with files in python <a href="https://docs python org/2/tutorial/inputoutput html" rel="nofollow">https://docs python org/2/tutorial/inputoutput html</a> - python v 2 * <a href="https://docs python org/3/tutorial/inputoutput html" rel="nofollow">https://docs python org/3/tutorial/inputoutput html</a> - python v 3 * This part of documentation will help you: ````with open('time txt' 'wb') as f: f write('sometext') f write(some_string_variable) with open('time txt' 'rb') as f: s = f getlines() ```` And next time - search info about your problem first - it can be already solved
How to split a string with more than one delimiter in python? I have a string like this = ````str = (((MY (NAME IS) IS) YOUR NAME) ```` I want to split all the values in this string to get a result like this: ````lst = ['(' '(' '(' 'MY' '(' 'NAME' 'IS' ')' 'IS' ')' 'YOUR' 'NAME' ')'] ```` Is it possible to split the string like this with more than one delimiter?
You can use regex: ````&gt;&gt;&gt; import re &gt;&gt;&gt; s = '(((MY (NAME IS) IS) YOUR NAME)' &gt;&gt;&gt; re findall(r'[()]|[a-zA-Z]+' s) ['(' '(' '(' 'MY' '(' 'NAME' 'IS' ')' 'IS' ')' 'YOUR' 'NAME' ')'] ```` A non-regex solution using <a href="https://docs python org/2/library/itertools html#itertools groupby" rel="nofollow">`itertools groupby`</a>: ````&gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; def solve(s): for k g in groupby(s str isalpha): if k: yield '' join(g) else: for x in g: if not x isspace(): yield x &gt;&gt;&gt; list(solve(s)) ['(' '(' '(' 'MY' '(' 'NAME' 'IS' ')' 'IS' ')' 'YOUR' 'NAME' ')'] ````
£ Sign on python SQLAlchemy query I am trying to inject into a query a string in the following way: ````value = '£' query = """select * from table where condition = '{0}';""" format(value) ```` the problem is the result of this formatting is: <blockquote> select * from table where condition = '\xc2\xa3'; </blockquote> Since I will use this query with sqlalchemy I need the encoded characers to appear as the actual pund sign Any ideas on how I can makes this query look like this?: <blockquote> select * from table where condition = '£'; </blockquote> I am using postgres 3 5 and python 2 7 6 Also if I try the following: ````'\xc2\xa3' decode('utf-8') ```` the result is: <blockquote> you'\xa3' </blockquote>
The Unicode for a pound sign is 163 (decimal) or A3 in hex so the following should work ````print you"\xA3" ```` Oirigin answer: <a href="http://stackoverflow com/questions/705434/what-encoding-do-i-need-to-display-a-gbp-sign-pound-sign-using-python-on-cygwi">What encoding do I need to display a GBP sign (pound sign) using python on cygwin in Windows XP?</a>
How do I turn off email notifications when transferring ownership? I am setting up an api and need to change the ownership of some files in my drive from my service account to my non-service account How do I turn off the email notifications? I have tried via both Python <a href="https://developers google com/drive/v2/reference/permissions/insert" rel="nofollow">as well as via the docs (at the bottom of the page)</a> The emails are getting really annoying ````new_permission = {'value': 'me@example com' 'type': 'user' 'role': 'owner' 'sendNotificationEmails':'false'} self service permissions() insert(fileId=self doc['copied']['id'] body=new_permission sendNotificationEmails='false') execute() ````
As @Grant mentions in the comment use the boolean `false` rather than the string `'false'` Since you are changing the owner of a documentation sendNotificationEmails is ignored as <a href="https://developers google com/drive/v2/reference/permissions/insert" rel="nofollow">per the documentation</a>: <blockquote> Whether to send notification emails when sharing to users or groups This parameter is ignored and an email is sent if the `role` is `owner` (Default: `true`) </blockquote>
Google Drive API List Folders GET I am trying to query Google Drive for a certain file to find its url Here is my code The only thing I changed was my API key is substituted with AAAAAAAAAA ```` queryString = urllib quote_plus("title = \'" filename "\'") parameters = {'key':'{AAAAAAAAAA}' 'q': queryString} inserted_file = requests get('https://www googleapis com/drive/v2/files' params = parameters) print (inserted_file url) print inserted_file ```` when I print inserted_file it returns error 400 What am I doing wrong?
<a href="https://developers google com/drive/v3/web/handle-errors#400_bad_request" rel="nofollow">400 error</a> response means the `value` supplied is invalid or the combination of provided fields is invalid Its user error This can mean that a required field or parameter has not been provided It might gives you `API key not valid` or `Bad request` message/ ````"message": "API key not valid Please pass a valid API key " "message": "Bad Request" ```` It is recommended to generate/use valid credentials There is a documentation how to get credentials/ steps to run sample project here: <a href="https://developers google com/drive/v3/web/quickstart/python#top_of_page" rel="nofollow">https://developers google com/drive/v3/web/quickstart/python#top_of_page</a>
upgrading python in ubuntu Currently I have a working site on Ubuntu 10 04 python 2 6 5 Django 1 3 virtualenv and mod_wsgi I also have nginx serving the static files but I am not sure that fits into this equation I set this up over a year ago and really only learned enough to get it going so I do not remember the exact steps I took to get it going initially I have a need to start using python 2 7 but I am not exactly sure the best way to go about that From what I have read it looks like I need to re-install mod_wsgi specifically for 2 7 I believe the steps to accomplish this are something like the following: - uninstall mod_wsgi - insatll python 2 7 (I believe this can live alongside 2 6?) - re-install mod_wsgi specifically for python 2 7 - create a new virtualenv using 2 7 and re-install requirements I am also looking at my django wsgi file that I had setup that apache points to (in my project): ````import os sys import site wsgi_dir = os path abspath(os path join(os path dirname(__file__))) project_dir = os path dirname(wsgi_dir) root_dir = os path join(project_dir ' ') site addsitedir(os path join(root_dir 'env/lib/python2 6/site-packages')) sys path append(project_dir) os environ['DJANGO_SETTINGS_MODULE'] = 'settings' import django core handlers wsgi application = django core handlers wsgi WSGIHandler() ```` And I do not see anywhere that I specifically call out the python binary to use so I think I need to add something in there for that So my question is: What are the steps I need to take to upgrade my setup to python 2 7?
The following two links may be of some help: - <a href="https://docs djangoproject com/en/dev/howto/deployment/wsgi/modwsgi/" rel="nofollow">How to use Django with Apache and mod_wsgi</a> especially the section "Using a virtualenv" - a similar question: <a href="http://stackoverflow com/questions/3462102/django-virtualenv-deployment-configuration">Django virtualenv deployment configuration</a>
Python Enclosing Words With Quotes In A String For Python I am opening a csv file that appears like: ```` jamie london uk 600087 matt paris fr 80092 john newyork ny 80071 ```` How do I enclose the words with quotes in the csv file so it appears like: ```` "jamie" "london" "uk" "600087" etc ```` What I have right now is just the basic stuff: ```` filemame = "data csv" file = open(filename "r") ```` Not sure what I would do next
If you are just trying to convert the file use the `QUOTE_ALL` constant from the <a href="https://docs python org/2/library/csv html#csv QUOTE_ALL" rel="nofollow">`csv` module</a> like this: ````import csv with open('data csv') as input open('out csv' 'w') as output: reader = csv reader(input) writer = csv writer(output delimiter=' ' quoting=csv QUOTE_ALL) for line in reader: writer writerow(line) ````
Best method of importing scapy I have used: from scapy all import * in the past however now I am getting conflicts (Queue) within the namespace What Is the best method to import scapy? Methods I have looked into: ````import scapy import scapy all from scapy import all ````
````from scapy all import sr1 IP ICMP ```` Is probably the best way of doing this To import all the layers at once (to test packets against them) use: ````from scapy layers import all ````
What has caused more people of mixed races to the US?
Diverse immigration
Calling script-level Python functions from the Linux command line How can I create functions and software for my Linux server? Let me explain this in a bit more detail So for my Linux server which I access with my SSH client I have made a few Python scripts that work fine but what I really want to do is have these Python scripts active all the time such that I can execute functions I have created in the script (such as "def time(): ") just by typing "time" in to the command line rather than starting up a script with /script-name py and then type "time" Do I need to install my Python files in to the system in some way? I struggled searching Google because I did not fully understand what to search and results that came up were not really related to my request I did find the cmd Python module and learned how to create cmd interpreters however in order for me to access the commands I defined in the cmd interpreter I had to first start the script which as I explained above not what I am looking for How can I make script-level Python functions callable from the Linux command line?
If you are using Python you will still need to fire up the interpreter but you can make that happen automatically Start by making your script executable Run this command in the she will: ````chmod x script-name py ls -l script-name py ```` The output of `ls` should look something like this (note the `x`s in the left-hand column): ````-rwxr-xr-x 1 me me 4 Jan 14 11:02 script-name py ```` Now add an <a href="https://en wikipedia org/wiki/Interpreter_directive" rel="nofollow">interpreter directive</a> line at the top of your script file - this tells the she will to run Python to interpret your script: ````#!/usr/bin/python ```` Then add code at the end of the file that calls your function: ````if __name__ == '__main__': time() ```` The `if` statement checks to see if this is the file that is being executed It means you can still import your module from another Python file without the `time()` function being automatically called if you want Finally you need to put your script in the executable path ````mkdir -p $HOME/bin mv script-name py $HOME/bin/ export PATH=$HOME/bin:$PATH ```` Now you should be able to run `script-name py` and you will see the output of the `time()` function You can rename your file to whatever you like; you can even remove the ` py` extension Additional things you can do: - Use the <a href="https://docs python org/2 7/library/argparse html" rel="nofollow">`argparse` module</a> to add command line arguments e g so you can run `script-name py time` to execute the `time()` function - Put the script in a system-wide path like `/usr/local/bin` or - Add the `export PATH=$HOME/bin:$PATH` line to your <a href="http://superuser com/questions/49289/what-is-the-bashrc-file">` bashrc`</a> so that it happens by default when you log in
Python: Find element in the list which has frequency = 2 Let us say I have a list: Input: ids = [123 456 123] I need to find the element whose frequency is 2 Output: 123 Best way to do this in python?
````from collections import Counter counter = Counter(ids) [k for k v in counter items() if v == 2] ````
python extracting sequences from gene prediction output I have done a gene prediction using SoftBerry and it returns output like this: Predicted protein(s): ````&gt;FGENESH:[mRNA] 1 12 exon (s) 4267 - 6782 1296 bp chain ATGATACGCACTGCGCTTTCACGAGCAGCGGCCATCGTCGCCGCCCGCACCTCCGCCAAG CTCCGCCCTTCCCTCCTCGCTCGATCTCCGCCGTCCAGACTCCTCCACGATGGGATTAAC GCCAACCCAGTTGCTCTTCAGATGATCAACTACGCCGTCTCTCTCGCCAGGTCTCAGAAA &gt;FGENESH: 1 12 exon (s) 4267 - 6782 431 aa chain MIRTALSRAAAIVAARTSAKLRPSLLARSPPSRLLHDGINANPVALQMINYAVSLARSQK SDESYGQAQLVLEQCLSSQPSEGQDLATHNSRAMVLMAMSTLLSERGKLDEAIEKLQKVE ```` etc: an extensive output so manual editing is not trivial I need to fish out the sequences that start with '>FGENESH:[mRNA]' So I try this: ````for line in infile: if line startswith('&gt;FGENESH:[mRNA]'): print(line) outfile write(line) ```` Which gives me only the header lines: ````&gt;FGENESH:[mRNA] 1 12 exon (s) 4267 - 6782 1296 bp chain ```` However I would like the output to look like this: ````&gt;FGENESH:[mRNA] 1 12 exon (s) 4267 - 6782 1296 bp chain ATGATACGCACTGCGCTTTCACGAGCAGCGGCCATCGTCGCCGCCCGCACCTCCGCCAAG CTCCGCCCTTCCCTCCTCGCTCGATCTCCGCCGTCCAGACTCCTCCACGATGGGATTAAC GCCAACCCAGTTGCTCTTCAGATGATCAACTACGCCGTCTCTCTCGCCAGGTCTCAGAAA ```` Could anyone advice me how to obtain that? I would be much obliged - being a novice and all Thank you jd
````flag = False for line in infile: if flag is True: if line startswith('&gt;'): flag = False else: outfile write(line) if line startswith('&gt;FGENESH:[mRNA]'): flag = True outfile write(line) ````
What percentage of human communication occurs through nonverbal facial expressions?
55%
Suppressing scientific notation in pandas? I have a DataFrame in pandas where some of the numbers are expressed in scientific notation (or exponent notation) like this: ```` id value id 1 00 -4 22e-01 value -0 42 1 00e+00 percent -0 72 1 00e-01 played 0 03 -4 35e-02 money -0 22 3 37e-01 other NaN NaN sy -0 03 2 19e-04 sz -0 33 3 83e-01 ```` And the scientific notation makes what should be an easy comparison needlessly difficult I assume it is the 21900 value that is screwing it up for the others I mean 1 0 is encoded ONE! This does not work: ````np set_printoptions(supress=True) ```` And `pandas set_printoptions` does not implement suppress either and I have looked all at `pd describe_options()` in despair and `pd core format set_eng_float_format()` only seems to turn it on for all the other float values with no ability to turn it off
Your data is probably `object` dtype This is a direct copy/paste of your data `read_csv` interprets it as the correct dtype You should normally only have `object` dtype on string-like fields ````In [5]: df = read_csv(StringIO(data) sep='\s+') In [6]: df Out[6]: id value id 1 00 -0 422000 value -0 42 1 000000 percent -0 72 0 100000 played 0 03 -0 043500 money -0 22 0 337000 other NaN NaN sy -0 03 0 000219 sz -0 33 0 383000 ```` check if your dtypes are `object` ````In [7]: df dtypes Out[7]: id float64 value float64 dtype: object ```` This converts this frame to `object` dtype (notice the printing is funny now) ````In [8]: df astype(object) Out[8]: id value id 1 -0 422 value -0 42 1 percent -0 72 0 1 played 0 03 -0 0435 money -0 22 0 337 other NaN NaN sy -0 03 0 000219 sz -0 33 0 383 ```` This is how to convert it back (`astype(float)`) also works here ````In [9]: df astype(object) convert_objects() Out[9]: id value id 1 00 -0 422000 value -0 42 1 000000 percent -0 72 0 100000 played 0 03 -0 043500 money -0 22 0 337000 other NaN NaN sy -0 03 0 000219 sz -0 33 0 383000 ```` This is what an `object` dtype frame would look like ````In [10]: df astype(object) dtypes Out[10]: id object value object dtype: object ````
virtualenv cannot find python2 I am on a mac which comes with python 2 7 installed so I should have the required version At least I believe that is the problem I am getting an error when trying to run `make install` for a project and getting the following error: ````The executable python2 (from --python=python2) does not exist make: *** [bin/python] Error 3 ````
Specify the full path to the Python interpreter (not sure if this is the right path - have not used MacOs): ````mkvirtualenv myenv --python=/Library/Frameworks/Python framework/Versions/2 7/bin/python ```` or smth like: ````--python=`which python` ````
Pandas percentage calculation with groupby operation I have a data frame in pandas which have following format ```` coupon_applied coupon_type dish_id dish_name dish_price 0 Yes Rs 20 off 012 Paneer Biryani 110 dish_quant_bought dish_quantity dish_substitute dish_type 0 50 2 Yes Veg rder_time order_id order_lat year 0 2015-12-05 16:30:04 345 order_1 73 955741 2015 month day time 0 12 Saturday 16:30:04 345000 ```` I want to calculate dish selling rate for a particular time interval dish selling rate = (dish_quant)/(dish_quant_bought) I am doing following ```` df_final[(df_final['time'] &gt; datetime time(16 30)) &amp; (df_final['time'] < datetime time(16 35))] groupby('dish_name') sum()['dish_quantity'] ```` Which gives me following ````dish_name Chicken Biryani 2 Chicken Tikka Masala 2 Mutton Biryani 2 Paneer Biryani 2 ```` But I am unable to divide dish quantity sold by dish quantity bought How to do it? please help
IIUC you can do it very simple: ````df = df_final[(df_final['time'] &gt; datetime time(16 30)) &amp; (df_final['time'] < datetime time(16 35))] groupby('dish_name') sum() df['dish_selling_rate'] = df['dish_quantity'] / df['dish_quant_bought'] print df head(5) ````
How do I port MultiCheckComboBox to PySide? I want the items in a combobox to be checkable I have found a way to do this <a href="https://github com/spanners/pyqt4-examples/blob/master/MultiSelectionExample/" rel="nofollow">here</a> This specific example uses PyQt and since I use PySide it needs some modifications to work The first error I get is about `QStringList` which I replaced with `[]` Then I get the following error: ````Traceback (most recent call last): File "MultiCheckComboBox py" line 401 in data if not value isValid(): AttributeError: 'NoneType' object has no attribute 'isValid' ```` I am not sure what needs to be changed to fix the above error
PyQt4 (by default) returns some values as instances of `QVariant` (although it can be configured to return a native Python type) PySide however always converts to native Python types Your code is assuming that PyQt4 will be using `QVariant` That line of code assumes `value` is a `QVariant` You will need to change it to: ````if value is not None: ```` in this case however this is unlikely to be the only instance of a `QVariant` in this code and the modification you need to make to those will be dependent on the `QVariant` function that the code is trying to call
regex a line from file using python I am trying to regex data from a line in the file and failing I tried to use <a href="http://regexpal com/" rel="nofollow">regexpal</a> but failed there as well The code I came up with is: ````#!/usr/bin/python3 #line to be parsed: # 1 Ni type=1 np=1001 r1=1 0E-05 rnp=-1 35602175 pfile=Ni1 pot #To parse is # 1 Ni Ni1 pot import re f1=open("file str" "r") pattern=r'(\d+)\s+( *)\s+ type=(\d+)*\s pfile=( *)' count=[]; atype=[]; pots=[] for line in f1: match=re search(pattern line) if match: count append(int(match group(1))) atype append((match group(2))) apots append((match group(3))) print(count) ```` Can anyone kindly show what error I am making?
You do not match the dot after the first number and you do not match the other arguments after type= and before pfile= This should work: ````pattern=r'(\d+) \s+( *?)\s+type=(\d+) *\s+pfile=( *?)\s*' ````
Separate mixture of gaussians in Python There is a result of some physical experiment witch is represented as histogram `[i amount_of(i)]` I suppose that result can be estimated by a mixture of 4 6 gaussian functions Is there a package in Python wich gets the histogram at input and returns mean and variance for each gaussian in sum? Original data for example: <img src="http://i stack imgur com/ze2G9 png" alt="enter image description here">
This is a <a href="http://en wikipedia org/wiki/Mixture_model">mixture of gaussians</a> and can be estimated using an <a href="http://en wikipedia org/wiki/Expectation%E2%80%93maximization_algorithm">expectation maximization</a> approach (basically it finds the centers and means of the distribution at the same time as it is estimating how they are mixed together) This is implemented in the <a href="http://www pymix org/pymix/">PyMix</a> package Below I generate an example of a mixture of normals and use PyMix to fit a mixture model to them including figuring out what you are interested in which is the size of subpopulations: ````# requires numpy and PyMix (matplotlib is just for making a histogram) import random import numpy as np from matplotlib import pyplot as plt import mixture random seed(010713) # to make it reproducible # create a mixture of normals: # 1000 from N(0 1) # 2000 from N(6 2) mix = np concatenate([np random normal(0 1 [1000]) np random normal(6 2 [2000])]) # histogram: plt hist(mix bins=20) plt savefig("mixture pdf") ```` All the above code does is generate and plot the mixture It looks like this: <img src="http://i stack imgur com/M337Q png" alt="enter image description here"> Now to actually use PyMix to figure out what the percentages are: ````data = mixture DataSet() data fromArray(mix) # start them off with something arbitrary (probably based on a guess from the figure) n1 = mixture NormalDistribution(-1 1) n2 = mixture NormalDistribution(1 1) m = mixture MixtureModel(2 [0 5 0 5] [n1 n2]) # perform expectation maximization m THEM(data 40 1) print m ```` The output model of this is: ````G = 2 p = 1 pi =[ 0 33307859 0 66692141] compFix = [0 0] Component 0: ProductDist: Normal: [0 0360178848449 1 03018725918] Component 1: ProductDist: Normal: [5 86848468319 2 0158608802] ```` Notice it found the two normals quite correctly (one `N(0 1)` and one `N(6 2)` approximately) It also estimated `pi` which is the fraction in each of the two distributions (you mention in the comments that is what you are most interested in) We had 1000 in the first distribution and 2000 in the second distribution and it gets the division almost <them>exactly</them> right: `[ 0 33307859 0 66692141]` If you want to get this value directly do `m pi` A few notes: - This approach takes a vector of values not a histogram It should be easy to convert your data into a 1D vector (that is turn `[(1 4 2) (2 6 3)]` into `[1 4 1 4 2 6 2 6 2 6]`) - We had to guess the number of gaussian distributions in advance (it will not figure out a mix of 4 if you ask for a mix of 2) - We had to put in some initial estimates for the distributions If you make even remotely reasonable guesses it should converge to the correct estimates
Everytime Celery is restarted all the scheduled tasks are acknowledged Everytime Celery is restarted all the scheduled tasks are acknowledged again And this is leading to a huge time lag to start processing new tasks How can we solve this?
You can simply purge all the tasks before starting Celery again: ````$ celery purge WARNING: This will remove all tasks from queue: celery There is no undo for this operation! (to skip this prompt use the -f option) Are you sure you want to delete all tasks (yes/NO)? ````
JSON list/dictionary parsing from API I have developed a small library and am interested in making it easier on users to retrieve data from the JSON lists/dictionaries that are returned I have created functions that handle the calls using <them>requests</them> Now suppose I call this function and pass in a few parameters: ````precip = precipitation_obs(stid='kfnl' start='201504261800' end='201504271200' units='precip|in') ```` This will return the following JSON: ````{ 'STATION': [ { 'ELEVATION': '5016' 'ID': '192' 'LATITUDE': '40 45' 'LONGITUDE': '-105 01667' 'MNET_ID': '1' 'NAME': 'Fort Collins/Loveland Fort Collins-Loveland ' 'Municipal Airport' 'OBSERVATIONS': { 'count_1': 6 'ob_end_time_1': '2015-04-27T00:55:00Z' 'ob_start_time_1': '2015-04-26T18:55:00Z' 'total_precip_value_1': 0 13 'vids case4': ['39' '51' '40' '52']} 'STATE': 'CO' 'STATUS': 'ACTIVE' 'STID': 'KFNL' 'TIMEZONE': 'US/Mountain'}] 'SUMMARY': { 'METADATA_RESPONSE_TIME': '5 22613525391 ms' 'NUMBER_OF_OBJECTS': 1 'RESPONSE_CODE': 1 'RESPONSE_MESSAGE': 'OK' 'TOTAL_TIME': '57 6429367065 ms'}} ```` Now I want the user to be able to just drill down through the dictionary but STATION is a list and requires me to do the following: ````output = precip['STATION'][0]['OBSERVATIONS']['ob_start_time_1'] print(output) # returns 2015-04-26T18:55:00Z ```` where I have to include the [0] to avoid: ````TypeError: list indices must be integers not str ```` Is there anyway around this? Adding that [0] in there really jacks things up so to say Or even having to specify ['STATION'] every time is a bit of a nuisance Should I use the simpleJSON module to help here? Any tips on making this a bit easier would be great thanks!
<blockquote> Adding that `[0]` in there really jacks things up so to say Or even having to specify `['STATION']` every time is a bit of a nuisance </blockquote> So just store `precip['STATION'][0]` in a variable: ````&gt;&gt;&gt; precip0 = precip['STATION'][0] ```` And now you can use it repeatedly: ````&gt;&gt;&gt; precip0['OBSERVATIONS']['ob_start_time_1'] 2015-04-26T18:55:00Z ```` If you know that the API is always going to return exactly one station and you are never going to want anything other than the data for that station you can put that in your wrapper function: ````def precipitation_obs(stid start end units): # your existing code which assigns something to result return result['STATION'][0] ```` <hr> If you are worried about "efficiency" here do not worry First this is not making a copy of anything it is just making another reference to the same object that already exists—it takes under a microsecond and wastes about 8 bytes In fact it <them>saves</them> you memory because if you are not storing the whole dict just the sub-dict Python can garbage-collect the rest of the structure And more importantly that kind of micro-optimization is not worth worrying about in the first place until (1) your code is working and (2) you know it is a bottleneck <hr> <blockquote> Should I use the simpleJSON module to help here? </blockquote> Why would you think that would help? As <a href="https://pypi python org/pypi/simplejson/" rel="nofollow">its readme says</a>: <blockquote> simplejson is the externally maintained development version of the json library included with Python 2 6 and Python 3 0 but maintains backwards compatibility with Python 2 5 </blockquote> In other words it is either the same code you have already got in the stdlib or an older version of that code Sometimes a <them>different</them> library like <a href="https://pypi python org/pypi/ijson/" rel="nofollow">`ijson`</a> can help—e g if the JSON structures are so big that you cannot parse the whole thing into memory or so complex that it is easier to describe what you want upside-down in SAX style But that is not relevant here
What did wealthy merchants want to put strict limits on?
null
Python / PyGame: Set font render() alpha I know how to set the alpha for a pygame Surface or a pygame image That would be: ````surface set_alpha(alpha) ```` but how to do that for labels created by ````label = font render("I am a label" True [255 255 255]) ```` Does anyone know this? ````label set_alpha(1) ```` did not do anything to it When I blitted it it was just fully colored If you do not know what I mean - feel free to ask :)
When you call font render you are getting a `surface` If you check the <a href="https://www pygame org/docs/ref/font html#pygame font Font" rel="nofollow">documentation</a> it says: "draw text on a new Surface render(text antialias color background=None) -> Surface" The "-> Surface" means it returns a surface So basically your label should work like any image in pygame You could try this to ensure pygame is treating the label like a surface: `label = pygame Surface((label get_width() label get_height()) label)` Also you might have a problem with the surface being locked To unlock it is just `pygame Surface unlock()` and `pygame Surface lock()` to lock UPDATE: I do not know what is wrong your missing some details because it should work ````import pygame pygame init() s = pygame display set_mode((500 500)) font = pygame font SysFont("comicsansms" 20) label = font render("hello" 0 (255 255 255)) label set_alpha(100) while True: s fill((0 0 0)) s blit(label (0 0)) pygame display update() ```` <img src="http://i stack imgur com/WM6Q3 png" alt="enter image description here">
Error occurs while parsing the json file I am trying to parse the json format data to json load() method But it is giving me an error I tried different methods like reading line by line convert into dictionary list and so on but it is not working I also tried the solution mention in the following url <a href="http://stackoverflow com/questions/12451431/loading-and-parsing-a-json-file-in-python">loading-and-parsing-a-json</a> but it give's me the same error ````import json data = [] with open('output txt' 'r') as f: for line in f: data append(json loads(line)) ```` Error: ````ValueError: Extra data: line 1 column 71221 - line 1 column 6783824 (char 71220 - 6783823) ```` <strong>Please find the output txt in the below URL</strong> <P><strong><them><a href="https://drive google com/file/d/0Bx4WhgnRKxwGa21mamJwUFZhX00/view?usp=sharing" rel="nofollow">Content- output txt</a></them></strong>
Your alleged JSON file is not a properly formatted JSON file JSON files must contain exactly one object (a list a mapping a number a string etc) Your file appears to contain a number of JSON objects in sequence but not in the correct format for a list Your program's JSON parser correctly returns an error condition when presented with this non-JSON data Here is a program that will interpret your file: ````import json # Idea and some code stolen from https://gist github com/sampsyo/920215 data = [] with open('output txt') as f: s = f read() decoder = json JSONDecoder() while s strip(): datum index = decoder raw_decode(s) data append(datum) s = s[index:] print len(data) ````
How to override Django-CMS templates settings py ````from ENV import BASE_DIR ENV_VAR # SECURITY WARNING: do not run with debug turned on in production! # False if not in os environ DEBUG = ENV_VAR('DEBUG' default=False) # SECURITY WARNING: keep the secret key used in production secret! # If not found in os environ will raise ImproperlyConfigured error SECRET_KEY = ENV_VAR('SECRET_KEY') SITE_ID = 1 # Application definition INSTALLED_APPS = [ 'djangocms_admin_style' 'django contrib auth' 'django contrib contenttypes' 'django contrib sessions' 'django contrib admin' 'django contrib sites' 'django contrib sitemaps' 'django contrib staticfiles' 'django contrib messages' 'cms' 'menus' 'sekizai' 'treebeard' 'djangocms_text_ckeditor' 'djangocms_style' 'djangocms_column' 'djangocms_file' 'djangocms_googlemap' 'djangocms_inherit' 'djangocms_link' 'djangocms_picture' 'djangocms_teaser' 'djangocms_video' 'reversion' 'config' ] MIDDLEWARE_CLASSES = [ 'cms middleware utils ApphookReloadMiddleware' 'django contrib sessions middleware SessionMiddleware' 'django middleware csrf CsrfViewMiddleware' 'django contrib auth middleware AuthenticationMiddleware' 'django contrib messages middleware MessageMiddleware' 'django middleware locale LocaleMiddleware' 'django middleware common CommonMiddleware' 'django middleware clickjacking XFrameOptionsMiddleware' 'cms middleware user CurrentUserMiddleware' 'cms middleware page CurrentPageMiddleware' 'cms middleware toolbar ToolbarMiddleware' 'cms middleware language LanguageCookieMiddleware' ] ROOT_URLCONF = 'urls' TEMPLATES = [ { 'BACKEND': 'django template backends django DjangoTemplates' 'DIRS': [ BASE_DIR('config/templates') ] 'OPTIONS': { 'context_processors': [ 'django contrib auth context_processors auth' 'django contrib messages context_processors messages' 'django core context_processors i18n' 'django core context_processors debug' 'django core context_processors request' 'django core context_processors media' 'django core context_processors csrf' 'django core context_processors tz' 'sekizai context_processors sekizai' 'django core context_processors static' 'cms context_processors cms_settings' ] 'loaders': [ 'django template loaders filesystem Loader' 'django template loaders app_directories Loader' 'django template loaders eggs Loader' ] } } ] WSGI_APPLICATION = 'config wsgi application' # Database # https://docs djangoproject com/en/1 8/ref/settings/#databases DATABASES = { 'default': ENV_VAR db() } # Password validation # https://docs djangoproject com/en/1 9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django contrib auth password_validation UserAttributeSimilarityValidator' } { 'NAME': 'django contrib auth password_validation MinimumLengthValidator' } { 'NAME': 'django contrib auth password_validation CommonPasswordValidator' } { 'NAME': 'django contrib auth password_validation NumericPasswordValidator' } ] # Internationalization # https://docs djangoproject com/en/1 8/topics/i18n/ LANGUAGE_CODE = 'en' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True MEDIA_ROOT = BASE_DIR('media' default='') MEDIA_URL = '/media/' # Static files (CSS JavaScript Images) # https://docs djangoproject com/en/1 8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR('static') STATICFILES_FINDERS = ( 'django contrib staticfiles finders AppDirectoriesFinder' 'django contrib staticfiles finders FileSystemFinder' ) STATICFILES_STORAGE = 'whitenoise storage CompressedManifestStaticFilesStorage' ```` urls py ````from __future__ import absolute_import print_function unicode_literals from cms sitemaps import CMSSitemap from django conf import settings from django conf urls import include url from django conf urls i18n import i18n_patterns from django contrib import admin admin autodiscover() urlpatterns = [ url(r'^sitemap\ xml$' 'django contrib sitemaps views sitemap' {'sitemaps': {'cmspages': CMSSitemap}}) url(r'^select2/' include('django_select2 urls')) ] urlpatterns = i18n_patterns( '' url(r'^admin/' include(admin site urls)) url(r'^' include('cms urls')) ) ```` DIR Structure ```` |-- apps | |-- __init__ py |-- config | |-- __init__ py | |-- settings | | |-- base py | | |-- configurations | | | |-- DJANGOCMS py | | | |-- DJANGO py | | | |-- ENV py | | | |-- GRAPPELLI py | | | |-- __init__ py | | |-- dev py | | |-- __init__ py | | `-- pro py | |-- templates | | |-- base html | | |-- feature html | | |-- menu html | | |-- page html | |-- wsgi py |-- manage py |-- media |-- requirements | |-- base txt | |-- dev txt | `-- pro txt |-- requirements txt |-- static |-- urls py ```` <a href="http://i stack imgur com/9K8pz png" rel="nofollow"><img src="http://i stack imgur com/9K8pz png" alt="enter image description here"></a> <strong>I am unable to open localhost:8000/ it always redirects me to login page Then I have created a new project and this time kept the default project layout and now this is what I see if I open localhost:8000/</strong> <a href="http://i stack imgur com/X1124 png" rel="nofollow"><img src="http://i stack imgur com/X1124 png" alt="enter image description here"></a> <strong>So if someone can tell me what is wrong ?? How do I use custom templates ???</strong>
First off if it redirects you to the login page that will most likely be because there is not any content yet Based on the question I am assuming this is a new installation with no pages so you would need to login create your pages and then you should get it to load without the admin redirect In terms of overriding templates it works the same as for any django or app template If you want to use a custom template you simply create your own version following the same path as the original but in one of your own template directories For example I have got a directory in my project where I override CMS templates; `/project/myapp/templates/cms/toolbar/plugin html` Which you can see in the CMS app lives in that same template path; <a href="https://github com/divio/django-cms/tree/release/3 3 x/cms/templates/cms/toolbar" rel="nofollow">https://github com/divio/django-cms/tree/release/3 3 x/cms/templates/cms/toolbar</a> If you have got templates that you wish to make available as page templates for the CMS then there is a `CMS_TEMPLATES` setting which you add like so; ````CMS_TEMPLATES = ( ('home html' 'Homepage') ('article html' 'Article') ('blogs/entry_form html' 'Blogs Competition Entry Form') ) ````
What entity governed Portugal until 1976?
Junta de Salvação Nacional
What international prize winning winery is located in North Carolina?
Noni Bacca Winery
Merging 1D and 2D lists in python I am trying to set up data to convert to a numpy array I have three lists Two are one dimensional and one is two dimensional ````a = [1 2 3] b = [4 5 6] c = [ [7 8] [9 10] [11 12] ] ```` I want to end up with this: ````[ [1 4 7 8] [2 5 9 10] [3 6 11 12] ] ```` I have tried using `zip()` but it does not delve into the 2D array
Assuming you do not mind if the use of NumPy in the conversion itself the following should work ````from numpy import array a = array([1 2 3]) b = array([4 5 6]) c = array([[7 8] [9 10] [11 12]]) result = array(list(zip(a b c[: 0] c[: 1]))) ```` Note that `c[: n]` will only work with NumPy arrays not standard Python lists
Python: How to import package root with relative imports I have a large number of names defined in the top-level __init__ py of a python package I would like to use a <them>relative</them> import to import this namespace because I do not necessarily know the package name at runtime (it might even be used as a sub-package of some other package) For example take the following package: ````my_package/ __init__ py a = 1 b = 2 my_module py from import ??? as my_package print(my_package a) ```` How shall I fix the import statement in my_module such that the print statement works correctly? I would also rather avoid `from import a b `; I just want the entire package namespace imported as one variable I have tried `from import __init__ as my_package` but in this case `my_package` is imported as a method-wrapper not a module I have also tried `my_module = __import__(__package__)` which works only in the case that my_package is not a sub-package It seems like there should be a simple answer to this
`__init__ py` is used for names you want to expose as being importable from the top level of your package In this case you are using it for importing names internally i e within your package hence the problem So you should put all the names/definitions to be used internally in your package in another file e g `defs py` and import from there: ````from defs import foo bar baz ```` And make sure to only leave in `__init__ py` the names you want to top-level-expose to the outside world EDIT: to clarify in `__init__ py` you do not need to duplicate the names/definitions simply import them in exactly the same way: ````from defs import foo bar ```` Or ````from defs import * # not recommended of course ```` Then from outside the package names can be imported from packege's top level like this: ````from my_package import foo bar ```` Or ````from path to my_package import foo bar ````