questions
stringlengths
50
48.9k
answers
stringlengths
0
58.3k
How to best perform recursion on a pandas dataframe column I am trying to calculate an index value over a time series within a pandas dataframe. This index depends on the previous row's result to calculate each row after the first iteration. I've attempted to do this recursively, within iteration over the dataframe's rows, but I find that the first two rows of the calculation are correct, but the third and subsequent rows are inaccurate. I think this is because after the initial value, subsquent index calculations are going wrong and then set all other subsequent calculations wrong.What is causing this inaccuracy. Is there a better approach than the one I've taken? A sample of the output looks like this:ticket_cat Sector Year factor Incorrect_index_value correct_index_value prev_rowRevenue LSE Jan 2004 100.00 100.00 Revenue LSE Jan 2005 4.323542894 104.3235 104.3235 100.00Revenue LSE Jan 2006 3.096308080 98.823 107.5537 <--incorrect row Revenue LSE Jan 2007 6.211666 107.476 114.2345 <--incorrect row Revenue LD Jan 2004 100.00 100.0000Revenue LD Jan 2005 3.5218 103.5218 103.5218Revenue LD Jan 2006 2.7417 99.2464 106.3602 <--- incorrect rowRevenue LD Jan 2007 3.3506 104.1353 109.9239 <--- incorrect row The code snippet I have is as follows: stpassrev is the dataframe#insert initial value for indexstpassrev['index_value'] = np.where( (stpassrev['Year'] == 'Jan 2004' ) & (stpassrev['Ticket_cat']=='Revenue'), 100.00,np.nan )#set up initial values for prec_row columnstpassrev['prev_row'] = np.where( #only have relevant row impacted (stpassrev['Year'] == 'Jan 2005' ) & (stpassrev['Ticke_cat']=='Revenue'), 100.00, np.nan )#calculate the index_valuefor i in range(1,len(stpassrev)): stpassrev.loc[i,'passrev'] = np.where( (stpassrev.loc[i,'Ticket_cat']=='Revenue' ) & (pd.isna(stpassrev.loc[i,'factor'])==False), ((100+stpassrev.loc[i,'factor'] ) /stpassrev.loc[i-1,'index_value'])*100, stpassrev.loc[i,'index_value']) stpassrev.loc[i,'prev_row'] = stpassrev.loc[i-1,'index_value']
Based on your updated question, you just need to do this:# assign a new temp_factor with initial values and prep for cumprodstpassrev['temp_factor'] = np.where(stpassrev['factor'].isna(), 1, stpassrev['factor'].add(100).div(100))# calculate the cumprod based on the temp_factor (grouped by Sector) and multiply by 100 for index_valuestpassrev['index_value'] = stpassrev.groupby('Sector')['temp_factor'].cumprod().mul(100)Results: ticket_cat Sector Year factor temp_factor index_value0 Revenue LSE Jan 2004 NaN 1.000000 100.0000001 Revenue LSE Jan 2005 4.323543 1.043235 104.3235432 Revenue LSE Jan 2006 3.096308 1.030963 107.5537213 Revenue LSE Jan 2007 6.211666 1.062117 114.2345994 Revenue LD Jan 2004 NaN 1.000000 100.0000005 Revenue LD Jan 2005 3.521800 1.035218 103.5218006 Revenue LD Jan 2006 2.741700 1.027417 106.3600577 Revenue LD Jan 2007 3.350600 1.033506 109.923757If you need it rounded to 4 digit precision, add .round(4) after the .mul(100):stpassrev['index_value'] = stpassrev.groupby('Sector')['temp_factor'].cumprod().mul(100).round(4) ticket_cat Sector Year factor temp_factor index_value0 Revenue LSE Jan 2004 NaN 1.000000 100.00001 Revenue LSE Jan 2005 4.323543 1.043235 104.32352 Revenue LSE Jan 2006 3.096308 1.030963 107.55373 Revenue LSE Jan 2007 6.211666 1.062117 114.23464 Revenue LD Jan 2004 NaN 1.000000 100.00005 Revenue LD Jan 2005 3.521800 1.035218 103.52186 Revenue LD Jan 2006 2.741700 1.027417 106.36017 Revenue LD Jan 2007 3.350600 1.033506 109.9238
Select rows containing a NaN following a specific value in Pandas I am trying to create a new DataFrame consisting of the rows corresponding to the value 1.0 or NaN in the last column, whereby I only take the Nans under a 1.0 (that is, I'm interested in everything until a 0.0 appears). Timestamp Value Mode 00-00-10 34567 1.0 00-00-20 45425 00-00-30 46773 0.0 00-00.40 64567 00-00-50 25665 1.0 00-00-60 25678 My attempt is:for row in data.itertuples():while data[data.Mode != 0.0]: df2 = df2.append(row)else: #How do I differentiate between a NaN under a 1.0 and a NaN under a 0.0?print (df2)The idea is to save every row until a 0.0 appears, and afterwards ignore every row until a 1.0 appears again.
You can use .ffill to figure out if it's a NaN below a 1 or a 0.Here are the NaN values below a 1df[(df['Mode'].isnull()) & df['Mode'].ffill() == 1]# Timestamp Value Mode#1 00-00-20 45425 NaN#5 00-00-60 25678 NaNTo get all of the 1s and NaN below:df[((df['Mode'].isnull()) & df['Mode'].ffill() == 1) | df.Mode == 1]# Timestamp Value Mode#0 00-00-10 34567 1.0#1 00-00-20 45425 NaN#4 00-00-50 25665 1.0#5 00-00-60 25678 NaNYou can get away with slightly nicer logic, since you have only 1 and 0, though this might not always work due to the NaN in 'Mode' (It seems to work for the above bit)df[((df['Mode'].isnull()) & df['Mode'].ffill()) | df.Mode]
Change CSV name to CSV date time python I want to change csv name (in this case Example.csv) to a specific name: date time name. I have a library called from datetime import datetimeThis is my sentence to create a cvsFile:with open('Example.csv', 'w') as csvFile:I want that my output to be:20180820.csv20180821.csv20180822.csv ... etcAnd if I run more that one time in the same day, I want that my output to be:20180820.csv (First time that I run the script) 20180821(2).csv (Second time run) ... etc
Something like this:import pandas as pdimport datetimecurrent_date = datetime.datetime.now()filename = str(current_date.day)+str(current_date.month)+str(current_date.year)df.to_csv(str(filename + '.csv'))
Python select exists SQLite3 with variable I am to be unable to get the following code to work. I know how to use python variables in queries, but somehow I can't get this right. The query works fine when I hard code the 'icaocode' variable in the query, but not if I try to use a variable. What is wrong with this code?icaocode = input()c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO = ?)", (icaocode))if c.fetchone(): print("Found!")else: print("Not found...")Received error:sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 4 supplied.
In Python, wrapping an expression in parentheses does not make any difference, (icaocode) is exactly the same as icaocode.The execute method expects some kind of list of parameters, so it sees the string as a sequence of four characters.To tell Python that you want a tuple with a single element, you have to add a comma:c.execute("... WHERE ICAO = ?", (icaocode,))
File in "datas" array from the pyinstaller "spec" file is not found By creating the following spec file:# -*- mode: python ; coding: utf-8 -*-block_cipher = Noneface_models = [('face_recognition_models/models/*.dat', 'face_recognition_models/models')]a = Analysis(['main.py'], pathex=[], binaries=face_models, datas=[ ('material/haarcascade_frontalface_default.xml','tools'), ('processing/model_01_human_category.h5','tools'), ('icon/faceicon.ico','tools') ],# MORE CODE...I try to run the .exe that was created and I get the following error.My line 69:self.model = load_model('tools/model_01_human_category.h5')I confess that I don't know what else to do...
I found an interesting solution that solved the problem, follow the link: https://github.com/explosion/spaCy/issues/3592I used this script to get the correct PATH from the file that was built by the .specdef resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath("__file__"))) return os.path.join(base_path, relative_path)
How to export all the Details in the Div using Beautiful soup python to excel/csv? i am Newbie to Soup/python and i am trying to find the data.my website Structure look like this.and if i open the Divclass border class it look like this.(image below)I have done something like this:for P in soup.find_all('p', attrs={'class': 'bid_no pull-left'}) : print(P.find('a').contents[0])a Div structure look like there are around 10 div in each pagethis in which i want to extract the Items,Quantity Require,Bid number,End date.Please help me<div class="border block " style="display: block;"> <div class="block_header"> <p class="bid_no pull-left"> BID NO: <a style="color:#fff !important" href="/showbidDocument/1844736">GEM/2020/B/763154</a></p> <p class="pull-right view_corrigendum" data-bid="1844736" style="display:none; margin-left: 10px;"><a href="#">View Corrigendum</a></p> <div class="clearfix"></div> </div> <div class="col-block"> <p><strong style="text-transform: none !important;">Item(s): </strong><span>Compatible Cartridge</span></p> <p><strong>Quantity Required: </strong><span>8</span></p> <div class="clearfix"></div> </div> <div class="col-block"> <p><strong>Department Name And Address:</strong></p> <p class="add-height"> Ministry Of Railways<br> Na<br> South Central Railway N/a </p> <div class="clearfix"></div> </div> <div class="col-block"> <p><strong>Start Date: </strong><span>25-08-2020 02:54 PM</span></p> <p><strong>End Date: </strong><span>04-09-2020 03:00 PM</span></p> <div class="clearfix"></div> </div> <div class="clearfix"></div></div>Error image
Try the below approach using requests and beautiful soup. I have created the script with the URL which is fetched from website and then creating a dynamic URL to traverse each and every page to get the data.What exactly script is doing:First script will create a URL where page_no query string parameter will increment by 1 upon completion of each traversal.Requests will get the data from the created URL using get method which will then pass to beautiful soup to parse HTML structure using lxml.Then from the parsed data script will search for the div where data is actually present.Finally looping on all the div text data one by one for each page.```pythonimport requestsfrom urllib3.exceptions import InsecureRequestWarningrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)from bs4 import BeautifulSoup as bsdef scrap_bid_data():page_no = 1 #initial page numberwhile True: print('Hold on creating URL to fetch data...') URL = 'https://bidplus.gem.gov.in/bidlists?bidlists&page_no=' + str(page_no) #create dynamic URL print('URL cerated: ' + URL) scraped_data = requests.get(URL,verify=False) # request to get the data soup_data = bs(scraped_data.text, 'lxml') #parse the scraped data using lxml extracted_data = soup_data.find('div',{'id':'pagi_content'}) #find divs which contains required data if len(extracted_data) == 0: # **if block** which will check the length of extracted_data if it is 0 then quit and stop the further execution of script. break else: for idx in range(len(extracted_data)): # loops through all the divs and extract and print data if(idx % 2 == 1): #get data from odd indexes only because we have required data on odd indexes bid_data = extracted_data.contents[idx].text.strip().split('\n') print('-' * 100) print(bid_data[0]) #BID number print(bid_data[5]) #Items print(bid_data[6]) #Quantitiy Required print(bid_data[10] + bid_data[12].strip()) #Department name and address print(bid_data[16]) #Start date print(bid_data[17]) #End date print('-' * 100) page_no +=1 #increments the page number by 1 scrap_bid_data() ```Actual CodeOutput image
TastyPie throttling - by user or by IP? I can't seem to find any information on what TastyPie throttles based on. Is it by the IP of the request, or by the actual Django user object?
Throttle key is based on authentication.get_identifier function.Default implementation of this function returns a combination of IP address and hostname.EditOther implementations (i.e. BasicAuthentication, ApiKeyAuthentication) returns username of the currently logged user or nouser string.
Can't get Pygame Collision detection to work I'm using Pygame and Python 3.2 to make a game. I must find out how to use collision detection so the player (ballpic) can pick up the items.Here is my code:from pygame import * #import pygamebg = image.load('BG.png')ballpic = image.load('PlayerForward1.png') #Set the variable "ballpic" to ball.pngseed = image.load('Sunflowerseed.png')ballpic.set_colorkey((0,0,0))from random import randintnumballs = 10delay = 5red = ( 0, 0, 255)done=Falseballx = 0 #Ball Coordinatesbally=0ballxmove = 0ballymove = 0 #Set the direction of the ballinit() #Start Pygamekey.set_repeat(10,10)screen = display.set_mode((640, 480)) #Set the size of the windowdisplay.set_caption("RPG game") #Set the window nameevent.set_grab(1)if ballx > 600: ballx =ballx-4if ballx < 0: ballx =ballx+4if bally > 440: bally=bally-4if bally < 0: bally=bally+4mixer.music.load('bgm.flac')#mixer.music.play(-1, 0.0)while done == False: screen.fill(0) #Fill the screen with black screen.blit(bg, (ballx,bally)) screen.blit(ballpic, (320,240))#Draw ball screen.blit(seed, (ballx,240)) display.update() #Update the screen time.delay(9) #Slow it down ballx=ballx + ballxmove #Update ball position bally=bally + ballymove for e in event.get(): #Check for ESC pressed if e.type == KEYDOWN: if e.key ==K_LEFT: ballpic=image.load('PlayerReversed.png') print(ballx,bally) ballx= (ballx+4) if e.key ==K_RIGHT: ballpic=image.load('PlayerForward1.png') print(ballx,bally) ballx=ballx-4 if e.key == K_ESCAPE: quit()My background (BG) runs on the ballx variable so the screen appears to scroll.I need to detect if ballpic and seed collide.
Why don't you try to use rectangles in pygame and their collision detection. http://www.pygame.org/docs/ref/rect.htmlYou can also try to google a simple pygame game and see what's what.
splitting list and adding values I have the following listlst = ['Adam,widgets,5769', 'joe,balls,7186', 'greg,tops,1819.999',]I need to be able to take the list and then divide the Adams number by lets say 100, and put that new number back into the list and then add it to gregs total.I started by splitting out the list, I am not wanting someone to right the code, I just need a way to separate out each part of the list so I can view it as individual parts.for i in sod_hng_hhl_lst: g=i.split(",")This gives['Adam','widgets','5769']etcwhat is best way to divided the number and then add it to another group in the list.
In [1]: lst = ['Adam,widgets,5769', 'joe,balls,7186', 'greg,tops,1819.999']In [2]: lst = [s.split(',') for s in lst]In [4]: for l in lst: l[-1] = float(l[-1]) ...: In [5]: for l in lst: ...: if l[0] == "Adam": ...: l[-1] /= 100 ...: In [6]: lstOut[6]: [['Adam', 'widgets', 57.69], ['joe', 'balls', 7186.0], ['greg', 'tops', 1819.999]]
Python: Listing the duplicates in a list I am fairly new to Python and I am interested in listing duplicates within a list. I know how to remove the duplicates ( set() ) within a list and how to list the duplicates within a list by using collections.Counter; however, for the project that I am working on this wouldn't be the most efficient method to use since the run time would be n(n-1)/2 --> O(n^2) and n is anywhere from 5k-50k+ string values.So, my idea is that since python lists are linked data structures and are assigned to the memory when created that I begin counting duplicates from the very beginning of the creation of the lists.List is created and the first index value is the word 'dog'Second index value is the word 'cat'Now, it would check if the second index is equal to the first index, if it is then append to another list called Duplicates.Third index value is assigned 'dog', and the third index would check if it is equal to 'cat' then 'dog'; since it matches the first index, it is appended to Duplicates.Fourth index is assigned 'dog', but it would check the third index only, and not the second and first, because now you can assume that since the third and second are not duplicates that the fourth does not need to check before, and since the third/first are equal, the search stops at the third index.My project gives me these values and append it to a list, so I would want to implement that above algorithm because I don't care how many duplicates there are, I just want to know if there are duplicates.I can't think of how to write the code, but I figured the basic structure of it, but I might be completely off (using random numgen for easier use):for x in xrange(0,10): list1.append(x) for rev, y in enumerate(reversed(list1)): while x is not list1(y): cond() if ???
I really don't think you'll get better than a collections.Counter for this:c = Counter(mylist)duplicates = [ x for x,y in c.items() if y > 1 ]building the Counter should be O(n) (unless you're using keys which are particularly bad for hashing -- But in my experience, you need to try pretty hard to make that happen) and then getting the duplicates list is also O(n) giving you a total complexity of O(2n) == O(n) (for typical uses).
Output compiler error to a txt file in python I'm a beginner using python. I want to create a regular expression to capture error messages from compiler output in python. How would I do this?for example, if the compiler output is the following error message:Traceback (most recent call last): File "sample.py", line 1, in <module> helloNameError: name 'hello' is not definedI want to be able to only extract only the following string from the output:NameError: name 'hello' is not definedIn this case there is only one error, however I want to extract all the errors the compiler outputs. How do I do this using regular expressions? Or if there is an easier way, I'm open to suggestions
r'Traceback \(most recent call last\):\n(?:[ ]+.*\n)*(\w+: .*)'should extract your exception; a traceback contains lines that all start with whitespace except for the exception line.The above matches the literal text of the traceback first line, 0 or more lines that start with at least one space, and then captures the line following that provided it starts with 1 or more word characters (which fits Python identifiers nicely), a colon, and then the rest up to the end of a line.Demo:>>> import re>>> sample = '''\... Traceback (most recent call last):... File "sample.py", line 1, in <module>... hello... NameError: name 'hello' is not defined... '''>>> re.search(r'Traceback \(most recent call last\):\n(?:[ ]+.*\n)*(\w+: .*)', sample).groups()("NameError: name 'hello' is not defined",)
nested workspace problems: packages with the same name seem to overwrite? I am working on a project where I need nested workspaces--our project has a git repository with a submodule, and both need to be able to build and run bazel tests independently.The structure is like this:projectA WORKSPACE tools/ py/ testing.py tests/ sample_test.py projectB WORKSPACE tools/ py/ different_file.pyThe file, sample_test.py, references both projectA/tools/py/testing.py and projectB/tools/py/different_file.py. My projectA workspace has a config like this:local_repository( name = "projectB", path = __workspace_dir__ + "/projectB",)And then my build rule for my test is like this:py_test( name = "sample_test", srcs = ["sample_test.py"], deps = [ ":class_under_test", "//tools/py:testing", "@projectB//tools/py:different_file", ])And testing.py has imports like this:from tools.py.testing import functionAfrom projectB.tools.py.different_file import functionBNow, when I run the test, I get a Python error that says:ImportError: no module named tools.py.testingIf I comment out both imports and just sayimport tools.pyand in my test setup, do print(tools.py), it shows the path to testing in projectB!bazel-out/local-fastbuild/bin/analysis/py/test_name.runfiles/projectB/tools/py/__init__.pycThe right thing seems to be here at:bazel-out/local-fastbuild/bin/analysis/py/test_name.runfiles/__main__/tools/py/testing.pyWhat am I missing here? Surely there's a way for nested workspaces to be able to reference same paths without clobbering one another.Thanks for your time!
This problem resolved itself when I gave projectA a name in the workspace file:workspace(name = "projectA")I already had that line in projectB's WORKSPACE file but it got skipped in projectA.
csv_reader read N lines at a time I have to read a CSV file N lines at a time.csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: print rowI know I can loop N times at a time, build a list of list and process that way.But is there a simpler way of using csv_reader so that I read n lines at a time.
Hi I don't think that you'll be able to do that without a loop with csv package.You should use pandas (pip install --user pandas) instead:import pandasdf = pandas.read_csv('myfile.csv')start = 0step = 2 # Your 'N'for i in range(0, len(df), step): print(df[i:i+step]) start = i
urlopen for loop with beautifulsoup New user here. I'm starting to get the hang of Python syntax but keep getting thrown off by for loops. I understand each scenario I've reach on SO thus far (and my previous examples), but can't seem to come up with one for my current scenario.I am playing around with BeautifulSoup to extract features from app stores as an exercise.I created a list of both GooglePlay and iTunes urls to play around with. list = {"https://play.google.com/store/apps/details?id=com.tov.google.ben10Xenodromeplus&hl=en","https://play.google.com/store/apps/details?id=com.doraemon.doraemonRepairShopSeasons&hl=en","https://play.google.com/store/apps/details?id=com.KnowledgeAdventure.SchoolOfDragons&hl=en","https://play.google.com/store/apps/details?id=com.turner.stevenrpg&hl=en","https://play.google.com/store/apps/details?id=com.indigokids.mimdoctor&hl=en","https://play.google.com/store/apps/details?id=com.rovio.gold&hl=en","https://itunes.apple.com/us/app/angry-birds/id343200656?mt=8","https://itunes.apple.com/us/app/doodle-jump/id307727765?mt=8","https://itunes.apple.com/us/app/tiny-wings/id417817520?mt=8","https://itunes.apple.com/us/app/flick-home-run-!/id454086751?mt=8","https://itunes.apple.com/us/app/bike-race-pro/id510461370?mt=8"}To test out beautifulsoup (bs in my code), I used one app for each store:gptest = bs(urllib.urlopen("https://play.google.com/store/apps/details?id=com.rovio.gold&hl=en"))ios = bs(urllib.urlopen("https://itunes.apple.com/us/app/doodle-jump/id307727765?mt=8"))I found an app's category on iTunes using:print ios.find(itemprop="applicationCategory").get_text()...and on Google Play:print gptest.find(itemprop="genre").get_text()With this newfound confidence, I wanted to try to iterate through my entire list and output these values, but then I realized I suck at for loops...Here's my attempt:def opensite():for item in list: bs(urllib.urlopen())for item in list:try: if "itunes.apple.com" in row: print "Category:", opensite.find(itemprop="applicationCategory").get_text() else if "play.google.com" in row: print "Category", opensite.find(itemprop="genre").get_text()except: passNote: Ideally I'd be passing a csv (called "sample" with one column "URL") so I believe my loop would start withfor row in sample.URL:but I figured it was more helpful to show you a list rather than deal with a data frame.Thanks in advance!
from __future__ import print_function #try: # from urllib import urlopen # Support Python 2 and 3except ImportError: # from urllib.request import urlopen #from bs4 import BeautifulSoup as bsfor line in open('urls.dat'): # Read urls from file line by line doc = bs(urlopen(line.strip()), 'html5lib') # Strip \n from url, open it and parse if 'apple.com' in line: prop = 'applicationCategory' elif 'google.com' in line: prop = 'genre' else: continue print(doc.find(itemprop=prop).get_text())
Distributed processing of a PostgreSQL table I've got a PostgreSQL table with several millions of rows that need to be processed with the same algorithm.I am using Python and SQLAlchemy.Core for this task.This algorithm accepts one or several rows as input and returns the same amount of rows with some updated values.id1, id2, NULL, NULL, NULL -> id1, id2, value1, value2, value3id1, id3, NULL, NULL, NULL -> id1, id3, value4, value5, value6id2, id3, NULL, NULL, NULL -> id2, id3, value7, value8, value9...id_n, id_m, NULL, NULL, NULL -> id_n, id_m, value_xxx, value_yyy, value_zzzI am using a PC cluster to perform this task. This cluster runs dask.distributed scheduler and workers.I think, that this task can be effectively implemented with the map function. My idea is that each worker queries data base, selects for processing some rows with NULL values, then updates them with results.My question is: how to write the SQL query, that would allow to distribute pieces of the table among workers?I've tried to define subsets of row for each worker with offset and limit in SQL queries, that each worker emits:SQL:select * from table where value1 is NULL offset N limit 100;...update table where id1 = ... and id2 = ... set value1 = value...; Python: from sqlalchemy import create_engine, bindparam, select, funcfrom distributed import Executor, progressdef process(offset, limit): engine = create_engine(...) # get next piece of work query = select(...).where(...).limit(limit).offset(offset) rows = engine.execute([select]).fetchall() # process rows # submit values to table update_stmt = table.update().where(...).where(...).values(...) up_values = ... engine.execute(update_stmt, up_values) if __name__ == '__main__': e = Executor('{address}:{port}'.format(address=config('SERVER_ADDR'), port=config('SERVER_PORT'))) n_rows = count_rows_to_process() chunk_size = 100 progress(e.map(process, range(0, n_rows, chunk_size)))However, this didn't work. The range function has returned list of offsets before calculations have started, and the map function has distributed them among workers before starting process function. Then some workers have successfully finished processing their chunks of work, submitted their results to the table, and updated values. Then new iteration begins, new SELECT ...WHERE value1 is NULL LIMIT 100 OFFSET ... query is sent to the data base, but the offset is now invalid, because it was calculated before the previous workers have updated the table. Amount of NULL values is now reduced, and a worker can receive empty set from the database.I cannot use one SELECT query before starting calculations, because it will return huge table that doesn't fit in RAM.SQLAlchemy manual also says that for distributed processing the engine instance should be created locally for each python process. Therefore, I cannot query the database once and send returned cursor to the process function.Therefore, the solution is correct construction of SQL queries.
One option to consider is randomization:SELECT *FROM tableWHERE value1 IS NULLORDER BY random()LIMIT 100;In worst case scenario you will have several workers calculating the same thing in parallel. If it does not bother you this is one of the most simple ways.The other option is dedicating individual rows to the particular worker:UPDATE table SET value1 = -9999 WHERE id IN ( SELECT id FROM table WHERE value1 IS NULL ORDER BY random() LIMIT 100) RETURNING * ;This way you "mark" the rows your particular worker has "taken" with -9999. All other workers will skip these rows as value1 IS NOT NULL any more. The risk here is that if the worker fails you will not have a simple way to get back to these rows - you would have to manually update them back to NULL.
BeautifulSoup doesn't find, findAll, or get a div by its ID I've been on this for the last two days non-stop...I'm trying to get a specific div by its ID using BeautifulSoup as so:import requestsfrom bs4 import BeautifulSoupr = requests.get('www.example.com', cookies=cookies_dict)soup = BeautifulSoup(r.content, 'html.parser')div_text = soup.get('div', {'id': 'this_div_id'}).textprint div_textAll I get is a dictionary:{'id': 'this_div_id'}Now, I checked to make sure that 'this_div_id' actually is inside of r.content:>>> 'this_div_id' in r.contentTrueI'd be glad to receive any help and suggestions.
Err... Maybe you should check BeautifulSoup documentation again ?-) Help on method get in module bs4.element: get(self, key, default=None) unbound bs4.BeautifulSoup method Returns the value of the 'key' attribute for the tag, or the value given for 'default' if it doesn't have that attribute.I think you want the find() method instead:>>> html = """<html><body><div><div><div id='this_div_id'>haha</div></div></div>""">>> from bs4 import BeautifulSoup>>> s = BeautifulSoup(html, 'html.parser')>>> s.find("div")<div><div><div id="this_div_id">haha</div></div></div>>>> s.find("div", id="this_div_id")*<div id="this_div_id">haha</div>>>>
python and mysql connections in a class , DB open and close strange behaviour I have written a small app that uses mysql to get a list of products that need updating on our magento website.Python then actions these updates and marks the product in the db as complete.My Original code (pseudo to show the overview)class Mysqltools: def get_products(): db = pymysql.connect(host= .... ) mysqlcursor = db.cursor(pymysql.cursors.DictCursor) sql = select * from x where y = z mysqlcursor.execute(sql % (z)) rows = mysqlcursor.fetchall() mysqlcursor.close() db.close return rows def write_products(sku, name, id): db = pymysql.connect(host= .... ) mysqlcursor = db.cursor(pymysql.cursors.DictCursor) sql = update table set sku = sku, name = name, id = id..... mysqlcursor.execute(sql % (sku, name, id)) mysqlcursor.close() db.closeThis was working ok, but on each db connection string we were getting a pause.I did a bit of research and did the following:class Mysqltools: def __init__(): self.db = pymysql.connect(host= .... ) def get_products(): mysqlcursor = self.db.cursor(pymysql.cursors.DictCursor) sql = select * from x where y = z mysqlcursor.execute(sql % (z)) rows = mysqlcursor.fetchall() mysqlcursor.close() def write_products(sku, name, id): mysqlcursor = self.db.cursor(pymysql.cursors.DictCursor) sql = update table set sku = sku, name = name, id = id..... mysqlcursor.execute(sql % (sku, name, id)) mysqlcursor.close() db.commit()This has a MASSIVE speed improvement. However, it would only do a successful get_products on the first iteration, once it was called a second time, it was finding 0 products to update, even though performing the same SQL on the db would show a number of rows returned.Am I doing something wrong with the connections ?I have also tried moving the db = outside of the class and referencing it but that still gives the same issue.UPDATEDoing some testing, and if I remove the DictCursor from the cursor I can get the correct rows returned each time (I've just created a quick loop to keep checking for records)Is the DictCursor doing something I am unaware of ?** UPDATE 2 **I've removed the DictCursor, and tried the following.Create a while True loop which calls my get_product method.In MySQL change some rows so that they should be found.If I go from having 0 possible rows to find, then change some so they should be found, my code just shows 0 found, and loops stating this.If I got from having x possible rows to find, then change it to 0 in mysql, my code continues to loop showing the x possible rows.
Ok, the answer to this is as follows:db = pymysql.connect(host=.... user=... )class MySqlTools: def get_products(): mysqlcursor = db.cursor(pymysql.cursors.DictCursor) sql = select * from x where y = z mysqlcursor.execute(sql % (z)) rows = mysqlcursor.fetchall() mysqlcursor.close() db.commit()This then allows you to re-use the db connection and remove the overhead of creating and closing a connection each and every time.In testing, downloading 500 orders from our website and writing them to a db went from 16minutes to <3 minutes.
Why is my Output 0? def russian (a,b): x=a y=b z=0 while x>0: if x % 2 == 1: z=z+y y= y *2 x= x/2 return zprint russian(24,16)This function uses the russian peasant algorithm to multiply two numbers together. I am expecting to see 384 as my output but I get 0 instead. What am I doing wrong? I am using Python 2.7.
You are computing the z value only once and then immediately return it inside the while loop. Lose one level of indentation for return z.
How to split an equation given as a string into coefficients, variables and powers? So I have to create a program which takes a string in the following form:2x^3 + x^2 - 4 and calculate its derivative i.e. make it like this: 6x^2 + 2x So I'm creating a class Monomial that has three member variables: coefficient, variable name and power. In other words, I have to split the polynomial into monomials. Then I have to take each monomial and split it into the aforementioned variables. So 2x^3 would be represented as the following object: Monomial(2, 'x', 3)However, how do I split the string like that specifically? I don't want to use 'SymPy' or other libraries for easy calculation of derivatives.
I would use regular expressions:pattern = "(\d+)?([a-z])\^(\d+)"result = re.match(pattern, "323x^22")print result.groups() produces:('323', 'x', '22')The explanation of the pattern is as follows: Each of the parenthesis will contain a group, the first one matches digits, indicated by the "\d" and matches as many digits as possible, indicated by "+". The question mark indicates that if there is no match (because it is x^2 for example) that is OK. In the central group you see [a-z] which will match any single low-case letter. So, if you find "23c^2" it will match as well. Finally, you need to escape the "^" symbol, which has its own meaning in regular expressions, using "\^" instead.result = re.match(pattern, "x^2")print result.groups()Now, for an input of "x^2" this code will produce:(None, 'x', '2')so just make sure to substitute None for 1.
mpi4py getting only one MPI process available I'm trying to use mpi4py but am getting the following error when trying to initialize it:Tried to create an MPI pool, but there was only one MPI process available. Need at least two.The value of MPI.COMM_WORLD.Get_size() is 1, which confirms the issue.Still, when I run the usual test after installing it I get the expected output, which is weird:$ mpiexec -n 5 python -m mpi4py.bench helloworldHello, World! I am process 0 of 5 on sevrhuntd1.Hello, World! I am process 1 of 5 on sevrhuntd1.Hello, World! I am process 2 of 5 on sevrhuntd1.Hello, World! I am process 3 of 5 on sevrhuntd1.Hello, World! I am process 4 of 5 on sevrhuntd1.I'm not a system admin and it is taking them a while to process my request to remove openmpi and install mpich, as suggested here and here. Is there any other way around this error?More specifically, I'm trying to create a pool using the MPIPool class in this file in the Platypus library and am getting the error here:from mpi4py import MPIclass MPIPool(object): def __init__(self, comm=None, debug=False, loadbalance=False): self.comm = MPI.COMM_WORLD if comm is None else comm self.rank = self.comm.Get_rank() self.size = self.comm.Get_size() - 1 self.debug = debug self.function = _error_function self.loadbalance = loadbalance if self.size == 0: raise ValueError("Tried to create an MPI pool, but there " "was only one MPI process available. " "Need at least two.") # This is the error. # More code below, but not making it there.when trying to initialize it with the following in my main:if __name__ == "__main__": pool = MPIPool()
This was a stupid mistake. I just had to call Python with mpiexec -n <# processes> python .... Problem solved.
Optimal memory storage, nested lists vs. flat lists I have a fairly large amount of data that needs to be stored in memory in Python, and i'm trying to work out how to save memory space as i'm continually running out of RAM.I have restricted myself to use only basic Python methods like lists, dicts and tuples as i have found, that these often have a huge advantage in speed when i need to read/write the data.How much am i penalized memory-wise for organizing my data in nested lists/dicts/tuples vs. just one flat list/dict/tuple?Nested example:[ [ [ a ], [ b ], [ c ] ], [ [ d ], [ e ], [ f ] ],]Flat list:[ a, b, c, d, e, f ]1st edit: Data is a mix of string, float and int values.2nd edit: Context as requested: These are small datasets for use in a neural network. The data cannot readily be split up or handled in chunks, as it will impair the training process, or require a large amount of the code to be rewritten. I have 32gb of RAM available.
If your data is all of the same type, especially if it is primitive types (int, float, character, not str though) try using numpy arrays. Numpy stores data as a flat list but let's you access it like it's nested, and will generally use less memory as it is implemented to be more memory and speed efficient than lists. Keep in mind though that this only applies to rectangular arrays (ie. each sublist must have the same length).
total size of new array must be unchanged I have two arrays x1 and x2, both are 1*14 arrays i am trying to zip them up and then perform reshape.The code is as below ;x1Out[122]: array([1, 2, 3, 1, 5, 6, 5, 5, 6, 7, 8, 9, 7, 9])x2Out[123]: array([1, 3, 2, 2, 8, 6, 7, 6, 7, 1, 2, 1, 1, 3])X = np.array(zip(x1, x2)).reshape(2, len(x1))ValueErrorTraceback (most recent call last) in ()----> 1 X = np.array(zip(x1, x2)).reshape(2, len(x1))ValueError: total size of new array must be unchanged
I would assume you're on Python 3, in which the result is an array with a zip object. You should call list on the zipped items:X = np.array(list(zip(x1, x2))).reshape(2, len(x1))# ^^^^print(X)# [[1 1 2 3 3 2 1 2 5 8 6 6 5 7]# [5 6 6 7 7 1 8 2 9 1 7 1 9 3]]In Python 2, zip returns a list and not an iterator as with Python 3, and your previous code would work fine.
How should negative time work? I'm trying to create a Time -class which can handle times of format hh:mm:ss.This is what I have:class Time(object): def __init__(self, h=0, m=0, s=0): #private self.__hours = 0 self.__minutes = 0 self.__seconds = 0 #public self.hours = h self.minutes = m self.seconds = s @property def hours(self): return self.__hours @hours.setter def hours(self, value): if value < 0: raise ValueError self.__hours = value @property def minutes(self): return self.__minutes @minutes.setter def minutes(self, value): if value < 0: raise ValueError self.hours += int(value / 60) self.__minutes = value % 60 @property def seconds(self): return self.__seconds @seconds.setter def seconds(self, value): if value < 0: raise ValueError self.minutes += int(value / 60) self.__seconds = value % 60I'm having problems with negative time values.What I do is check if the time value (e.g. minutes) is being set to negative and raise a ValueError if it is.But the thing is, I would like to work with negative time formats too, I'm just not sure how.How should negative time values behave?Are they even possible to achieve with my setters?I really can't even get started, I don't need you to code it for me, but atleast give some tips and explain how negative time works.
There are 2 concepts to time:a moment in time (instant)a length between two instants (timespan or time delta).We measure timespan in seconds and multiple of seconds.A moment of time is described using the same unit, understood as a timespan between some reference time (like 0 BC, or Unix epoch). (The units are more complex though - instead of regular multiples of seconds, we use calendars that assign nice names like "July 16th" to particular moments in time).So:Timespan or can certainly be negative (as a whole)An instant can be negative too, because there's a timespan inside (like year -3000 BC), but the actual formats don't have negative coefficients (it makes no sense to say "14:-3" or "June -5th").So:setting minutes to negative on an instant, should be a ValueError,there could be a method .later(minutes=10) that would be equivalent to .earlier(minutes=-10).
What's the difference between class variables of different types? Firstly, there is class A with two class variables and two instance variables:In [1]: def fun(x, y): return x + yIn [2]: class A: ...: cvar = 1 ...: cfun = fun ...: def __init__(self): ...: self.ivar = 100 ...: self.ifun = funWe can see that both class variable and instance variable of int type works fine:In [3]: a = A()In [4]: a.ivar, a.cvarOut[4]: (100, 1)However, things have changed if we check the function type variables:In [5]: a.ifun, a.cfunOut[5]: (<function __main__.fun>, <bound method A.fun of <__main__.A instance at 0x25f90e0>>)In [6]: a.ifun(1,2)Out[6]: 3In [7]: a.cfun(1,2)---------------------------------------------------------------------------TypeError Traceback (most recent call last)/home/future/<ipython-input-7-39aa8db2389e> in <module>()----> 1 a.cfun(1,2)TypeError: fun() takes exactly 2 arguments (3 given)I known that python has translated a.cfun(1,2) to A.cfun(a,1,2) and then error raised.My question is: Since both cvar and cfun are class variable, why do python treat them in difference way?
Actually, a function assigned to a class member remains function:def x():passclass A: f = x e = None g = Noneprint(A.__dict__['f'])# <function x at 0x10e0a6e60>It's converted on the fly to a method object when you retrieve it from an instance:print(A().f)# <bound method A.x of <__main__.A instance at 0x1101ddea8>>http://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy "User-defined methods": User-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class), if that attribute is a user-defined function object, an unbound user-defined method object, or a class method object... Note that the transformation from function object to (unbound or bound) method object happens each time the attribute is retrieved from the class or instance.This conversion only occurs to functions assigned to a class, not to an instance. Note that this has been changed in Python 3, where Class.fun returns a normal function, not an "unbound method". As to your question why is this needed, a method object are essentially a closure that contains a function along with its execution context ("self"). Imagine you've got an object and use its method as a callback somewhere. In many other languages you have to pass both object and method pointers or to create a closure manually. For example, in javascript: myListener = new Listener() something.onSomeEvent = myListener.listen // won't work! something.onSomeEvent = function() { myListener.listen() } // worksPython manages that for us behind the scenes: myListener = Listener() something.onSomeEvent = myListener.listen // worksOn the other side, sometimes it's practical to have "bare" functions or "foreign" methods in a class: def __init__(..., dir, ..): self.strip = str.lstrip if dir == 'ltr' else str.rstrip ... def foo(self, arg): self.strip(arg)This above convention (class vars => methods, instance vars => functions) provides a convenient way to have both.Needless to add, like everything else in python, it's possible to change this behavior, i.e. to write a class that doesn't convert its functions to methods and returns them as is.
Using POST for flask url I've been looking at other stack questions but I am still confused on a concept that I think is very simple to most people on here. Basically, I'm trying to understand how my data from my form will post to my url route when form.validate_on_submit. Apologies in advance for bad terminology with Get/Post I have the following form using WTForms: class Info(Form): name = StringField('Name', validators=[Length(0, 64)],filters=[lambda x: x or None]) submit = SubmitField('Submit')Then in my views.py I use the form. @main.route('/people/', methods=('GET', 'POST'))def person(): form = Info() if form.validate_on_submit(): name = form.name.data return redirect(url_for('.find_person', name=name)) return render_template('mytemplate.html', form=form)I would want the url to post to something like @main.route/people/. Then in find_person() I would be able to use request.form to get the arguments. Thanks in advance
In your HTML template, when setting up your form tags, make sure it looks like:<form action="{{ url_for('people') }}" method="post"> <...content of your form here...></form>
Can't install virtualenvwrapper on OSX 10.11 El Capitan I recently wiped my Mac and reinstalled OSX El Capitan public beta 3. I installed pip with sudo easy_install pip and installed virtualenv with sudo pip install virtualenv and did not have any problems.Now, when I try to sudo pip install virtualenvwrapper, I get the following:Users-Air:~ User$ sudo pip install virtualenvwrapperThe directory '/Users/User/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.The directory '/Users/User/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.Collecting virtualenvwrapper Downloading virtualenvwrapper-4.6.0-py2.py3-none-any.whlRequirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Python/2.7/site-packages (from virtualenvwrapper)Requirement already satisfied (use --upgrade to upgrade): virtualenv-clone in /Library/Python/2.7/site-packages (from virtualenvwrapper)Collecting stevedore (from virtualenvwrapper) Downloading stevedore-1.7.0-py2.py3-none-any.whlRequirement already satisfied (use --upgrade to upgrade): pbr<2.0,>=1.3 in /Library/Python/2.7/site-packages (from stevedore->virtualenvwrapper)Requirement already satisfied (use --upgrade to upgrade): argparse in /Library/Python/2.7/site-packages (from stevedore->virtualenvwrapper)Collecting six>=1.9.0 (from stevedore->virtualenvwrapper) Downloading six-1.9.0-py2.py3-none-any.whlInstalling collected packages: six, stevedore, virtualenvwrapper Found existing installation: six 1.4.1 DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project. Uninstalling six-1.4.1:Exception:Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/basecommand.py", line 223, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/commands/install.py", line 299, in run root=options.root_path, File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_set.py", line 640, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_install.py", line 726, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_uninstall.py", line 125, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/utils/__init__.py", line 314, in renames shutil.move(old, new) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move copy2(src, real_dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2 copystat(src, dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat os.chflags(dst, st.st_flags)OSError: [Errno 1] Operation not permitted: '/tmp/pip-tTNnKQ-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'As the issue seems to be with the six package, manually trying to uninstall it with sudo pip uninstall six results in the same error. The output suggests using the -H flag as well, but I still get pretty much the same error:Users-Air:~ User$ sudo -H pip install virtualenvwrapperCollecting virtualenvwrapper Downloading virtualenvwrapper-4.6.0-py2.py3-none-any.whlRequirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Python/2.7/site-packages (from virtualenvwrapper)Requirement already satisfied (use --upgrade to upgrade): virtualenv-clone in /Library/Python/2.7/site-packages (from virtualenvwrapper)Collecting stevedore (from virtualenvwrapper) Downloading stevedore-1.7.0-py2.py3-none-any.whlRequirement already satisfied (use --upgrade to upgrade): pbr<2.0,>=1.3 in /Library/Python/2.7/site-packages (from stevedore->virtualenvwrapper)Requirement already satisfied (use --upgrade to upgrade): argparse in /Library/Python/2.7/site-packages (from stevedore->virtualenvwrapper)Collecting six>=1.9.0 (from stevedore->virtualenvwrapper) Downloading six-1.9.0-py2.py3-none-any.whlInstalling collected packages: six, stevedore, virtualenvwrapper Found existing installation: six 1.4.1 DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project. Uninstalling six-1.4.1:Exception:Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/basecommand.py", line 223, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/commands/install.py", line 299, in run root=options.root_path, File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_set.py", line 640, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_install.py", line 726, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_uninstall.py", line 125, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/utils/__init__.py", line 314, in renames shutil.move(old, new) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move copy2(src, real_dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2 copystat(src, dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat os.chflags(dst, st.st_flags)OSError: [Errno 1] Operation not permitted: '/tmp/pip-fwQzor-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'I have disabled rootless with sudo nvram boot-args="rootless=0", and this has had no effect. Any help would be appreciated!
You can manually install the dependencies that don't exist on a stock 10.11 install, then install the other packages with --no-deps to ignore the dependencies. That way it will skip six (and argparse which is also already installed). This works on my 10.11 beta 6 install:sudo pip install pbrsudo pip install --no-deps stevedoresudo pip install --no-deps virtualenvwrapperAnd no need to disable rootless.
SQL syntax error in absurdly simple sql? Calling: INSERT IGNORE INTO standard_group (group_name, subject, grade, country, state) VALUES (%(group_name), %(subject), %(grade), %(country), %(state));With ('Arizona Social Studies Standards', 'Social Studies', '1', 'United States', 'AZ')eg: print group_columns print group_sql print group cur.execute(group_sql, dict(zip(group_columns, group)))But I always get:['group_name', 'subject', 'standard_category', 'standard_sub_category', 'standard_name', 'standard_description', 'grade', 'country', 'state', 'is_common_core', 'is_state_standard']INSERT IGNORE INTO standard_group (group_name, subject, grade, country, state) VALUES (%(group_name), %(subject), %(grade), %(country), %(state));('Arizona Social Studies Standards', 'Social Studies', '1', 'United States', 'AZ')Traceback (most recent call last): File "standards-import/simport.py", line 167, in <module> cur.execute(group_sql, dict(zip(group_columns, group))) File "/Library/Python/2.7/site-packages/mysql/connector/cursor.py", line 507, in execute self._handle_result(self._connection.cmd_query(stmt)) File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 722, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 640, in _handle_result raise errors.get_exception(packet)mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%(group_name), %(subject), %(grade), %(country), %(state))' at line 1I've tried with named params, ? and %s, and get Not all arguments usedWrong number of arguments for named parameterSQL syntaxWhat's going on?? What am I missing???
It looks like a small typo. You forgot to add s to the paramsINSERT IGNORE INTO standard_group (group_name, subject, grade, country, state) VALUES (%(group_name)s, %(subject)s, %(grade)s, %(country)s, %(state)s);The relevant code is here:execute(self, operation, params=None, multi=False)_process_params_dict(self, params)
Django string_if_invalid and default I have string_if_invalid set to 'INVALID' in my django template settings.And there is some template that looks like this:{{ some_nonexisting_value|default:'Default value' }}After rendering result looks like 'INVALID'. So, default value is not used.Is there any way to make string_if_invalid to work with default values without changing templates?Edit:Template settings look like this:TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'OPTIONS': { 'libraries': { 'utm_tags': 'kurator.templatetags.utm_tags', }, 'string_if_invalid': 'INVALID', 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'kurator.context_processors.static_hash', 'kurator.context_processors.debug', ] }, },]
No, it's not possible to get the default filter to display the provided default instead of the invalid string.Note that the docs warn against using the string_if_invalid option:For debug purposes only!While string_if_invalid can be a useful debugging tool, it is a bad idea to turn it on as a ‘development default’.Many templates, including those in the Admin site, rely upon the silence of the template system when a non-existent variable is encountered. If you assign a value other than '' to string_if_invalid, you will experience rendering problems with these templates and sites.Generally, string_if_invalid should only be enabled in order to debug a specific template problem, then cleared once debugging is complete.For your own templates, I guess you could write your own template tag that takes the variable name and a default, then tries to fetch the variable from the template context. However, this wouldn't solve the problem in other templates that use the regular default filter, including the Django admin.
Passing Commands To Python From PHP I have a python script on a vps that I run a simple command though../script.py [ipaddress] [portnumber]example./script.py 127.0.0.1 8080What I'd like to do is put a simple php script on my apache server (same vps) with a form on the page to enter the ip address and port number into it.. Along with a go button.After running the script I'd like it to display the scripts output below.IF possible (as im really just not sure) I'd like to be able to have several people use it at once... example.. 10 users all passing data to the same script at the same time.My server is running CentOS
popen() is what you wanthttp://www.php.net/manual/en/function.popen.phpThis allows you to run an arbitrary command and get the stdout result.
Pulling certain data from an input Im trying to extract a certain part of my input from the first line and use it to calculate the problem and then put it back together. For example,Please enter the starting weight of food in pounds followed by ounces:8:9Please enter the ending weight of food in pounds followed by ounces:6:14I want to extract the pounds and work that first or am I looking at this wrong? Here is the problem description:Write the pseudocode and the Python 3.3 program for the following problem. A monkey is being fed some food. Read in the starting weight in lbs:ozs. Also read in the ending weight in lbs:ozs (you may assume this is smaller than the starting weight. Find the difference and print out the amount of food consumed by the monkey in lbs:ozs. Some sample data is shown below (with the corresponding output). Hints: convert all values to ounces first. Use the “find” command to locate the “:” in the input data (see sample2 on Y:).Run#1:> Starting weight of food (in lbs:ozs)=8:9Ending weight of food (in lbs:ozs)=6:14Food consumed by the monkey (lbs:ozs)=1:11
# get input from the user, e.g. '8:9'start_weight= input('Starting weight of food (in lbs:ozs)=')# so start_weight now has the value '8:9'# find the position of the ':' character in the user input, as requested in the assignment: 'Use the “find” command to locate the “:” in the input data'sep= start_weight.find(':')# with the input from before ('8:9'), sep is now 1# convert the text up to the ":" character to a numberstart_pounds= float(start_weight[:pos])# start_pounds is now 8# convert the text after the ":" character to a numberend_pounds= float(start_weight[pos+1:])# end_pounds is now 9# get input from the user, e.g. '6:14'end_weight= input('Ending weight of food (in lbs:ozs)=')SNIP # You'll have to figure this part out for yourself, I can't do the entire assignment for you...# finally, display the result, using "str(number)" to convert numbers to textprint('Food consumed by the monkey (lbs:ozs)=' + str(pounds_eaten_by_monkey) + ':' + str(ounces_eaten_by_monkey))This should get you started. All that's left is to write the code that converts pounds and ounces to pounds, and to calculate how much food the monkey has consumed. Good luck.
Testing for cookie existence in Django Simple stuff here...if I try to reference a cookie in Django viarequest.COOKIE["key"]if the cookie doesn't exist that will throw a key error.For Django's GET and POST, since they are QueryDict objects, I can just doif "foo" in request.GETwhich is wonderfully sophisticated...what's the closest thing to this for cookies that isn't a Try/Catch block, if anything...
request.COOKIES is a standard Python dictionary, so the same syntax works.Another way of doing it is:request.COOKIES.get('key', 'default')which returns the value if the key exists, otherwise 'default' - you can put anything you like in place of 'default'.
Why can't I use variables (using "%s" or "?") to refer to table and column names in sqlite's "CREATE TABLE IF NOT EXISTS" and "INSERT INTO VALUES"? I am creating a database class for my application since I'll need database tables at various occasions. I am using sqlite3 and I need my code to be as generic as possible but when I used "%s" and/or "?" for the table name and the column titles I got the above mentioned error.Here's my code:import sqlite3conn = sqlite3.connect("cows.db")c = conn.cursor()class databases: global c def __init__(self, table_name): self.table_name = table_name def create_table(self, *args, **kwargs): c.execute('CREATE TABLE IF NOT EXISTS %s(%s)', (self.table_name, args)) c.execute("INSERT INTO %s VALUES (%s)", (self.table_name, kwargs)) conn.commit() def delete_record(self, *args): c.execute(''' DELETE FROM ? WHERE ? = ?''', (self.table_name, args)) conn.commit()cows = databases('cow')cows.create_table('cow_id REAL', 'lactation_phase TEXT', 'milk_production REAL', 'weight REAL')Here's the error message:C:\Users\farid\PycharmProjects\cownutritionmanagmentsystem\venv\Scripts\python.exe C:/Users/farid/PycharmProjects/cownutritionmanagmentsystem/database.pyTraceback (most recent call last): File "C:/Users/farid/PycharmProjects/cownutritionmanagmentsystem/database.py", line 24, in <module> cows.create_table('cow_id REAL', 'lactation_phase TEXT', 'milk_production REAL', 'weight REAL') File "C:/Users/farid/PycharmProjects/cownutritionmanagmentsystem/database.py", line 14, in create_table c.execute('CREATE TABLE IF NOT EXISTS %s(%s)', (self.table_name, args))sqlite3.OperationalError: near "%": syntax error
You can use %s to refer to the table name or other variables in the string.Notice the %s marker to insert a string, and the %d marker to insert an integer.Alternatively, you can also use the format method to substitute the value of a variable in the string.In format method, the curly braces show where the inserted value should go.You can insert multiple values using this method and values do not need to be only string but it can be numbers and other Python objects.import sqlite3conn = sqlite3.connect("cows.db")c = conn.cursor()class databases: global c def __init__(self, table_name): self.table_name = table_name def create_table(self, *args, **kwargs): c.execute('CREATE TABLE IF NOT EXISTS %s(%s)' % (self.table_name, args)) c.execute("INSERT INTO %s VALUES (%s)" % (self.table_name, kwargs)) # Notice how we have used % operator here conn.commit() def delete_record(self, *args): c.execute(''' DELETE FROM {} WHERE {} = {}'''.format(self.table_name, args)) # We have used format method here conn.commit()cows = databases('cow')cows.create_table('cow_id REAL', 'lactation_phase TEXT', 'milk_production REAL', 'weight REAL')
How do I write in a new text file every x lines? [python] Let's say I have a list with 10,000 entries. The user inputs a number, say 10. What I need to do is write all of the entries in the list to .txt files, but only 10 to each file. So the program would write the first 10, and then create a new file, and write the next 10... etc.Thankscount = 0ext = 0path = 'New/' + str(ext) + '.txt'open(path, 'a').close()for line in flines: f = open(path, 'a') if count <= x: f.write(line) count += 1 else: ext += 1 path = 'New/' + str(ext) + '.txt' count += x f.close()This is what I've tried, amongst some other solutions. I have a feeling that I'm missing something simple.This is different to the other question pointed out above as that's talking about a text file and this is talking about a list.
Very easy do with the itertools.grouper recipe:from itertools import izip_longestn = 2l = ["1", "2", "3", "4", "5", "6"]def grouper(iterable, n, fillvalue=""): args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args)for ind, ele in enumerate(grouper(l[:-n], n)): with open("new_{}.txt".format(ind), "w") as f: f.writelines(ele)If you don't care about losing data just use zip/izip.To not have any empty lines in the last file and still not lose data, as @Jon Clements suggested we can filter:it = iter(l)for num, chunk in enumerate(iter(lambda: list(islice(it, n)), []), 1): with open('output{}'.format(num), 'w') as fout: fout.write("\n".join(chunk))
Xpath returning more than desired (python, urllib, lxml) I am trying to retrieve the first download link from a website, but my code is returning more than that and I'm not sure why.Here is a piece of my code:site_search = "http://mp3skull.com/mp3/tubidy.html"user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0'class MyOpener(FancyURLopener, object): version = user_agentmyopener = MyOpener()page = myopener.open(site_search)html = etree.HTML(page.read())xpath = "//a[@style = 'color:green;'][1]/@href"filtered_html = html.xpath(xpath)print(filtered_html)My code returns:['http://megdadhashem.wapego.ru/files/56727/tubidy_mp3_e2afc5.mp3', 'http://dc357.4shared.com/img/1396413489/41200d37/dlink__2Fdownload_2FOfQCGDtd_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc337.4shared.com/img/1394581159/99fd9e7/dlink__2Fdownload_2FoENbSCE2_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc337.4shared.com/img/1394580769/9e8391f3/dlink__2Fdownload_2Fu4IeKpFK_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc337.4shared.com/img/1386745964/e7f6dcb/dlink__2Fdownload_2F303C_5FUCB_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc337.4shared.com/img/1386568212/616a9b6e/dlink__2Fdownload_2Fcw_5FeT72M_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc540.4shared.com/img/1386000196/b6a127da/dlink__2Fdownload_2FEyTD5P9j_3Ftsid_3D20130107-14410-24515ba/preview.mp3', 'http://dc337.4shared.com/img/1330719927/4f96e0d1/dlink__2Fdownload_2FiYGiVen4_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc242.4shared.com/img/1328992471/f164c1bb/dlink__2Fdownload_2Fsgz8qSBW_3Ftsid_3D00000000-000000-000000/preview.mp3', 'http://dc539.4shared.com/img/1317978255/68f8329d/dlink__2Fdownload_2FSi_5Fka2Pm_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc402.4shared.com/img/1236310800/70345122/dlink__2Fdownload_2FYWU0Aksu_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc150.4shared.com/img/1236293916/681798eb/dlink__2Fdownload_2Fhe_5FMHVoM_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc263.4shared.com/img/1233805806/ab16f2f1/dlink__2Fdownload_2FFp1E7eV8_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc392.4shared.com/img/1194298272/dda6a2b0/dlink__2Fdownload_2Fq1Y3PdRO_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc392.4shared.com/img/1186905892/803a5130/dlink__2Fdownload_2FubH7xctu_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc429.4shared.com/img/1183115738/125793e3/dlink__2Fdownload_2F9Y3zzp-K_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc459.4shared.com/img/1181881278/421221cb/dlink__2Fdownload_2FjstpNTCi_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc453.4shared.com/img/1181881110/18d5b026/dlink__2Fdownload_2F8mmM2BcS_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc120.4shared.com/img/1181875882/25fa514a/dlink__2Fdownload_2F0_5F0UxQuu_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc471.4shared.com/img/1181868760/9121abb8/dlink__2Fdownload_2Fq2ykXJ7Q_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc381.4shared.com/img/1177326344/661ba359/dlink__2Fdownload_2FHztHPN1O_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc201.4shared.com/img/1146076462/de8d83e2/dlink__2Fdownload_2Fqaumhl-G_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc352.4shared.com/img/1142200306/a439f02c/dlink__2Fdownload_2FECiq0Wc8_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc392.4shared.com/img/1137314077/bf9aa3d8/dlink__2Fdownload_2F1ZQOMJ9O_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc362.4shared.com/img/1128611400/34471996/dlink__2Fdownload_2FEF12Czzg_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc196.4shared.com/img/1124868095/a0646612/dlink__2Fdownload_2FruOhPkHz_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc508.4shared.com/img/1124145685/1257f194/dlink__2Fdownload_2FPUqL0qz8_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc337.4shared.com/img/1120296900/3946f5cc/dlink__2Fdownload_2FqsLK3WC9_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc337.4shared.com/img/1091112724/d363d3c4/dlink__2Fdownload_2FylEZuq80_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc394.4shared.com/img/1086814685/542051eb/dlink__2Fdownload_2FiRSSrUEu_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc340.4shared.com/img/1086805965/4423758d/dlink__2Fdownload_2FAXmv12yD_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc397.4shared.com/img/1086804062/6d2abcc4/dlink__2Fdownload_2FIWWI8tmV_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc339.4shared.com/img/1086802960/a99eb9bb/dlink__2Fdownload_2FlxGG5VBU_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc402.4shared.com/img/1086799043/2637e6a9/dlink__2Fdownload_2FSjcCMKQ5_3Ftsid_3D20130107-14410-24515ba/preview.mp3', 'http://dc352.4shared.com/img/1086798986/4d8501c0/dlink__2Fdownload_2Fk1ZHbbCa_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc364.4shared.com/img/1086798016/93968106/dlink__2Fdownload_2FgNBZbBqG_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc253.4shared.com/img/1086794519/4f34e1c4/dlink__2Fdownload_2FBZWIHqC4_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc337.4shared.com/img/1086790487/f7ee8aea/dlink__2Fdownload_2FbvASkRUI_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc337.4shared.com/img/1084754225/3a8f1481/dlink__2Fdownload_2FY2rkufif_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc495.4shared.com/img/1039479528/73f2fa3c/dlink__2Fdownload_2FKWsm3WJ-_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc145.4shared.com/img/975452680/1597c3a2/dlink__2Fdownload_2FQ2VX9l6W_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc252.4shared.com/img/933590669/b1f79b67/dlink__2Fdownload_2F0hbdsF2M_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc120.4shared.com/img/885049589/d1a62f17/dlink__2Fdownload_2FmC_5F1JDXl_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc224.4shared.com/img/884702525/bb0c917b/dlink__2Fdownload_2F46GnfVxK_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc337.4shared.com/img/849169766/fd8d3498/dlink__2Fdownload_2F-hynMHjn_3Ftsid_3D20130107-14410-24515ba/preview.mp3', 'http://dc431.4shared.com/img/844202587/a88f9c21/dlink__2Fdownload_2F85HCohcN_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc184.4shared.com/img/838092829/30bd6ae8/dlink__2Fdownload_2Ffil3BIUA_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc430.4shared.com/img/838091664/324b51b5/dlink__2Fdownload_2FfrzQcwBu_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc441.4shared.com/img/838089810/882d2f3e/dlink__2Fdownload_2FqUMmG5Zl_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc190.4shared.com/img/838088957/cb5b72cb/dlink__2Fdownload_2FiR6VJUSC_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc433.4shared.com/img/838087554/32bca43/dlink__2Fdownload_2Ff3_5Fn7pKY_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc316.4shared.com/img/838086255/c9df8b35/dlink__2Fdownload_2FKMBk8wZI_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc445.4shared.com/img/838084096/55ee8966/dlink__2Fdownload_2FM9Qw6AwI_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc415.4shared.com/img/838082894/9098e62e/dlink__2Fdownload_2F8DGix4I5_3Ftsid_3D20130107-14410-24515ba/preview.mp3', 'http://dc233.4shared.com/img/838081788/99dc7397/dlink__2Fdownload_2Ft-4IKE5C_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc445.4shared.com/img/838081320/6ae1bbf3/dlink__2Fdownload_2FBy95Sp_5FU_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc387.4shared.com/img/838079502/f5b07bd1/dlink__2Fdownload_2FF_5FyXSg9E_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc429.4shared.com/img/842513873/dbab9cf3/dlink__2Fdownload_2FeNLkoppN_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc424.4shared.com/img/827830064/127ba0d9/dlink__2Fdownload_2Fj8emrNnO_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc270.4shared.com/img/822099181/7483e90e/dlink__2Fdownload_2F7xIdA4q6_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc308.4shared.com/img/822092067/d5a08c83/dlink__2Fdownload_2FM26G9oiJ_3Ftsid_3D20130107-14410-24515ba/preview.mp3', 'http://dc198.4shared.com/img/800516614/3d006c3d/dlink__2Fdownload_2Fdz18B2dB_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc388.4shared.com/img/793902768/4eeb6c1d/dlink__2Fdownload_2FnRMBB2bB_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc362.4shared.com/img/788822785/d1e8e98f/dlink__2Fdownload_2Fqs2Ky8y6_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc183.4shared.com/img/788819652/6b419587/dlink__2Fdownload_2FlnWIeFyL_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc391.4shared.com/img/788813387/c7f33dca/dlink__2Fdownload_2FvmPZSPCp_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc198.4shared.com/img/788809769/eb1c5c4b/dlink__2Fdownload_2F0r6tlUex_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc280.4shared.com/img/788804149/2fcd9aa6/dlink__2Fdownload_2FBZSQjBQM_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc280.4shared.com/img/788803303/35275a6b/dlink__2Fdownload_2FsH4BjUMw_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc198.4shared.com/img/781278584/363504d6/dlink__2Fdownload_2Fof2zYynb_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc405.4shared.com/img/717415145/3d6233e1/dlink__2Fdownload_2FkxXODf-m_3Ftsid_3D20130107-14410-24515ba/preview.mp3', 'http://dc376.4shared.com/img/717284773/98545fac/dlink__2Fdownload_2FrreBjY6x_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc397.4shared.com/img/716180972/4a4cac7d/dlink__2Fdownload_2FPLBlw3hR_3Ftsid_3D20130107-14410-24515ba0/preview.mp3', 'http://dc302.4shared.com/img/7074I know it wouldn't be hard to just take the first link from my results, but I'm curious to why I'm getting so many links in the first place.Thank you
//something[1] returns all values that are the first something of their respective parent. (//something)[1] would return the first of all somethings in the document.So you would have to use:(//a[@style = 'color:green;'])[1]/@href
How do I fix 'ImportError: cannot import name IncompleteRead'? When I try to install anything with pip or pip3, I get:$ sudo pip3 install python3-tkTraceback (most recent call last): File "/usr/bin/pip3", line 9, in <module> load_entry_point('pip==1.5.6', 'console_scripts', 'pip3')() File "/usr/lib/python3/dist-packages/pkg_resources.py", line 356, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2476, in load_entry_point return ep.load() File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2190, in load ['__name__']) File "/usr/lib/python3/dist-packages/pip/__init__.py", line 61, in <module> from pip.vcs import git, mercurial, subversion, bazaar # noqa File "/usr/lib/python3/dist-packages/pip/vcs/mercurial.py", line 9, in <module> from pip.download import path_to_url File "/usr/lib/python3/dist-packages/pip/download.py", line 25, in <module> from requests.compat import IncompleteReadImportError: cannot import name 'IncompleteRead'I have a Ubuntu 14.10 system.How can I fix this problem?
While this previous answer might be the reason, this snipped worked for me as a solution (in Ubuntu 14.04):First remove the package from the package manager:# apt-get remove python-pipAnd then install the latest version by side:# easy_install pip(thanks to @Aufziehvogel, @JunchaoGu)
A way to get the path to the user installed packages on Linux and OS X operating systems? (Usable for Python versions between 2.5 - 2.7) >>> import distutils.sysconfig>>> distutils.sysconfig.get_python_lib()/usr/lib/python2.7/dist-packagesBut I want this path: /usr/local/lib/python2.7/dist-packages.I can't use the sysconfig module because it is only supported on python2.7 and there is no PyPI download to that module. so I could not even use a requirements file to let other users download it with pip.So, is there any way to get the path to my installed packages that works for Linux and OS X operating systems? (or even all Unix based os's)
If you need the specific functionality of the get_python_lib function, the source for that module is fairly straightforward and doesn't use any Python 2.7 specific syntax at all; you could simply backport it.You'd basically need the following definitions and two functions:import osimport sysfrom distutils.errors import DistutilsPlatformErrorPREFIX = os.path.normpath(sys.prefix)EXEC_PREFIX = os.path.normpath(sys.exec_prefix)def get_python_version(): """Return a string containing the major and minor Python version, leaving off the patchlevel. Sample return values could be '1.5' or '2.2'. """ return sys.version[:3]def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. If 'prefix' is supplied, use it instead of sys.prefix or sys.exec_prefix -- i.e., ignore 'plat_specific'. """ if prefix is None: prefix = plat_specific and EXEC_PREFIX or PREFIX if os.name == "posix": libpython = os.path.join(prefix, "lib", "python" + get_python_version()) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(prefix, "Lib") else: if get_python_version() < "2.2": return prefix else: return os.path.join(prefix, "Lib", "site-packages") elif os.name == "os2": if standard_lib: return os.path.join(prefix, "Lib") else: return os.path.join(prefix, "Lib", "site-packages") else: raise DistutilsPlatformError( "I don't know where Python installs its library " "on platform '%s'" % os.name)You can cut the long function down to just the branch you need for your platform, of course; for OS X that'd be:def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): if prefix is None: prefix = plat_specific and EXEC_PREFIX or PREFIX libpython = os.path.join(prefix, "lib", "python" + get_python_version()) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages")Note that Debian patches this function to return dist-packages in the default case, this doesn't apply to OS X.
mapping keys (all occur in the given string) to the position in string I am trying to get all indexes of the keys in the string and store them in a dict, so thatevery index has a list of keys mapping to it.Example: string = "loloo and foofoo at the foo bar"keys = "foo", "loo", "bar", "lo"i expect something like{ 0: [lo] 2: [loo, lo] 10: [foo] 13: [foo] 24: [foo] 28: [bar]}My current answer loos the following:def get_index_for_string(string, keys): """ Get all indexes of the keys in the string and store them in a dict, so that every index has a list of keys mapping to it. """ key_in_string = dict((key, [m.start() for m in re.finditer(key, string)]) for key in keys if key in string) index_of_keys = {} for key, values in key_in_string.items(): for value in values: if not value in index_of_keys: index_of_keys[value] = [] index_of_keys[value].append(key) return index_of_keysAny suggestions on how to make this better?
Non-regex approach:using str.find(), str.find() accepts a optional second argument which is the index after which you want to find the word.def indexes(word,strs): ind=0 #base index is 0 res=[] while strs.find(word,ind)!=-1: #loop until str.find() doesn't return -1 ans=strs.find(word,ind) res.append(ans) ind=ans+1 #change base index if the word is found return res strs = "loloo and foofoo at the foo bar"keys = ["foo", "loo", "bar", "lo"]print {x:indexes(x,strs) for x in keys}output:{'lo': [0, 2], 'foo': [10, 13, 24], 'bar': [28], 'loo': [2]}
How can i use my own images to train my CNN neural network in tensorFlow I am currently working on a program that uses a CNN tensorflow neural network and I want to use my own images to train and test it, please I want some advice because I am new in deep learning Thanks.
Download the ronnie package from python.[{pythonpath}\scripts\pip3 ronnie]Construct the training data structure as [label, image pixel] and execute the below code to create the training data.dataFileLoc = os.path.join(dir,"./data/digitalRec/train.csv")orgDF = collector.initial(dataFileLoc)########################################################################### Return Object from buildFormDF are ImgXs and LabelYs in dict Structure{meta.DATA_INPUTXs: imgXs, meta.DATA_LABELYs: labelYs}########################################################################## trainData = collector.buildFromDF(orgDF,batchNum=1, batchSize=30000)
Python 3 Bokeh Heatmap Rect simple example not showing anything in plot I'm trying to color code a simple categorical heatmap using python's Bokeh library. For example, given the following table, I would want to replace each 'A' with a red square and each 'B' with a blue square:AAAABAAAABBBBAAAABBBTo start, I thought the following would produce 2 rows of 10 squares of the same color. but I just get a blank plot. I must be missing a core concept of how to create categorical heatmaps in bokeh. To start, I was trying to mimic an example on the bokeh site:https://docs.bokeh.org/en/latest/docs/gallery/categorical.htmlDoes anyone see what I'm missing? (This is a simple example. I have many rows with hundreds of columns that I need to color by category.)from bokeh.plotting import figure, show, output_filehm = figure()colors = ['#2765a3' for x in range(20)]x_input = [x for x in range(10)]y_input = ['a', 'b']hm.rect(x_input, y_input, width = 1, height = 1, color = colors)output_file('test.html)show(hm)
You need to create specific coordinates for each rect. If there are 2 possible values on the y-axis, and 10 possible values on the x-axis, then there are 20 possible unique pairs of coordinates for all the rects (i.e. the cross product of those two lists). For example:(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), ...If you split each of these tuples into an x-coordinate and y-coordinate, and collect x's and y's into their own lists, they you can see why there must be both 20 x-coordinates and 20 y-coordinates. Additionally, for categorical coordinates, you have to tell figure what they are. Here is your code updated:from bokeh.plotting import figure, showcolors = ['#2765a3' for x in range(20)]x = list(range(10)) * 2y = ['a'] * 10 + ['b'] * 10hm = figure(y_range=('a', 'b'))hm.rect(x, y, width=1, height=1, fill_color=colors, line_color="white")show(hm)The User's Guide section on Categorical Data has much more information on how to use categoricals in Bokeh, including complete examples of heat maps
Save rows of a bidimensional numpy array in another array I have a bidimensional np array V (100000x50). I want to create a new array V_tgt in which I keep just certain rows of V, so the dimension will be (ix50). It may be easy to do it but I tried different things and it seems to save just the first of the 50 elements. My code is the following:V_tgt = np.array([])for i in IX_items: if i in IX_tgt_items: V_tgt=np.append(V_tgt, V[i])I tried with functions such as insert and delete as well but it didn't work.How can I save all the values and create an array with the right dimension? Any help is really appreciated.
From your comments I assume that you have some kind of list of target indices (in my example tgt_idx1 and tgt_idx2)that tells you which elements to take from V. You could do something like this:import numpy as npV = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])tgt_idx1 = np.array([1, 2, 3])tgt_idx2 = np.array([1, 3])mask = []for i, elem in enumerate(V): inTargets = i in tgt_idx1 and i in tgt_idx2 mask.append(inTargets)print maskV_tgt = V[mask]print V_tgtThis prints[False, True, False, True][[ 4 5 6] [10 11 12]]
Is there any Celeryd or Celery (for Django/Python) type altenative for Symfony 2 framework I am a big fan of Celery for executing scheduled tasks in Django. I am now using Symfony 2 and see that it is almost similar to Django framework.I wonder if there is something similar to Celery in Symfony for scheduling task queues.
Celery is providing a simple layer to use messaging. It makes the task of building async services easy. Interestingly the concept is not new. It is already available in form of standard protocol like AMQP. Documentation available at http://php.net/manual/en/book.amqp.phpAlthough I can't vouch for it but potentially you could hookup PHP and Python code as publisher and subscriber, thus using Celery for doing the task while PHP code could issue it.
Python parsing log file to extract events in real time I've a process that is logging messages to a file. I want to implement another process (in Python) that parses these logs (as they are written to the file), filters the lines that I'm interested in and then performs certain actions based on the state of the first process.I was wondering before I go ahead and write something on my own if there is a library in Python that does something like this. Also, ideas regarding how implement something like this Python would be appreciated. Thanks.
C programs usually seek to the current position to clear any “end of file” flags. But as @9000 correctly pointed out, python apparently takes care of this, so you can read from the same file repeatedly even if it has reached end of file.You might have to take care of incomplete lines, though. If your application writes its log in pieces, then you want to make sure that you handle whole lines, and not those pieces. The following code will accomplish that:f = open('some.log', 'r')while True: line = '' while len(line) == 0 or line[-1] != '\n': tail = f.readline() if tail == '': time.sleep(0.1) # avoid busy waiting # f.seek(0, io.SEEK_CUR) # appears to be unneccessary continue line += tail process(line)
Expand a list of dictionaries into a readable format My description/title may be lacking, as I am new to python, however as an example, I currently have data like below stored in the variable bunnies: [{'rabbithole': {'holenumber': 1, 'family': 'roger', 'status': 'elite'}, 'food': 'steak', 'children': 108, 'job': 'chef', 'etc': 'etc', 'etc': 'etc'}, {'rabbithole': {'holenumber': 2, 'family': 'roger', 'status': 'elite'}, 'food': 'steak', 'children': 108, 'job': 'chef', 'etc': 'etc', 'etc': 'etc'}, {'rabbithole': {'holenumber': 3, 'family': 'roger', 'status': 'elite'}, 'food': 'steak', 'children': 108, 'job': 'chef', 'etc': 'etc', 'etc': 'etc'}]my goal is to break it into a readable format like this:{'rabbithole': { 'holenumber': 1, 'family': 'roger', 'status': 'elite'}, 'food': 'steak', 'children': 108, 'job': 'chef', 'etc': 'etc', 'etc': 'etc'}...What I have so far is this...def virt(list): for i in list: print i print "\n"virt(bunnies)which gives me a new line for each rabbithole listing...so I tried this:import redef virt(list) for i in list: match = re.search( r'{|.*: {.*},|.*:.*,|}',i, re.I) print i.replace(match,match+"\n")virt(bunnies)Unfortunately this didn't do anything except throw an error from the re library.File "/usr/lib64/python2.7/re.py", line 146, in search return _compile(pattern, flags).search(string)I haven't looked too much into that error yet, but I have a feeling I was going in the wrong direction anyway.Can anyone help point me in the right direction?
You can use the json Python module:import jsonprint json.dumps(your_data, sort_keys=True, indent=4, separators=(',', ': '))Example:a=json.dumps([{'rabbithole': {'holenumber': 1, 'family': 'roger', 'status': 'elite'}, 'food': 'steak', 'children': 108, 'job': 'chef', 'etc': 'etc', 'etc': 'etc'}, {'rabbithole': {'holenumber': 2, 'family': 'roger', 'status': 'elite'}, 'food': 'steak', 'children': 108, 'job': 'chef', 'etc': 'etc', 'etc': 'etc'}, {'rabbithole': {'holenumber': 3, 'family': 'roger', 'status': 'elite'}, 'food': 'steak', 'children': 108, 'job': 'chef', 'etc': 'etc', 'etc': 'etc'}], sort_keys=True, indent=4, separators=(',', ': '))>>> print a[ { "children": 108, "etc": "etc", "food": "steak", "job": "chef", "rabbithole": { "family": "roger", "holenumber": 1, "status": "elite" } }, { "children": 108, "etc": "etc", "food": "steak", "job": "chef", "rabbithole": { "family": "roger", "holenumber": 2, "status": "elite" } }, { "children": 108, "etc": "etc", "food": "steak", "job": "chef", "rabbithole": { "family": "roger", "holenumber": 3, "status": "elite" } }]
why will I get a "TypeError: object of type 'NoneType' has no len()"? words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes',"don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under']def requirement(word): onelist = [] if word in words: return(len(onelist.append(word)))print(map(requirement('look'), words))ErrorTypeError: object of type 'NoneType' has no len()I want to practise the function "map". But it seems that I made a mistake when I use len().
The function list.append() modifies a list in place and returns None. So the linereturn(len(onelist.append(word)))is trying to return the length of None, which should obviously throw a TypeError. Try something like onelist.append(word)return(len(onelist))
python pandas: passing in dataframe to df.apply Long time user of this site but first time asking a question! Thanks to all of the benevolent users who have been answering questions for ages :)I have been using df.apply lately and ideally want to pass a dataframe into the args parameter to look something like so: df.apply(testFunc, args=(dfOther), axis = 1)My ultimate goal is to iterate over the dataframe I am passing in the args parameter and check logic against each row of the original dataframe, say df , and return some value from dfOther . So say I have a function like this:def testFunc(row, dfOther): for index, rowOther in dfOther.iterrows(): if row['A'] == rowOther[0] and row['B'] == rowOther[1]: return dfOther.at[index, 'C']df['OTHER'] = df.apply(testFunc, args=(dfOther), axis = 1)My current understanding is that args expects a Series object, and so if I actually run this we get the following error:ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().However before I wrote testFunc which only passes in a single dataframe, I had actually written priorTestFunc, which looks like this... And it works!def priorTestFunc(row, dfOne, dfTwo): for index, rowOne in dfOne.iterrows(): if row['A'] == rowOne[0] and row['B'] == rowOne[1]: return dfTwo.at[index, 'C']df['OTHER'] = df.apply(testFunc, args=(dfOne, dfTwo), axis = 1)So to my dismay I have been coming into the habit of writing testFunc like so and it has been working as intended:def testFunc(row, dfOther, _): for index, rowOther in dfOther.iterrows(): if row['A'] == rowOther[0] and row['B'] == rowOther[1]: return dfOther.at[index, 'C']df['OTHER'] = df.apply(testFunc, args=(dfOther, _), axis = 1)I would really appreciate if someone could let me know why this would be the case and maybe errors that I will be prone to, or maybe another alternative for solving this kind of problem!!EDIT: As requested by the comment: My dfs generally look like the below.. They will have two matching columns and will be returning a value from the dfOther.at[index, column] I have considered pd.concat([dfOther, df]) however I will be running an algorithm testing conditions on df and then updating it accordingly from specific values on dfOther(which will also be updating) and I would like df to be relatively neat, as opposed to making a multindex and throwing just about everything in it. Also I am aware df.iterrows is in general slow, but these dataframes will be about 500 rows at the max, so scalability isn't really a massive concern for me at the moment.dfOut[10]: A B C0 foo bur 60001 foo bur 70002 foo bur 80003 bar kek 90004 bar kek 100005 bar kek 11000dfOtherOut[12]: A B C0 foo bur 10001 foo bur 20002 foo bur 30003 bar kek 40004 bar kek 50005 bar kek 6000
The error is in this line: File "C:\Anaconda3\envs\p2\lib\site-packages\pandas\core\frame.py", line 4017, in apply if kwds or args and not isinstance(func, np.ufunc):Here, if kwds or args is checking whether the length of args passed to apply is greater than 0. It is a common way to check if an iterable is empty:l = []if l: print("l is not empty!")else: print("l is empty!") l is empty!l = [1]if l: print("l is not empty!")else: print("l is empty!") l is not empty!If you had passed a tuple to df.apply as args, it would return True and there wouldn't be a problem. However, Python does not interpret (df) as a tuple:type((df))Out[39]: pandas.core.frame.DataFrameIt is just a DataFrame/variable inside parentheses. When you type if df:if df: print("df is not empty")Traceback (most recent call last): File "<ipython-input-40-c86da5a5f1ee>", line 1, in <module> if df: File "C:\Anaconda3\envs\p2\lib\site-packages\pandas\core\generic.py", line 887, in __nonzero__ .format(self.__class__.__name__))ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().You get the same error message. However, if you use a comma to indicate that it'a tuple, it works fine:if (df, ): print("tuple is not empty")tuple is not emptyAs a result, adding a comma to args=(dfOther) by making it a singleton should solve the problem.df['OTHER'] = df.apply(testFunc, args=(dfOther, ), axis = 1)
Python class input argument I am new to OOP. My idea was to implement the following class:class name(object, name): def __init__(self, name): print nameThen the idea was to create two instances of that class:person1 = name("jean")person2 = name("dean")I know, that is not possible, but how can I pass an input-argument into an instance of a class?
The problem in your initial definition of the class is that you've written:class name(object, name):This means that the class inherits the base class called "object", and the base class called "name". However, there is no base class called "name", so it fails. Instead, all you need to do is have the variable in the special init method, which will mean that the class takes it as a variable.class name(object): def __init__(self, name): print nameIf you wanted to use the variable in other methods that you define within the class, you can assign name to self.name, and use that in any other method in the class without needing to pass it to the method.For example:class name(object): def __init__(self, name): self.name = name def PrintName(self): print self.namea = name('bob')a.PrintName()bob
Cannot use im.getcolors I was trying this code:im = Image.open("myimage") colors = im.getcolors()print colorsand it returns "None". So I tried this:im = Image.open("myimage") size = im.size colors = im.getcolors(size[0]*size[1]) and when I "print colors" with this, Python basically crashes. I'm not using a huge image. How can I make it work?My goal is to know from an image how many pixels are closer to black and how many px are closer to white. Maybe im.getcolors it's not the right solution?
The image has to be in RGB mode in order to use getcolors. So try: im_rgb = im.convert('RGB') colors = im_rgb.getcolors() print colors
Python TypeError: cannot convert dictionary update sequence element #1 to a sequence doing some data wrangling from an example in O'Reilly's "Python for Data Analysis."We start with data of the following format:In [108]: data.CATEGORY[:5]Out[108]: 0 1. Urgences | Emergency, 3. Public Health, 4 1. Urgences | Emergency, 5 5e. Communication lines down, 6 4. Menaces | Security Threats, 4e. Assainissem...7 4. Menaces | Security Threats, Name: CATEGORY, dtype: objectThe book then lays out a procedure for removing the periods and '|' from each entry with the goal of creating a dictionary, using the following definitions;def get_all_categories(cat_series): cat_sets = (set(to_cat_list(x)) for x in cat_series) return sorted(set.union(*cat_sets))def get_english(cat): code, names = cat.split('.') if '|' in names: names = names.split(' | ')[1] return code, names.strip()The first step goes fine, creating the list of unique categories;In [109]: all_cats = get_all_categories(data.CATEGORY)In [110]: all_cats[:5]Out[110]: ['1. Urgences | Emergency', '1a. Highly vulnerable', '1b. Urgence medicale | Medical Emergency', '1c. Personnes prises au piege | People trapped', '1d. Incendie | Fire']However, using the second definition results in the following;In [116]: english_mapping = dict(get_english(x) for x in all_cats)---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-116-e69c3419c341> in <module>()----> 1 english_mapping = dict(get_english(x) for x in all_cats)TypeError: cannot convert dictionary update sequence element #1 to a sequenceA little help for a Python noob please :)
Here is the solution:"cannot convert dictionary update sequence element #1 to a sequence"---because there is null value in the expression "get_english(x) for x in all_cats", so it can't be converted into a dictionary;Why? def get_english(cat): code,names=cat.split('.') if '|' in names: names=names.split('|')[1] return code,names.strip()----Here is the problem,the last line shouldn't indent,if not,you will get some value null.
python requests: how can I get the "exception code" I am using "requests (2.5.1)" .now I want to catch the exception and return an dict with some exception message,the dict I will return is as following:{ "status_code": 61, # exception code, "msg": "error msg",}but now I can't get the error status_code and error message,I try to usetry:.....except requests.exceptions.ConnectionError as e:response={ u'status_code':4040, u'errno': e.errno, u'message': (e.message.reason), u'strerror': e.strerror, u'response':e.response, }but it's too redundancy,how can I get the error message simplicity?anyone can give some idea?
try: #the codes that you want to catch errors goes hereexcept: print ("an error occured.")This going to catch all errors, but better you define the errors instead of catching all of them and printing special sentences for errors.Like;try: #the codes that you want to catch errors goes hereexcept SyntaxError: print ("SyntaxError occured.")except ValueError: print ("ValueError occured.")except: print ("another error occured.")Or;try: #the codes that you want to catch errors goes here except Exception as t: print ("{} occured.".format(t))
R to Python pandas numpy.where conversion what is the best way to write the following R code in Python (pandas dataframe) using numpy.where syntax.Data$new = ifelse(Data$Diff > 1.652*Data$Diff10, 1, ifelse(Data$Diff < 3.95*Data$Diff10, -1, 0 ))
You can use:Data['new'] = np.where(Data['Diff'] > 1.652*Data['Diff10'], 1, np.where(Data['Diff'] < 3.95*Data['Diff10'], -1, 0 ))EDIT:It seems code above have logic error, because never return 0.Maybe need:Data = pd.DataFrame({'Diff':[2,4,.5], 'Diff10':[1,1,1]})print (Data) Diff Diff100 2.0 11 4.0 12 0.5 1Data['new'] = np.where(Data['Diff'] < 1.652*Data['Diff10'], 2, np.where(Data['Diff'] > 3.95*Data['Diff10'], 3, 4 ))print (Data) Diff Diff10 new0 2.0 1 41 4.0 1 32 0.5 1 2
How to fix overfitting in Elman neural network? I'm training elman network with neurolab python library and my net doesn't work properly.Training input vectors: http://pastebin.com/urQX2eEA Training target vector: http://pastebin.com/1JQh1xZvSample vector to test a network: http://pastebin.com/jprZhBHaBut while training it is showing too big errors:Epoch: 100; Error: 23752443150.672318;Epoch: 200; Error: 284037904.0305649;Epoch: 300; Error: 174736152.57367808;Epoch: 400; Error: 3318952.136089243;Epoch: 500; Error: 299017.4471083774;Epoch: 600; Error: 176600.0906688521;Epoch: 700; Error: 176599.32080188877;Epoch: 800; Error: 185178.21132511366;Epoch: 900; Error: 177224.2950528976;Epoch: 1000; Error: 176632.86797784362;The maximum number of train epochs is reachedAs a result network fails on testing sample.Original MICEX:1758,971626,181688,341609,191654,5516691733,171642,971711,531771,05Predicted MICEX:[ 1237.59155306] [ 1237.59155306] [ 1237.59155306] [ 1237.59155306] [ 1237.59155306] [ 1237.59155306] [ 1237.59155306] [ 1237.59155306] [ 1237.59155306] [ 1237.59155306]Here is my code:import neurolab as nlimport numpy as np# Create train samplesMICEX = [421.08,455.44,430.3,484,515.17,468.85,484.73,514.71,551.72,591.09,644.64,561.78,535.4,534.84,502.81,549.28,611.03,632.97,570.76,552.22,575.74,635.38,598.04,593.88,603.89,639.98,700.65,784.28,892.5,842.52,944.55,1011,1171.44,1320.83,1299.19,1486.85,1281.5,1331.39,1380.24,1448.72,1367.24,1426.83,1550.71,1693.47,1656.97,1655.19,1698.08,1697.28,1570.34,1665.96,1734.42,1677.02,1759.44,1874.73,1850.64,1888.86,1574.33,1660.42,1628.43,1667.35,1925.24,1753.67,1495.33,1348.92,1027.66,731.96,611.32,619.53,624.9,666.05,772.93,920.35,1123.38,971.55,1053.3,1091.98,1197.2,1237.18,1284.95,1370.01,1419.42,1332.64,1450.15,1436.04,1332.62,1309.31,1397.12,1368.9,1440.3,1523.39,1565.52,1687.99,1723.42,1777.84,1813.59,1741.84,1666.3,1666.59,1705.18,1546.05,1366.54,1498.6,1499.62,1402.02,1510.91,1594.32,1518.29,1474.14,1312.24,1386.89,1406.36,1422.38,1459.01,1423.46,1405.19,1477.87,1547.18,1487.46,1440.02,1386.69,1343.99,1331.24,1377.6,1364.54,1463.13,1509.62,1479.35,1503.39,1454.05,1444.71,1369.29,1306.01,1432.03,1476.38,1379.61,1400.71,1411.07,1488.47,1533.68,1396.61,1647.69]Brent = [26.8,28.16,28.59,30.05,28.34,27.94,28.76,30.48,29.51,33.01,32.36,35.12,36.98,33.51,41.6,39.33,47.08,48.78,44.03,40.24,45.87,50.14,53.05,49.33,49.83,54.85,59.7,66.68,62.56,58.35,53.41,58.87,65.43,60.05,64.94,72,69,73.28,75.16,69.64,61.37,56.97,64.42,60.13,57.21,60.66,68.42,67.28,68.82,73.26,78.05,73.53,81.75,91.14,88,93.85,91.98,100.04,100.51,112.71,128.27,140.3,123.96,115.17,98.96,65.6,53.49,45.59,45.93,45.84,48.68,50.64,65.8,69.42,71.52,69.32,68.92,75.09,78.36,77.93,71.18,78.03,82.17,87.35,74.6,74.66,78.26,74.42,82.11,83.26,85.45,94.59,100.56,112.1,117.17,126.03,116.68,111.8,117.54,114.49,102.15,109.19,110.37,107.22,111.16,123.04,122.8,119.47,101.62,97.57,104.62,114.92,112.14,108.4,111.17,111.11,114.56,111,109.89,101.74,100.15,101.5,107.7,114.45,108.2,108.9,110.11,110.9,105.79,108.65,107.7,108.14,109.49,112.4,105.52,103.11,94.8,85.96,68.34,57.54,52.95]DJIA = [8850.26,8985.44,9233.8,9415.82,9275.06,9801.12,9782.46,10453.92,10488.07,10583.92,10357.7,10225.57,10188.45,10435.48,10139.71,10173.92,10080.27,10027.47,10428.02,10783.01,10489.94,10766.23,10503.76,10192.51,10467.48,10274.97,10640.91,10481.6,10568.7,10440.07,10805.87,10717.5,10864.86,10993.41,11109.32,11367.14,11168.31,11150.22,11185.68,11381.15,11679.07,12080.73,12221.93,12463.15,12621.69,12268.63,12354.35,13062.91,13627.64,13408.62,13211.99,13357.74,13895.63,13930.01,13371.72,13264.82,12650.36,12266.39,12262.89,12820.13,12638.32,11350.01,11378.02,11543.96,10850.66,9325.01,8829.04,8776.39,8000.86,7062.93,7608.92,8168.12,8500.33,8447,9171.61,9496.28,9712.28,9712.73,10344.84,10428.05,10067.33,10325.26,10856.63,11008.61,10136.63,9774.02,10465.94,10014.72,10788.05,11118.49,11006.02,11577.51,11891.93,12226.34,12319.73,12810.54,12569.79,12414.34,12143.24,11613.53,10913.38,11955.01,12045.68,12217.56,12632.91,12952.07,13212.04,13213.63,12393.45,12880.09,13008.68,13090.84,13437.13,13096.46,13025.58,13104.14,13860.58,14054.49,14578.54,14839.8,15115.57,14909.6,15499.54,14810.31,15129.67,15545.75,16086.41,16576.66,15698.85,16321.71,16457.66,16580.84,16717.17,16826.6,16563.3,17098.45,17042.9,17390.52,17828.24,17823.07,17164.95]CAC_40 = [2991.75,3084.1,3210.27,3311.42,3134.99,3373.2,3424.79,3557.9,3638.44,3725.44,3625.23,3674.28,3669.63,3732.99,3647.1,3594.28,3640.61,3706.82,3753.75,3821.16,3913.69,4027.16,4067.78,3908.93,4120.73,4229.35,4451.74,4399.36,4600.02,4436.45,4567.41,4715.23,4947.99,5000.45,5220.85,5188.4,4930.18,4965.96,5009.42,5165.04,5250.01,5348.73,5327.64,5541.76,5608.31,5516.32,5634.16,5930.77,6104,6054.93,5751.08,5662.7,5715.69,5841.08,5667.5,5614.08,4871.8,4790.66,4707.07,4996.54,5014.28,4425.61,4392.36,4485.64,4027.15,3487.07,3262.68,3217.97,2962.37,2693.96,2803.94,3159.85,3273.55,3138.93,3426.27,3657.72,3794.96,3601.43,3684.75,3936.33,3737.19,3708.8,3974.01,3816.99,3507.56,3442.89,3643.14,3476.18,3715.18,3833.5,3610.44,3804.78,4005.5,4110.35,3989.18,4106.92,4006.94,3980.78,3672.77,3256.76,2981.96,3242.84,3154.62,3159.81,3298.55,3447.94,3423.81,3212.8,3005.48,3196.65,3291.66,3413.07,3354.82,3429.27,3557.28,3641.07,3732.6,3723,3731.42,3856.75,3948.59,3738.91,3992.69,3933.78,4143.44,4299.89,4295.21,4295.95,4165.72,4408.08,4391.5,4487.39,4519.57,4422.84,4246.14,4381.04,4426.76,4233.09,4390.18,4263.55,4604.25]SSEC = [1576.26,1486.02,1476.74,1421.98,1367.16,1348.3,1397.22,1497.04,1590.73,1675.07,1741.62,1595.59,1555.91,1399.16,1386.2,1342.06,1396.7,1320.54,1340.77,1266.5,1191.82,1306,1181.24,1159.15,1060.74,1080.94,1083.03,1162.8,1155.61,1092.82,1099.26,1161.06,1258.05,1299.03,1298.3,1440.22,1641.3,1672.21,1612.73,1658.64,1752.42,1837.99,2099.29,2675.47,2786.34,2881.07,3183.98,3841.27,4109.65,3820.7,4471.03,5218.82,5552.3,5954.77,4871.78,5261.56,4383.39,4348.54,3472.71,3693.11,3433.35,2736.1,2775.72,2397.37,2293.78,1728.79,1871.16,1820.81,1990.66,2082.85,2373.21,2477.57,2632.93,2959.36,3412.06,2667.74,2779.43,2995.85,3195.3,3277.14,2989.29,3051.94,3109.11,2870.61,2592.15,2398.37,2637.5,2638.8,2655.66,2978.83,2820.18,2808.08,2790.69,2905.05,2928.11,2911.51,2743.47,2762.08,2701.73,2567.34,2359.22,2468.25,2333.41,2199.42,2292.61,2428.49,2262.79,2396.32,2372.23,2225.43,2103.63,2047.52,2086.17,2068.88,1980.12,2269.13,2385.42,2365.59,2236.62,2177.91,2300.59,1979.21,1993.8,2098.38,2174.66,2141.61,2220.5,2115.98,2033.08,2056.3,2033.31,2026.36,2039.21,2048.33,2201.56,2217.2,2363.87,2420.18,2682.83,3234.68,3210.36]Brent_sample = [62.48, 55.1, 66.8, 65.19, 63.14, 51.85, 53.12, 48.44, 49.5, 44.5]DJIA_sample = [18132.7, 17776.12, 17840.52, 18010.68, 17619.51, 17689.86, 16528.03, 16284.7, 17663.54, 17719.92]CAC_40_sample = [4922.99, 5031.47, 5042.84, 5084.08, 4812.24, 5081.73, 4652.34, 4453.91, 4880.18, 4951.83]SSEC_sample = [3310.3, 3747.9, 4441.66, 4611.74, 4277.22, 3663.73, 3205.99, 3052.78, 3382.56, 3445.4]MICEX = np.asarray(MICEX)Brent = np.asarray(Brent)DJIA = np.asarray(DJIA)CAC_40 = np.asarray(CAC_40)SSEC = np.asarray(SSEC)Brent_sample = np.asarray(Brent_sample)DJIA_sample = np.asarray(DJIA_sample)CAC_40_sample = np.asarray(CAC_40_sample)SSEC_sample = np.asarray(SSEC_sample)size = len(MICEX)inp = np.vstack((Brent, DJIA, CAC_40, SSEC)).Ttar = MICEX.reshape(size, 1)smp = np.vstack((Brent_sample, DJIA_sample, CAC_40_sample, SSEC_sample)).T# Create network with 2 layers and random initializednet = nl.net.newelm( [[min(inp[:, 0]), max(inp[:, 0])], [min(inp[:, 1]), max(inp[:, 1])], [min(inp[:, 2]), max(inp[:, 2])], [min(inp[:, 3]), max(inp[:, 3])] ], [46, 1], [nl.trans.TanSig(), nl.trans.PureLin()] # SatLinPrm(0.00000001, 421.08, 1925.24) )# Set initialized functions and initnet.layers[0].initf = nl.init.InitRand([-0.1, 0.1], 'wb')net.layers[1].initf = nl.init.InitRand([-0.1, 0.1], 'wb')net.init()# Changing training method# net.trainf = nl.train.train_cg# Train networkerror = net.train(inp, tar, epochs=1000, show=100, goal=0.02)# Simulate networkout = net.sim(smp)print(smp)print('MICEX predictions for the next 10 periods:\n', out)Does anybody know a solution of this problem?
First of all this is not overfitting. You are underfitting, you do not even converge for training cases. Can't you just increase number of epochs? Let the net converge.
Why does my data change into NaN in Task4? Why does my data change into NaN in task 4? I also tried using .loc[], but that still doesn't work. I need to be able to use the numbers.dec6 = pd.read_csv('coinmarketcap_06122017.csv', header=0)market_cap_raw = dec6[['id', 'market_cap_usd']]print(market_cap_raw.describe())#print(market_cap_raw)market_cap_raw.count()#Task 3cap = market_cap_raw.query('market_cap_usd > 0')cap.count()print(cap.describe())#Task 4cap10 = cap.head(10).reindex(index=cap['id'])print(cap10.describe())Result: market_cap_usdcount 1.144000e+03mean 4.861599e+08std 6.713982e+09min 1.200000e+0125% 7.513858e+0550% 6.856627e+0675% 4.043108e+07max 1.862130e+11 market_cap_usdcount 1.144000e+03mean 4.861599e+08std 6.713982e+09min 1.200000e+0125% 7.513858e+0550% 6.856627e+0675% 4.043108e+07max 1.862130e+11 market_cap_usdcount 0.0mean NaNstd NaNmin NaN25% NaN50% NaN75% NaNmax NaNThe last print results in NaN.
The re_index() method is causing the data to change to NaN.
Reading File in Python and putting column into Array I am fairly new to Python and am working with the NLTK to produce a sound dynamic Text Analyzer. I have a .csv file with member information, survey response number, and survey response text that I need open and read. I have: import csvimport codecsf = open('testresponseFS.csv')raw = f.read()print rawThis may be a bit over my head, but I want to read each row in the file to keep all information intact, and read a specific cell "response" which contains text response. I have been suggested put that specific column in an array, iterating through the whole column with array values; therefore I can run functions on each item in that array, and eventually append those values back to the .csv file next to the "response".
import csv# read datawith open('testresponseFS.csv', 'rb') as inf: incsv = csv.reader(inf) header = next(incsv) data = [row for row in incsv]# process dataheader.append('Comments')response_column = 4for row in data: response = row[response_column] newval = response[:4].lower() # or whatever you do to it row.append(newval) # write data back outwith open('finaldata.csv', 'wb') as outf: outcsv = csv.writer(outf) outcsv.writerow(header) outcsv.writerows(data)
Itertools to create a list and work out probability I am trying to work out the probability of 'Susie' winning a match.Probability of 'Susie' winning a game = 0.837Probability of 'Bob' winning a game = 0.163If the first person to win n games wins a match, what is the smallest value of n such that Susie has a better than 0.9 chance of winning the match?So far I have this code:import itertoolsW = 0.837L = 0.163for product in itertools.product(['W','L'], repeat=3): #3=number of games print productWhich prints:('W', 'W', 'W')('W', 'W', 'L')('W', 'L', 'W')('W', 'L', 'L')('L', 'W', 'W')('L', 'W', 'L')('L', 'L', 'W')('L', 'L', 'L')I then want to use these results to work out the probability of 'Susie' winning the match overall.I have worked out this problem on paper, the more games played, the more chance there is of 'Susie' winning the match.
You also need to loop over values of n. Also note that 'first to n' is the same as 'best out of 2n-1'. So we can say m = 2 * n - 1 and see who wins the most games of that set. max(set(product), key=product.count) is a short but opaque way of working out who won the most games. Also, why bother with representing the probabilities with strings and then using a dictionary to read them, when you can store the values in your tuples directly.import itertoolspWin = 0 #the probability susie wins the matchn = 0while pWin<0.9: n += 1 m = 2 * n - 1 pWin = 0 for prod in itertools.product([0.837,0.163], repeat=m): #test who wins the match if max(set(prod), key=prod.count) == 0.837: pWin += reduce(lambda total,current: total * current, prod)print '{} probability that Susie wins the match, with {} games'.format(pWin, n)
unable to install face_recognition library for python I'm trying to install dbLib Library for executing python face_recognition as mentioned here https://github.com/ageitgey/face_recognition/issues/175#issuecomment-355899230as I execute the command python setup.py install --yes USE_AVX_INSTRUCTIONSit says the following C:\Python\dblib\dlib-master>python setup.py install --yes USE_AVX_INSTRUCTIONS --yes DLIB_USE_CUDArunning installrunning bdist_eggrunning buildDetected Python architecture: 32bitDetected platform: win32Removing build directory C:\Python\dblib\dlib-master\./tools/python/buildConfiguring cmake ...-- Building for: Visual Studio 14 2015CMake Error in CMakeLists.txt: Failed to run MSBuild command: C:/Program Files (x86)/MSBuild/14.0/bin/MSBuild.exe to get the value of VCTargetsPath: Microsoft (R) Build Engine version 14.0.25420.1 Copyright (C) Microsoft Corporation. All rights reserved. Build started 1/9/2018 12:16:21 AM. Project "C:\Python\dblib\dlib-master\tools\python\build\CMakeFiles\3.10.0\VCTargetsPath.vcxproj" on node 1 (default targets). C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\Win32\PlatformToolsets\v140\Toolset.targets(34,5): error MSB8036: The Windows SDK version 8.1 was not found. Install the required version of Windows SDK or change the SDKversion in the project property pages or by right-clicking the solution and selecting "Retarget solution". [C:\Python\dblib\dlib-master\tools\python\build\CMakeFiles\3.10.0\VCTargetsPath.vcxproj] Done Building Project "C:\Python\dblib\dlib-master\tools\python\build\CMakeFiles\3.10.0\VCTargetsPath.vcxproj" (default targets) -- FAILED. Build FAILED. "C:\Python\dblib\dlib-master\tools\python\build\CMakeFiles\3.10.0\VCTargetsPath.vcxproj" (default target) (1) -> (Desktop_PlatformPrepareForBuild target) -> C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\Win32\PlatformToolsets\v140\Toolset.targets(34,5): error MSB8036: The Windows SDK version 8.1 was not found. Install the required version of Windows SDK or change the SDK version in the project property pages or by right-clicking the solution and selecting "Retarget solution". [C:\Python\dblib\dlib-master\tools\python\build\CMakeFiles\3.10.0\VCTargetsPath.vcxproj] 0 Warning(s) 1 Error(s) Time Elapsed 00:00:00.09 Exit code: 1-- Configuring incomplete, errors occurred!See also "C:/Python/dblib/dlib-master/tools/python/build/CMakeFiles/CMakeOutput.log".error: cmake configuration failed!please let me know what I'm doing wrong here
I was able to install it with pip (through the pip install face_recognition command) after I had Boost and CMake installed.to install face_recognition install Boost from here hereand then install Cmake if both get successful then you can directly install it.and you also need to have visual studio C++ packages to ensure boost work properly
Python - Array becomes scalar variable when passed into function I am trying to create a simple python script that when given a photo, first converts it to greyscale and then will band it into a number of colors. For example if the number of colours passed in is 2, the greyscale image will be changed so that each pixel is either pitch black (0) or bright white (255). However, when calling my function 'getGreyscaleValue' used to determine the greyscale value of each pixel, I am getting an error. It seems that when passing the arrays, 'bandWidthArray' and 'colorsArray' into the function, they change from arrays to a scalar variable '0.0'. Running the following script and observing the printed values, should replicate the problem:import numpy as npfrom PIL import ImagenumberOfColors = 2;greyscaleRange=255;col = Image.open("IMG_5525.JPG")gray = col.convert('L') # Make grayscaley=np.asarray(gray.getdata(),dtype=np.float64).reshape((gray.size[1],gray.size[0]))def getGreyScaleValue(x, bandWidthArray, colorsArray): print(bandWidthArray) print(colorsArray) for i in range(1, bandWidthArray.len): if(int(round(x))<int(round(bandWidthArray[i]))): return colorsArray[i-1] return 255bandWidthArray = np.linspace(0, greyscaleRange, numberOfColors+1)colorsArray = np.linspace(0, greyscaleRange, numberOfColors)getGreyScaleValue = np.vectorize(getGreyScaleValue)print(bandWidthArray)print(colorsArray)y = getGreyScaleValue(y, bandWidthArray, colorsArray)y=np.asarray(y,dtype=np.uint8) #if values still in range 0-255!w=Image.fromarray(y,mode='L')w.save('out.jpg')Stack trace is as follows: PS C:\python\pythonimages> python imgChange1.py[ 0. 127.5 255. ][ 0. 255.]0.00.0Traceback (most recent call last): File "imgChange1.py", line 27, in <module> y = getGreyScaleValue(y, bandWidthArray, colorsArray) File "C:\Users\Jack\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\lib\function_base.py", line 2734, in __call__ return self._vectorize_call(func=func, args=vargs) File "C:\Users\Jack\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\lib\function_base.py", line 2804, in _vectorize_call ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args) File "C:\Users\Jack\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\lib\function_base.py", line 2764, in _get_ufunc_and_otypes outputs = func(*inputs) File "imgChange1.py", line 15, in getGreyScaleValue for i in range(1, bandWidthArray.len):AttributeError: 'numpy.float64' object has no attribute 'len'
Change:for i in range(1, bandWidthArray.len):to:for i in range(1, len(bandWidthArray)):NumPy arrays don't have a len method.Furthermore, don't vectorize your function. Remove this line:getGreyScaleValue = np.vectorize(getGreyScaleValue)
How can I extract credit card substring from a string using python I am new to python and I hope someone can help me with this. I need to extract credit card numbers from a string. e.g"My credit card number is 1234-2312-2312-2312" or"My Credict card number is 1234 1234 1832 1234"Anyone knows how I can do it?
Do it like this using regeximport redef findCardNumber(string): pattern = r"(^|\s+)(\d{4}[ -]\d{4}[ -]\d{4}[ -]\d{4})(?:\s+|$)" match = re.search(pattern, string) if match: print(match.group(0))findCardNumber("My Credict card number is 1234 1234 1832 1234")This also considers the location of your card number in the string, it can be anywhere - at the beginning, somewhere in the middle or at the end.
pandas creates 2 copies of files in a loop I have a dataframe like as belowimport numpy as npimport pandas as pdfrom numpy.random import default_rngrng = default_rng(100)cdf = pd.DataFrame({'Id':[1,2,3,4,5], 'customer': rng.choice(list('ACD'),size=(5)), 'region': rng.choice(list('PQRS'),size=(5)), 'dumeel': rng.choice(list('QWER'),size=(5)), 'dumma': rng.choice((1234),size=(5)), 'target': rng.choice([0,1],size=(5))})I am trying to split the dataframe based on Customer and store it in a folder. Not necessary to understand the full code. The issue is in the last line.i = 0for k, v in df.groupby(['Customer']): print(k.split('@')[0]) LM = k.split('@')[0] i = i+1 unique_cust_names = '_'.join(v['Customer'].astype(str).unique()) unique_ids = '_'.join(v['Id'].astype(str).unique()) unique_location = '_'.join(v['dumeel'].astype(str).unique()) filename = '_'.join([unique_ids, unique_cust_names, unique_location, LM]) print(filename) with pd.ExcelWriter(f"{filename}.xlsx", engine='xlsxwriter') as writer: v.to_excel(writer,columns=col_list,index=False) wb = load_workbook(filename = 'format_sheet.xlsx') sheet_from =wb.worksheets[0] wb1 = load_workbook(filename = f"{filename}.xlsx") sheet_to = wb1.worksheets[0] copy_styles(sheet_from, sheet_to) #wb.close() tab = Table(displayName = "Table1", ref = "A1:" + get_column_letter(wb1.worksheets[0].max_column) + str(wb1.worksheets[0].max_row) ) style = TableStyleInfo(name="TableStyleMedium2", showFirstColumn=False, showLastColumn=False, showRowStripes=True, showColumnStripes=False) tab.tableStyleInfo = style wb1.worksheets[0].add_table(tab) #wb1.worksheets[0].parent.save(f"{filename}.xlsx") wb1.save("test_files/" + f"{filename}.xlsx") # issue is here wb1.close()print("Total number of customers to be emailed is ", i)Though the code works fine, the issue is in the below line I guesswb1.save("test_files/" + f"{filename}.xlsx") # issue is hereThis creates two copies of files.. One in the current folder as jupyter notebook file and other one inside the test_files folder.For ex: I see two files called test1.xlsx one in the current folder and one inside the test_files folder (path is test_files/test1.xlsx)How can I avoid this?I expect my output to generate/save only 1 file for each customer inside the test_files folder?
The issue is happening because you are referencing 2 different file names one with the prefix "test_files/" and once without it. Best way to handle it will be to define file name as followsdir_filename = "test_files/" + f"{filename}.xlsx"and then reference it in the following placeswith pd.ExcelWriter(f"{filename}.xlsx", engine='xlsxwriter') as writer: v.to_excel(writer,columns=col_list,index=False)##wb1 = load_workbook(filename = f"{filename}.xlsx")##wb1.save("test_files/" + f"{filename}.xlsx") Hope it helps
Making sublist indices refer to the original list I need to check some sublist for a particular property, and then return the bin which satisfies that property, but as an index of the original list. Currently I'm having to do this manually:sublist = mylist[start:end]positive = search(sublist)positive = start + positive posiveList.append(positive)Is there a more elegant/idiomatic way to achieve this?
I think what you're asking is this: If I search and find an index in a sublist, is there a straightforward way to convert it to its index in the original list?No, the only way is what you're already doing: you need to add the start offset back to the index to get the index in the original list.This makes sense because there is no actual association between the sublist and the original list. Take this example for instance:>>> x = [1,2,3,4,5]>>> y = x[1:3]>>> z = [2,3]>>> y == zTruez has just as much of a relationship to x as y has to x. Even though y was created using slicing syntax, it's just a copy of a range of elements in x—it is just a vanilla list and has no actual references to the original list x. Since there is no relationship between x and y built into y, there's no way to get the original x-index back from a y-index.
64-bit argument for fcntl.ioctl() In my Python (2.7.3) code, I'm trying to use an ioctl call, accepting a long int (64 bit) as an argument. I'm on a 64-bit system, so a 64-bit int is the same size as a pointer.My problem is that Python doesn't seem to accept a 64-bit int as the argument for a fcntl.ioctl() call. It happily accepts a 32-bit int or a 64-bit pointer - but what I need is to pass a 64-bit int.Here's my ioctl handler:static long trivial_driver_ioctl(struct file *filp, unsigned int cmd, unsigned long arg){ long err = 0; switch (cmd) { case 1234: printk("=== (%u) Driver got arg %lx; arg<<32 is %lx\n", cmd, arg, arg<<32); break; case 5678: printk("=== (%u) Driver got arg %lx\n", cmd, arg); break; default: printk("=== OH NOES!!! %u %lu\n", cmd, arg); err = -EINVAL; } return err;}In existing C code, I use the call like this:static int trivial_ioctl_test(){ int ret; int fd = open(DEV_NAME, O_RDWR); unsigned long arg = 0xffff; ret = ioctl(fd, 1234, arg); // ===(1234) Driver got arg ffff; arg<<32 is ffff00000000 arg = arg<<32; ret = ioctl(fd, 5678, arg); // === (5678) Driver got arg ffff00000000 close(fd);}In python, I open the device file, and then I get the following results: >>> from fcntl import ioctl>>> import os>>> fd = os.open (DEV_NAME, os.O_RDWR, 0666)>>> ioctl(fd, 1234, 0xffff)0>>> arg = 0xffff<<32>>> # Kernel log: === (1234) Driver got arg ffff; arg<<32 is ffff00000000>>> # This demonstrates that ioctl() happily accepts a 32-bit int as an argument.>>> import struct>>> ioctl(fd, 5678, struct.pack("L",arg))'\x00\x00\x00\x00\xff\xff\x00\x00'>>> # Kernel log: === (5678) Driver got arg 7fff9eb1fcb0>>> # This demonstrates that ioctl() happily accepts a 64-bit pointer as an argument.>>> ioctl(fd, 5678, arg)Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> ioctl(fd, 5678, arg)OverflowError: signed integer is greater than maximum>>> # Kernel log: (no change - OverflowError is within python)>>> # Oh no! Can't pass a 64-bit int!>>> Is there any way Python can pass my 64-bit argument to ioctl()?
Whether or not this is possible using Python's fcntl.ioctl() will be system-dependent. Tracing through the source code, the error message is coming from the following test on line 658 of getargs.c...else if (ival > INT_MAX) { PyErr_SetString(PyExc_OverflowError, "signed integer is greater than maximum"); RETURN_ERR_OCCURRED;}...and on my system, /usr/include/limits.h tells me...# define INT_MAX 2147483647...which is (presumably) (2 ** ((sizeof(int) * 8) - 1)) - 1.So, unless you're working on a system where sizeof(int) is at least 8, you'll have to call the underlying C function directly using the ctypes module, but it's platform-specific.Assuming Linux, something like this ought to work...from ctypes import *libc = CDLL('libc.so.6')fd = os.open (DEV_NAME, os.O_RDWR, 0666)value = c_uint64(0xffff<<32)libc.ioctl(fd, 5678, value)
why my click function not working in python selenium Imported all the driver and library from lib2to3.pgen2.driver import Driver from sqlite3 import Timestamp from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from time import sleep import getpass as gpclick function not working tweeter site not being logging with usernamePATH = "/Users/pratikbhattarai/Downloads/chromedriver" driver = webdriver.Chrome(PATH) driver.get("https://twitter.com/login") sleep(3) username = driver.find_element(By.XPATH, "//input[@name='text']") username.send_keys("LearnereaBot") next_button = driver.find_element(By.XPATH, "//span[contains(text(), 'Next')]") next_button.click() UserTags = [] Timestamp = [] Tweets = [] Reply = [] reTweets = [] Likes = []
You may want to use explicit waits, rather than implicit. The following code will wait for the elements in page to become available, input your username, and click on Next button. Do not forget to import WebDriverWait and expected_conditions:from selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC[...]url='https://twitter.com/login'browser.get(url)username = WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.XPATH, "//input[@name='text']")))username.send_keys("LearnereaBot")next_button = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[contains(text(), 'Next')]")))next_button.click()[...]
How to make the docker container search the file within the host rather than within the container? I have a python script which takes the input file path from the user processes that file and gives the output file in the location specified by the user in the terminal. Below is my code which takes the files path.inputfilepath = input("Enter the input file path")print(inputfilepath)outputfilepath = input("Enter the output file path")print(outputfilepath)inputPath = inputfilepathThis python code works fine if I run it in the Pycharm but if I create a docker image of the same code and enter the input file path, it gives "File not found error".Providing the input and output file path to the running containerandThis is the error messageBecause if I give the file path of the host/local machine, it searches for that path within the container's working director not within the local machine.How do I make the container search the file path on the local file system?Thanks in advance!
You should mount your files (or the directory containing the files) from the host to the container.Assuming you want the same path in the container as in the host:docker run \ --mount type=bind,source=/path/to/directory,target=/path/to/directorySee the documentation about bind mounts.
pandas: from how to unpack nested JSON as dataframe? I have an JSON output like thisjson.json{"SeriousDlqin2yrs": {"prediction": "0", "prediction_probs": {"0": 0.95, "1": 0.04}}}{"SeriousDlqin2yrs": {"prediction": "0", "prediction_probs": {"0": 0.96, "1": 0.03}}}and I would like to read it in as a pandas dataframes that looks like thisprediction, prediction_probs.0, prediction_probs.10, 0.95, 0.040, 0.96, 0.03but I can't seem to find the right wayI triedpredictions = pd.read_json("json.json", lines=True)predictions.apply(lambda x: pd.DataFrame(x[0]), axis=1)
Tested in pandas 1.1.1 - convert values to lists and pass to json_normalize:s = pd.read_json('json.json', lines=True)['SeriousDlqin2yrs'].tolist()df = pd.json_normalize(s)print (df) prediction prediction_probs.0 prediction_probs.10 0 0.95 0.041 0 0.96 0.03Another idea is parsing json to list instead pd.read_json:import jsons = []with open('json.json') as f: for line in f: s.append(json.loads(line)['SeriousDlqin2yrs']) df = pd.json_normalize(s)print (df) prediction prediction_probs.0 prediction_probs.10 0 0.95 0.041 0 0.96 0.03
How to drop all strings in a column using a wildcard? I have some data that changes regularly but the column headers need to be consistent (so I cant drop the headers) but I need to clear our the strings in a given column.This is what I have now but this only seems to work for where I know what the string is called and one at a time? df1= pd.read_csv(r'C:\Users\Test.csv')df2 = df1.drop(df1[~(df1['column'] != 'String1')].index)
You can use the pd.drop function which removes rows having a specific index from a dataframe.for i in df.index: if type(df.loc[i, 'Aborted Reason']) == str: df.drop(i, inplace = True)df.drop will remove the index having a string in the relevant column from the dataframe.
How to use the universal POS tags with nltk.pos_tag() function? I have a text and I want to find number of 'ADJs','PRONs', 'VERBs', 'NOUNs' etc.I know that there is .pos_tag() function but it gives me different results , and I want to have results as 'ADJ','PRON', 'VERB', 'NOUN'.This is my code:import nltkfrom nltk.corpus import state_union, brownfrom nltk.corpus import stopwordsfrom nltk import ne_chunkfrom nltk.tokenize import PunktSentenceTokenizerfrom nltk.tokenize import word_tokenizefrom nltk.tokenize import RegexpTokenizerfrom nltk.stem import WordNetLemmatizer from collections import Countersentence = "this is my sample text that I want to analyze with programming language"# tokenizing text (make list with evey word)sample_tokenization = word_tokenize(sample)print("THIS IS TOKENIZED SAMPLE TEXT, LIST OF WORDS:\n\n", sample_tokenization)print()# tagging wordstaged_words = nltk.pos_tag(sample_tokenization.split(' '))print(taged_words)print()# showing the count of every type of word for new textcount_of_word_type = Counter(word_type for word,word_type in taged_words)count_of_word_type_list = count_of_word_type.most_common() # making a list of tuples countsprint(count_of_word_type_list)for w_type, num in count_of_word_type_list: print(w_type, num)print() The code above works but I want to find a way to get this type of tags:Tag Meaning English ExamplesADJ adjective new, good, high, special, big, localADP adposition on, of, at, with, by, into, underADV adverb really, already, still, early, nowCONJ conjunction and, or, but, if, while, althoughDET determiner, article the, a, some, most, every, no, whichNOUN noun year, home, costs, time, AfricaNUM numeral twenty-four, fourth, 1991, 14:24PRT particle at, on, out, over per, that, up, withPRON pronoun he, their, her, its, my, I, usVERB verb is, say, told, given, playing, would. punctuation marks . , ; !X other ersatz, esprit, dunno, gr8, univeristyI saw that there is a chapter here: https://www.nltk.org/book/ch05.htmlThat says:from nltk.corpus import brownbrown_news_tagged = brown.tagged_words(categories='news', tagset='universal')But I do not know how to apply that on my sample sentence.Thanks for your help.
From https://github.com/nltk/nltk/blob/develop/nltk/tag/init.py#L135 >>> from nltk.tag import pos_tag>>> from nltk.tokenize import word_tokenize# Default Penntreebank tagset.>>> pos_tag(word_tokenize("John's big idea isn't all that bad."))[('John', 'NNP'), ("'s", 'POS'), ('big', 'JJ'), ('idea', 'NN'), ('is', 'VBZ'),("n't", 'RB'), ('all', 'PDT'), ('that', 'DT'), ('bad', 'JJ'), ('.', '.')]# Universal POS tags.>>> pos_tag(word_tokenize("John's big idea isn't all that bad."), tagset='universal')[('John', 'NOUN'), ("'s", 'PRT'), ('big', 'ADJ'), ('idea', 'NOUN'), ('is', 'VERB'),("n't", 'ADV'), ('all', 'DET'), ('that', 'DET'), ('bad', 'ADJ'), ('.', '.')]
Get max time of grouped by time series dataframe I have a dataframe as follows:Date User Tag2-22-2022 09:00:00 u1 a2-22-2022 10:00:00 u1 b2-22-2022 11:00:00 u2 c2-23-2022 09:00:00 u1 a2-23-2022 10:00:00 u2 bWant to creat, for each user, a column with the time difference between followed users/records.Something like:df["diff"] = df.groupby("user")["StartT"].diff().shift(-1)Date User Tag diff2-22-2022 09:00:00 u1 a 1 hour2-22-2022 10:00:00 u1 b 23 hours2-22-2022 11:00:00 u2 c 23 hours2-23-2022 09:00:00 u1 a NaN 2-23-2022 10:00:00 u2 b NaNWhat I want to do is get, for each user (daily), and for each tag, the tag the user spent more time in.Output:Date User Tag2-22-2022 10:00:00 u1 b2-22-2022 11:00:00 u2 c2-23-2022 09:00:00 u1 a2-23-2022 10:00:00 u2 bTried to groupby(user, date(1day), tag)['diff].sum().idxmax() ?There might be multiple tags per day/user, that's why i'm grouping by tag
First of all, I had to split your calculation of the "diff" column in two steps to reach the same output as you:>>> df["diff"] = df.groupby("User")["Date"].diff()>>> df["diff"] = df.groupby("User")["diff"].shift(-1)We'll also fill the NaN values on the "diff" columns by calculating the hours remaining to end the day (useful at the end of your data).>>> df["diff"] = df["diff"].fillna(df["Date"].dt.date + pd.DateOffset(days=1) - df["Date"])>>> df Date User Tag diff0 2022-02-22 09:00:00 u1 a 0 days 01:00:001 2022-02-22 10:00:00 u1 b 0 days 23:00:002 2022-02-22 11:00:00 u2 c 0 days 23:00:003 2022-02-23 09:00:00 u1 a 0 days 15:00:004 2022-02-23 10:00:00 u2 b 0 days 14:00:00Now, we apply .groupby to group by "User", day (using df["Date"].dt.date), and "Tag" to calculate the total time spent on each "Tag":>>> times = pd.to_datetime(df["Date"])>>> df_total_diff = df.dropna().groupby(["User", times.dt.date, "Tag"])["diff"].sum().reset_index()>>> df_total_diff User Date Tag diff0 u1 2022-02-22 a 0 days 01:00:001 u1 2022-02-22 b 0 days 23:00:002 u1 2022-02-23 a 0 days 15:00:003 u2 2022-02-22 c 0 days 23:00:004 u2 2022-02-23 b 0 days 14:00:00Finally, we can group by "User" and "Date" to find the most consumed "Tag":>>> df_output = df.loc[df_total_diff.groupby(["User", "Date"])["diff"].idxmax()]>>> df_output Date User Tag1 2022-02-22 10:00:00 u1 b2 2022-02-22 11:00:00 u2 c3 2022-02-23 09:00:00 u1 a4 2022-02-23 10:00:00 u2 b
Create and populate dataframe column simulating (excel) vlookup function I am trying to create a new column in a dataframe and polulate it with a value from another data frame column which matches a common column from both data frames columns.DF1 DF2A B W B——— ——— Y 2 X 2N 4 F 4 Y 5 T 5I though the following could do the tick.df2[‘new_col’] = df1[‘A’] if df1[‘B’] == df2[‘B’] else “Not found”So result should be:DF2W B new_colX 2 Y -> Because DF1[‘B’] == 2 and value in same row is YF 4 NT 5 Ybut I get the below error, I believe that is because dataframes are different sizes?raise ValueError("Can only compare identically-labeled Series objects”)Can you help me understand what am I doing wrong and what is the best way to achieve what I am after?Thank you in advance.UPDATE 1Trying Corralien solution I still get the below:ValueError: You are trying to merge on int64 and object columns. If you wish to proceed you should use pd.concatThis is the code I wrotedf1 = pd.DataFrame(np.array([['x', 2, 3], ['y', 5, 6], ['z', 8, 9]]), columns=['One', 'b', 'Three']) df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c'])df2.reset_index().merge(df1.reset_index(), on=['b'], how='left') \ .drop(columns='index').rename(columns={'One': 'new_col'})UPDATE 2Here is the second option, but it does not seem to add columns in df2.df1 = pd.DataFrame(np.array([['x', 2, 3], ['y', 5, 6], ['z', 8, 9]]), columns=['One', 'b', 'Three'])df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c'])df2 = df2.set_index('b', append=True).join(df1.set_index('b', append=True)) \ .reset_index('b').rename(columns={'One': 'new_col'})print(df2) b a c new_col Three0 2 1 3 NaN NaN1 5 4 6 NaN NaN2 8 7 9 NaN NaNWhy is the code above not working?
Your question is not clear because why is F associated with N and T with Y? Why not F with Y and T with N?Using merge:>>> df2.merge(df1, on='B', how='left') W B A0 X 2 Y1 F 4 N # What you want2 F 4 Y # Another solution3 T 4 N # What you want4 T 4 Y # Another solutionHow do you decide on the right value? With row index?UpdateSo you need to use the index position:>>> df2.reset_index().merge(df1.reset_index(), on=['index', 'B'], how='left') \ .drop(columns='index').rename(columns={'A': 'new_col'}) W B new_col0 X 2 Y1 F 4 N2 T 4 YIn fact you can consider the column B as an additional index of each dataframe.Using join>>> df2.set_index('B', append=True).join(df1.set_index('B', append=True)) \ .reset_index('B').rename(columns={'A': 'new_col'}) B W new_col0 2 X Y1 4 F N2 4 T YSetup:df1 = pd.DataFrame([['x', 2, 3], ['y', 5, 6], ['z', 8, 9]], columns=['One', 'b', 'Three'])df2 = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c'])
How to use alt.condition() in alt.color(condition=)? I'm new to altair so i want to be able to see my code more clearly. that's why i'm trying to use long version coding. my problem is that, i could't find any documentation on how to use a alt.color(condition=) . How can i use condition= preferably with alt.condition()?brush = alt.selection_interval()alt.Chart(cars).mark_point().encode( alt.Y("Horsepower"), alt.X("Miles_per_Gallon", title="consumption"), #alt.Tooltip(["Name", "Origin"]), #color=alt.condition(brush, 'Origin:N', alt.value('White')) I Know with this line my code will work alt.Color(condition= alt.condition(brush, alt.Color('Origin:N', legend=None), alt.value('lightgray')))).add_selection( brush)
alt.condition is a shorthand for generating the full alt.Color specification for a conditional encoding. If you wish, you can create it more manually like this: alt.Color( condition={"selection": brush.name, "field": "Origin", "type": "nominal"}, value='lightgray')If you're really set on using alt.condition as an argument to condition=, you could do something like this: alt.Color( condition=alt.condition(brush, "Origin:N", "")["condition"], value='lightgray')but it's a bit strange.
How to show all categories in legend in pie chart with matplotlib python Hi I am trying a plot chart and have some difficulties to show the legend. Here's my code below:age = ['below 20', '20-30', '30-40', '40-50']age_count = [23,0,35,0]labels = agesizes = age_countfig1, ax1 = plt.subplots()ax1.pie(sizes, autopct='%1.1f%%', shadow=True, startangle=90)ax1.legend(labels,bbox_to_anchor=(1, 0),loc='lower left')I do not want to show the categories with zero count in the pie chart plot. Still I want to show all the category names (i.e. 20-30,40-50) in the legend. I tried the code above but it is now working. Would like to know where went wrong?
from matplotlib.pyplot.pie docs:"autopct None or str or callable, default: NoneIf not None, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be fmt % pct. If it is a function, it will be called."you can specify a specific bihavier by passing a function to autopct like so:import matplotlib.pyplot as pltage = ['below 20', '20-30', '30-40', '40-50']age_count = [23,0,35,0]def f(cpt): if cpt == 0: return '' else: return '%.2f' %cptfig1, ax1 = plt.subplots()ax1.pie(age_count, autopct=f, shadow=True, startangle=90)ax1.legend(age,bbox_to_anchor=(1, 0),loc='lower left')
How can I get "START!" to print after the first line of asterisks when I run it, rather than just the changes of direction? It will print start and stop, but not on the first line? How can I get "START!" to print after the first line of asterisks when I run it, rather than just the changes of direction?import time, syswhile True: try: print("Enter and integer between 5 and 15: ") userInput = int(input()) if userInput < 5 or userInput > 15: continue else: break except ValueError: print("You must enter an integer.") continuestars = ''indent = 0indentIncreasing = Truetry: stars += "*" * userInput while True: print(' ' * indent, end='') print(stars) time.sleep(0.1) if indentIncreasing: indent = indent + 1 if indent == 20: print(' ' * 20 + stars + " STOP!") indentIncreasing = False else: indent = indent - 1 if indent == 0: print(stars + " START!") indentIncreasing = Trueexcept KeyboardInterrupt: sys.exit()
How about just adding a print statement before the while loop and initializing indent at 1 instead of 0?indent = 1indentIncreasing = Truetry: stars += "*" * userInput print(stars + ' START!') while True: print(' ' * indent, end='') print(stars) time.sleep(0.1)
Merging excel sheets using pandas I have a quick script using python and pandas thats supposed to compare two excel sheets, grab the information that i need and create a new file. However when it creates the new file or if i just print it for testing one of the columns is coming back empty depending on where i merge (left of right) import pandas as pdbase_data = pd.read_excel("UpdatedList.xls") - #this sheet has Names and clock numbertoday_data = pd.read_excel("LocationUP.xlsx") - #this sheet has Names and where employees are working.merge_data = base_data[["Names", "Clock Number" ]].merge(today_data[["Names", "Job"]], on="Names", how="right") #this line merges the two and creates a new files using the excel row "Names" as a merging key# merge_data.to_excel("EmployeeLocationInner.xlsx", index=False)print(merge_data.to_string())
I haven't double checked your merge, but rather than sending your merged data to a string, you should usepd.to_excel()something like:merge_data.to_excel('merged_data.xlsx', sheet_name='merged')If you need to save multiple sheets, looks the documentation - there are directions there.https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.htmlAs far as merges, left or right will select what data you want to keep, so check your merge type to make sure you are keeping the data you want. I would advise trying each type of merge, and seeing what you want. It might be helpful to learn about different merge types. Here is a nice reference, or just google sql join types:https://www.w3schools.com/sql/sql_join.aspFor reference, pd.merge()https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html
Plotly: How to show other values than counts for marginal histogram? I am trying to create a linked marginal plot above the original plot, with the same x axis but with a different y axis.I've seen that in plotly.express package there are 4 options in which you can create marginal_x plot on a scatter fig, but they are all based on the same columns as x and y.In my case, I have a date on my x-axis and rate of something on my y-axis, and I am trying to produce a histogram marginal distribution plot of the samples of which this rate is based on (located in samples column within the df).I'm simplifying what I've tried without lessening any important details:import pandas as pdimport plotly.express as pxdf = pd.DataFrame( { "date": [pd.Timestamp("20200102"), pd.Timestamp("20200103")], "rate": [0.88, 0.96], "samples": [130, 1200]) })fig = px.scatter(df, x='date', y='rate', marginal_x='histogram')fig.show()The documentation I based on: https://plotly.com/python/marginal-plots/My desired result:Example:The difference is that I use an aggregated df, so my count is just 1, instead of being the amount of samples.Any ideas?Thanks!
I'm understanding your statement[...] and rate of something on my y-axis... to mean that you'd like to display a value on your histogram that is not count.marginal_x='histogram' in px.scatter() seems to be defaulted to show counts only, meaning that there is no straight-forward way to show values of individual observations. But if you're willing to use fig = make_subplots() in combination with go.Scatter() and go.Bar(), then you can easily build this:PlotComplete code:import pandas as pdimport numpy as npfrom datetime import datetime, timedeltafrom plotly.subplots import make_subplotsimport plotly.graph_objects as gofig = make_subplots(rows=2, cols=1, row_heights=[0.2, 0.8], vertical_spacing = 0.02, shared_yaxes=False, shared_xaxes=True)df = pd.DataFrame( { "date": [pd.Timestamp("20200102"), pd.Timestamp("20200103")], "rate": [0.88, 0.96], "samples": [130, 1200] })fig.add_trace(go.Bar(x=df['date'], y=df['rate'], name = 'rate'), row = 1, col = 1)fig.update_layout(bargap=0, bargroupgap = 0, )fig.add_trace(go.Scatter(x=df['date'], y=df['samples'], name = 'samples'), row = 2, col = 1)fig.update_traces(marker_color = 'rgba(0,0,250, 0.3)', marker_line_width = 0, selector=dict(type="bar"))fig.show()
Pandas: Compare rows within groups in a dataframe and create summary rows to mark / highlight different entries in group I have a pandas dataframe with approx. 1200 rows, where some of the rows are duplicated multiple times. The df looks like this:ID Serial Age Grade Chem Bio Math PhyM001 2 52 37 1 1 1 1M001 2 55 37 2 1 0 1M001 3 51 36,5 1 1 1 0M001 3 51 46,5 1 0 1 1M041 2 52 36,1 1 1 0 0M041 2 51 36,1 2 1 2 4M041 2 52 36,1 1 1 0 M041 2 52 36,1 1 1 1 M010 5 58 37,4 0 1 1 3M010 5 55 39,4 1 2 1 1M010 5 58 37,4 1 1 1 1The duplicates in the dataframe are supposed to be identified by the ID and Serial column and I was able to do that. However, I would like to compare each group of ID+Serial rows to find where they differ. This is a bit tricky as sometimes there are 2 rows in a group to compare and sometimes the rows (to compare) are more than 2 within each group.I am interested in a solution where I can groupby the dataframe based on ID and Serial cols and then compare rows within each group. If there is a difference between two or more cells that needs to be recorded (e.g., in a new row with a X below the conflicting cells or perhaps highlighting the cells in red color). The resulting dataframe should look something like this:ID Serial Age Grade Chem Bio Math PhyM001 2 52 37 1 1 1 1M001 2 55 37 2 1 0 1M001 2 X X X M001 3 51 36,5 1 1 1 0M001 3 51 46,5 1 0 1 1M001 3 X X XM041 2 52 36,1 1 1 0 0M041 2 51 36,1 2 1 2 4M041 2 52 36,1 1 1 0 M041 2 52 36,1 1 1 1 M041 2 X X X XM010 5 58 37,4 0 1 1 3M010 5 55 39,4 1 2 1 1M010 5 58 37,4 1 1 1 1M010 5 X X X X XCan someone help with this issue?
You can create a comparison marking table by grouping on ID and Serial using .groupby() and get the number of unique entries for each column by .nunique(). Mark with 'X' if number of unique entries > 1 or blank otherwise.Finally, concat the newly created comparison marking table back to the original dataframe by pd.concat(). Sort by ID and Serial columns by .sort_values() to bring back the related entries together.df_mark = (df.groupby(['ID', 'Serial']) .nunique() .gt(1) .replace({True: 'X', False: ''}) .reset_index() )(pd.concat([df, df_mark]) .sort_values(['ID', 'Serial']) .reset_index(drop=True))Result: ID Serial Age Grade Chem Bio Math Phy0 M001 2 52 37 1 1 1 1.01 M001 2 55 37 2 1 0 1.02 M001 2 X X X 3 M001 3 51 36,5 1 1 1 0.04 M001 3 51 46,5 1 0 1 1.05 M001 3 X X X6 M010 5 58 37,4 0 1 1 3.07 M010 5 55 39,4 1 2 1 1.08 M010 5 58 37,4 1 1 1 1.09 M010 5 X X X X X10 M041 2 52 36,1 1 1 0 0.011 M041 2 51 36,1 2 1 2 4.012 M041 2 52 36,1 1 1 0 NaN13 M041 2 52 36,1 1 1 1 NaN14 M041 2 X X X X
how to use keras demo code siamese_contrastive.py to use a custom dataset? I am following this example Image similarity estimation using a Siamese Network with a contrastive loss.The given code snippet reads directly from keras.datasets.mnist.load_data().I am trying to adapt this example and trying to feed a new dataset. I have a directory where I kept examples of positive and negative images.So I have three directories of anchor, positive, and negative examples, i.e.:anchor/1.jpg2.jpg3.jpg....positive/1.jpg2.jpg3.jpg....negative/1.jpg2.jpg3.jpg....How could I feed this dataset into this model?For my case I have to get embedding of the images before feeding into the model. Any idea is welcome.
You can load images like this :anchor_images = sorted([str(anchor_images_path / f) for f in os.listdir(anchor_images_path)])Same for positives and negatives.Detailed example here:https://keras.io/examples/vision/siamese_network/
Django Localization: languages and models connection The main idea of my project with localisation is show different content on all languages. I'm trying to use Django Internationalization and localization.Everything worked, except for one problem:If I post question (QA project) on polish language, my url is - site.com/pl/questions/question_123/And same question is available on all others locales:Spanish - site.com/es/questions/question_123/Norwegian - site.com/no/questions/question_123/Is it possible to make question available only in the language in which it was posted?Models:class Language(models.Model): name = models.CharField(max_length=100, unique=True) code = models.CharField(max_length=20, unique=True) def __str__(self): return f'{self.name} ({self.code})'class Question(models.Model): """Main class for all questions""" is_active = models.BooleanField(default=False) language = models.ForeignKey(Language, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=500) slug = models.SlugField(max_length=600, unique=True, blank=True) body = models.TextField(max_length=1000, blank=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name='question_category' ) tags = models.ManyToManyField(Tag, related_name='question_tags', blank=True) date_published = models.DateTimeField(auto_now_add=True) date_edited = models.DateTimeField(auto_now=True) vote = models.ManyToManyField( Profile, blank=True, related_name='question_vote' ) user = models.ForeignKey( Profile, on_delete=models.CASCADE, blank=True, null=True ) class Meta: verbose_name = 'question' verbose_name_plural = 'questions' def get_absolute_url(self): return reverse('questions:detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.id: self.slug = generate_slug(self.title) super().save(*args, **kwargs) @property def num_votes(self): return self.vote.all().count() def __str__(self): return self.titleViewsclass QuestionDetailView(DetailView): model = Question def get_context_data(self, **kwargs): context = super(QuestionDetailView, self).get_context_data(**kwargs) context['tags'] = Tag.objects.filter(question_tags=self.object) context['answers'] = Answer.objects.filter(question=self.object) context['current_site'] = get_current_site return contextUrlsurlpatterns = [ path('view/<slug:slug>/', QuestionDetailView.as_view(), name='detail')]SettingsMIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.redirects.middleware.RedirectFallbackMiddleware',]LANGUAGE_CODE = 'en'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = TrueLOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale')]LANGUAGES = [ ('en', 'English'), ('es', 'Spanish'), ('pl', 'Polish'),]Category Viewfrom django.utils.translation import get_languageclass CategoryListView(ListView): template_name = 'categorizations/category_list.html' def get_queryset(self): current_language = get_language() self.category = get_object_or_404(Category, slug=self.kwargs['slug']) return Question.objects.filter( category=self.category, language__code=current_language ) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) current_language = get_language() context['questions'] = Question.objects.filter( category=self.category, is_active=True, language__code=current_language) context['current_object'] = Category.objects.filter( name=self.category) return context
You can overrideget_queryset()from the DetailView and control, and filter your queryset by language.return Question.objects.filter(language__code=MY_LANGUAGE_CODE)You can access your language code probably with your URL-slug field. This should be accessible somewhere in your View.
Can not uninstall Tensorflow 2.1.0 as conda can't find the package and solving environment fails The tensorflow 2.1.0 package is shown under conda list as follows:But when I try to uninstall it using conda remove tensorflow I get the following message:pip uninstall is also not working. I tried several other methods as well (shown below), and none of these worked. This kinda makes sense as pip list doesn't show this package.Additional information which is also the strangest thing. This is how the anaconda navigator shows the package.As there are no other packages named as tensorflow present in the list, I assumed that this package marked in red must be the same tensorflow package which comes up in conda list.Please can someone help me to uninstall this remaining package so that I can have a clean re-installation of the latest tensorflow packages.
First obtain the path where your packages are installed in anaconda-spyder using this command. Refer this link for more informationpython -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"Then I was able to find the package that was listed in the final image of the question. So there after it was a matter of deleting those folders shown below.After that conda list doesn't have that package anymore.
Insert Property Value using Py2neo I have one label say User,and one property say Email.I am trying to insert one property value based on user input like "abcd@gmail.com" . My code is below db=Graph("bolt://localhost:1234", user="", password="")db.evaluate('''Create (u:User) WHERE u.Email=$para1 RETURN u''', parameters={'para1': arg}))I am tried alsodb.create(Node("User", "Email").__setitem__("Email", arg))However both is not working.
I have solved my problem.Posting the answer so it may help others.self.db.evaluate('''Create (u:User) SET u.Email=$para1 RETURN u''', parameters={'para1': arg})
ValueError: cannot reshape array of size 7840000 into shape (60000,784) I am trying to classify greyscale images of hand written digits (28 by 28 pixels) into their 10 categories.I already checked similar questions on this site, but I failed at solving why I am getting the error: ValueError: cannot reshape array of size 7840000 into shape (60000,784)If you can please help me how to fix this.from keras.datasets import mnistfrom keras import modelsfrom keras import layersfrom keras.utils import to_categoricaldef load_dataset(): (train_images, train_labels), (test_images, test_labels) = mnist.load_data() train_images = train_images.reshape((60000, 28 * 28)) test_images = test_images.reshape((60000, 28 * 28)) train_labels = to_categorical(train_labels) test_labels = to_categorical(test_labels) return train_images, train_labels, test_images, test_labelsdef prep_pixels(train, test): train_images = train_images.astype('float32') / 255 test_images = test_images.astype('float32') / 255 return train_images, test_imagesdef define_model(): network = models.Sequential() network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,))) network.add(layers.Dense(10, activation='softmax')) return networkdef compile(network): network.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])def run(): (train_images, train_labels), (test_images, test_labels) = load_dataset() train_images, test_images = prep_pixels(test_images, test_images) network = define_model() compiled_network = compile(network) compiled_network.fit(train_images, train_labels, epochs=5, batch_size=128)run()
MNIST dataset consist of 60000 training images and 10000 test images. Reshape as:test_images = test_images.reshape((10000, 28 * 28))
Flask configuration Error I'm having issues making flask work. I'm a noob and still learning about Linux. I'm getting this (very intimidating looking)error after running:flask runroot@DESKTOP-TV7O885:/mnt/c/Projects/app_1# flask run * Serving Flask app "application" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)[2018-03-12 14:10:00,550] ERROR in app: Exception on / [GET]Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/mnt/c/Projects/app_1/application.py", line 7, in index return render_template("index.html") File "/usr/local/lib/python2.7/dist-packages/flask/templating.py", line 133, in render_template return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list), File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 869, in get_or_select_template return self.get_template(template_name_or_list, parent, globals) File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 830, in get_template return self._load_template(name, self.make_globals(globals)) File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 804, in _load_template template = self.loader.load(self, name, globals) File "/usr/local/lib/python2.7/dist-packages/jinja2/loaders.py", line 113, in load source, filename, uptodate = self.get_source(environment, name) File "/usr/local/lib/python2.7/dist-packages/flask/templating.py", line 57, in get_source return self._get_source_fast(environment, template) File "/usr/local/lib/python2.7/dist-packages/flask/templating.py", line 85, in _get_source_fast raise TemplateNotFound(template)TemplateNotFound: index.html127.0.0.1 - - [12/Mar/2018 14:10:00] "GET / HTTP/1.1" 500 -and the page then drops Internal Server ErrorThe server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.I'm also getting a pylint error on VSCODE: E0401:Unable to import 'flask'I understand its probably a relatively simple error because of a bad configuration or installing something wrong. I've been trying to figure this out myself but I have a lot of gaps in my knowledge.I'm using Bash on Ubuntu on Windows and I think that's why i'm having issues. if anyone could help me or atleast point me in the right direction I would greatly appreciate it
On the call stack in the exception, you must go from bottom to top, until you find a file in your project. This is the starting point. In your case, it is:File "/mnt/c/Projects/app_1/application.py", line 7, in index return render_template("index.html")You say you have a template named index.html, but (as the exception error), Flask cannot find it. Check that you have such template in the correct place, and you define correctly (when you call Flask constructor) the location of template directory.
Performing list of Google Search using Python code I'm pretty new to programming, and I didn't start to learn python yet. In general I have a long list of codes which I need to search in google for example:123, 124, 125, 126I find code which can do that in python here:which look like this:try: from googlesearch import search except ImportError: print("No module named 'google' found") query = "Geeksforgeeks"for j in search(query, tld="co.in", num=10, stop=1, pause=2): print(j) but I don't know how to make it search more than one item from my list in a time. I tried to create a list in python but it didn't work. Can you guys help me on that?
I'd recommend just setting up a collection of strings you want to search for.Then iterate through the collection, search for that string, and store the results.from googlesearch import search list_of_queries = ["Geeksforgeeks", "stackoverflow", "GitHub"]results = []for query in list_of_queries: results.append(search(query, tld="co.in", num=10, stop=1, pause=2))print(results)
Python - Function not returning y value I'm essentially making a counter and it counts the number of times a name appears in a list. I'm trying to use a function so I can easily do it for all the names. It works fine when I don't make the code a function but as soon as I do it no longer returns the value of y.#animal_types=['Elephant', 'Rhinoceros', 'Lion','Water Buffalo','Leopard','Giraffe','Giraffe','Ghu','Thompson Gazelle','Dik Dik','Zebra','Baboon','Hyena','Hippopotamus','Crocodile','Ostrich','Wild Dog','WartHog','Vulture']short_animal_list = ['Baboon', 'Gnu', 'WartHog', 'Gnu', 'Vulture', 'Gnu', 'Gnu', 'Gnu', 'Zebra', 'WartHog', 'Zebra', 'Zebra', 'Leopard', 'Gnu', 'Gnu', 'Elephant', 'Gnu']medium_animal_list = ['Thompson Gazelle', 'Gnu', 'Lion', 'Vulture', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Hyena', 'Thompson Gazelle', 'Thompson Gazelle', 'Hyena', 'Gnu', 'Vulture', 'Vulture', 'Leopard', 'Zebra', 'Zebra', 'Crocodile', 'Zebra', 'Gnu', 'Gnu', 'Vulture', 'Hippopotamus', 'Gnu', 'Gnu', 'Zebra', 'Baboon', 'Vulture', 'Baboon', 'Baboon', 'WartHog', 'Gnu', 'Baboon', 'Zebra', 'Dik Dik', 'Rhinoceros', 'Gnu', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Hyena', 'Zebra', 'Hippopotamus', 'Zebra', 'Giraffe', 'Zebra', 'Hyena', 'Zebra', 'Crocodile', 'WartHog', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Zebra', 'Zebra', 'Zebra', 'Gnu', 'Hippopotamus', 'Gnu', 'Gnu', 'Elephant', 'Baboon', 'Gnu', 'Gnu', 'Gnu', 'Crocodile', 'Giraffe', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Dik Dik', 'Baboon', 'Gnu', 'Vulture', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Leopard', 'Vulture', 'Gnu', 'Dik Dik', 'Thompson Gazelle', 'Elephant', 'Gnu', 'Vulture', 'Crocodile', 'Zebra', 'Gnu', 'Rhinoceros', 'Zebra', 'Vulture', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Zebra', 'Dik Dik', 'Gnu', 'Zebra', 'Gnu', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Elephant', 'Hippopotamus', 'Baboon', 'Zebra', 'WartHog', 'Gnu', 'Gnu', 'Zebra', 'Zebra', 'Gnu', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Elephant', 'Thompson Gazelle', 'Vulture', 'Zebra', 'Hyena', 'Baboon', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Baboon', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Hippopotamus', 'Crocodile', 'Thompson Gazelle', 'Gnu', 'Dik Dik', 'Vulture', 'Gnu', 'Zebra', 'Zebra', 'Zebra', 'Zebra', 'Thompson Gazelle', 'Dik Dik', 'Zebra', 'Baboon', 'Gnu', 'Zebra', 'Zebra', 'Vulture', 'Zebra', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Giraffe', 'Zebra', 'Zebra', 'Hyena', 'Crocodile', 'WartHog', 'Zebra', 'Zebra', 'Giraffe', 'Hyena', 'Giraffe', 'Vulture', 'Zebra', 'Zebra', 'Vulture', 'Baboon', 'WartHog', 'Zebra', 'Gnu', 'Gnu', 'Hyena']long_animal_list = ['WartHog', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Zebra', 'Lion', 'Gnu', 'Thompson Gazelle', 'Thompson Gazelle', 'Thompson Gazelle', 'Lion', 'Gnu', 'Vulture', 'Crocodile', 'Zebra', 'Gnu', 'Lion', 'Gnu', 'Gnu', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Crocodile', 'Thompson Gazelle', 'Hyena', 'Zebra', 'Hyena', 'Zebra', 'Thompson Gazelle', 'Dik Dik', 'Baboon', 'Thompson Gazelle', 'Vulture', 'Elephant', 'Vulture', 'Vulture', 'WartHog', 'Zebra', 'Giraffe', 'Gnu', 'Hyena', 'Crocodile', 'Gnu', 'Gnu', 'Hippopotamus', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Vulture', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Dik Dik', 'Zebra', 'Zebra', 'WartHog', 'Gnu', 'Baboon', 'Gnu', 'Hyena', 'Vulture', 'Gnu', 'Zebra', 'WartHog', 'Gnu', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Hyena', 'WartHog', 'Elephant', 'Giraffe', 'Elephant', 'Thompson Gazelle', 'Vulture', 'Zebra', 'WartHog', 'Zebra', 'Vulture', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Elephant', 'WartHog', 'Vulture', 'WartHog', 'Thompson Gazelle', 'Gnu', 'Dik Dik', 'Gnu', 'Zebra', 'Crocodile', 'Leopard', 'Thompson Gazelle', 'Zebra', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Zebra', 'Gnu', 'Water Buffalo', 'Zebra', 'Vulture', 'Gnu', 'Thompson Gazelle', 'Thompson Gazelle', 'Baboon', 'Thompson Gazelle', 'Wild Dog', 'Zebra', 'Thompson Gazelle', 'Vulture', 'Thompson Gazelle', 'Baboon', 'Baboon', 'Zebra', 'Zebra', 'Gnu', 'Zebra', 'Gnu', 'Gnu', 'Crocodile', 'WartHog', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Vulture', 'Baboon', 'Zebra', 'Hippopotamus', 'Water Buffalo', 'Dik Dik', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Thompson Gazelle', 'Elephant', 'Gnu', 'Hyena', 'Zebra', 'Water Buffalo', 'Gnu', 'Baboon', 'Gnu', 'Dik Dik', 'Gnu', 'Zebra', 'Rhinoceros', 'Thompson Gazelle', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Water Buffalo', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Hyena', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Crocodile', 'WartHog', 'Gnu', 'Elephant', 'Hippopotamus', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Baboon', 'Gnu', 'Gnu', 'Dik Dik', 'Gnu', 'Hippopotamus', 'Gnu', 'Gnu', 'Gnu', 'Wild Dog', 'Zebra', 'Gnu', 'Baboon', 'Gnu', 'Gnu', 'Vulture', 'Gnu', 'Thompson Gazelle', 'Lion', 'Hyena', 'Crocodile', 'Hyena', 'Vulture', 'Hyena', 'Dik Dik', 'Gnu', 'Gnu', 'Thompson Gazelle', 'WartHog', 'Thompson Gazelle', 'Hippopotamus', 'Zebra', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Lion', 'Gnu', 'WartHog', 'Dik Dik', 'Zebra', 'Crocodile', 'Zebra', 'Thompson Gazelle', 'Vulture', 'Vulture', 'Hippopotamus', 'Wild Dog', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Giraffe', 'Zebra', 'Crocodile', 'Hyena', 'Zebra', 'Gnu', 'Zebra', 'Zebra', 'Giraffe', 'Cheetah', 'Zebra', 'Hippopotamus', 'Dik Dik', 'Gnu', 'Gnu', 'Hippopotamus', 'Thompson Gazelle', 'Dik Dik', 'Zebra', 'Giraffe', 'Gnu', 'Thompson Gazelle', 'Crocodile', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Hyena', 'Zebra', 'Leopard', 'Giraffe', 'Thompson Gazelle', 'Thompson Gazelle', 'Vulture', 'Gnu', 'Gnu', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Thompson Gazelle', 'Vulture', 'Thompson Gazelle', 'Zebra', 'Cheetah', 'Gnu', 'Zebra', 'Gnu', 'Zebra', 'Hippopotamus', 'Hyena', 'Baboon', 'Thompson Gazelle', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Baboon', 'Thompson Gazelle', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Gnu', 'Vulture', 'Vulture', 'Zebra', 'Gnu', 'Elephant', 'Thompson Gazelle', 'Crocodile', 'Gnu', 'Gnu', 'Gnu', 'Baboon', 'Crocodile', 'Giraffe', 'Gnu', 'Water Buffalo', 'Zebra', 'Gnu', 'Baboon', 'Zebra', 'Dik Dik', 'Zebra', 'Zebra', 'Hyena', 'WartHog', 'Gnu', 'Zebra', 'Hippopotamus', 'Vulture', 'Thompson Gazelle', 'Vulture', 'Zebra', 'Zebra', 'Gnu', 'Gnu', 'Gnu', 'Gnu', 'Crocodile', 'Dik Dik', 'Gnu', 'Crocodile', 'Gnu', 'WartHog', 'Baboon', 'Hyena', 'Vulture', 'Thompson Gazelle', 'Thompson Gazelle', 'Thompson Gazelle', 'WartHog', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Zebra', 'WartHog', 'Dik Dik', 'Thompson Gazelle', 'Hyena', 'Hyena', 'Baboon', 'Zebra', 'Lion', 'Thompson Gazelle', 'Leopard', 'Lion', 'Vulture', 'Elephant', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Zebra', 'Zebra', 'Elephant', 'Leopard', 'Elephant', 'Thompson Gazelle', 'Hyena', 'Giraffe', 'Thompson Gazelle', 'Thompson Gazelle', 'Vulture', 'Zebra', 'Gnu', 'Gnu', 'Hippopotamus', 'Gnu', 'Zebra', 'Elephant', 'Gnu', 'Thompson Gazelle', 'Lion', 'Zebra', 'Gnu', 'Gnu', 'Zebra', 'Baboon', 'Thompson Gazelle', 'Gnu', 'Baboon', 'Crocodile', 'Giraffe', 'Thompson Gazelle', 'Hyena', 'Vulture', 'Gnu', 'Wild Dog', 'Baboon', 'Giraffe', 'Vulture', 'Dik Dik', 'Thompson Gazelle', 'Hyena', 'Zebra', 'Gnu', 'Zebra', 'Crocodile', 'Zebra', 'Gnu', 'Dik Dik', 'Gnu', 'Gnu', 'Gnu', 'Cheetah', 'Gnu', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Lion', 'Lion', 'Zebra', 'Gnu', 'Gnu', 'Baboon', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Hyena', 'Gnu', 'Zebra', 'Hippopotamus', 'Gnu', 'Vulture', 'Gnu', 'Gnu', 'Zebra', 'Zebra', 'Crocodile', 'Baboon', 'Gnu', 'Vulture', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Giraffe', 'Zebra', 'WartHog', 'Gnu', 'Gnu', 'Gnu', 'Dik Dik', 'Dik Dik', 'Zebra', 'Gnu', 'Giraffe', 'Cheetah', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Gnu', 'Gnu', 'Gnu', 'Vulture', 'Baboon', 'Zebra', 'Gnu', 'Crocodile', 'Gnu', 'Baboon', 'Ostrich', 'Thompson Gazelle', 'Zebra', 'Hippopotamus', 'Baboon', 'Gnu', 'Zebra', 'Zebra', 'Gnu', 'Vulture', 'Zebra', 'Zebra', 'Zebra', 'Zebra', 'Gnu', 'Gnu', 'Giraffe', 'Gnu', 'Zebra', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Hyena', 'Zebra', 'Vulture', 'Hyena', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Vulture', 'Gnu', 'Dik Dik', 'Zebra', 'WartHog', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Leopard', 'Zebra', 'Vulture', 'Vulture', 'Hippopotamus', 'Zebra', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Thompson Gazelle', 'Vulture', 'Zebra', 'Vulture', 'Wild Dog', 'Hyena', 'Lion', 'Crocodile', 'Gnu', 'Elephant', 'Zebra', 'WartHog', 'Vulture', 'Thompson Gazelle', 'Thompson Gazelle', 'Zebra', 'WartHog', 'Thompson Gazelle', 'Lion', 'Zebra', 'Zebra', 'Gnu', 'Rhinoceros', 'Zebra', 'Giraffe', 'Zebra', 'Gnu', 'Zebra', 'Gnu', 'Zebra', 'Baboon', 'Gnu', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Hyena', 'Zebra', 'Vulture', 'Zebra', 'Zebra', 'Zebra', 'Elephant', 'Gnu', 'Thompson Gazelle', 'Hyena', 'Gnu', 'Wild Dog', 'WartHog', 'Gnu', 'Crocodile', 'Thompson Gazelle', 'Zebra', 'Zebra', 'Zebra', 'Gnu', 'Crocodile', 'Giraffe', 'Gnu', 'Zebra', 'Zebra', 'Gnu', 'Hyena', 'Gnu', 'Gnu', 'Lion', 'Hippopotamus', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Vulture', 'Zebra', 'Zebra', 'Baboon', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Hyena', 'Gnu', 'Zebra', 'Zebra', 'Giraffe', 'Baboon', 'Gnu', 'Zebra', 'Gnu', 'Vulture', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Rhinoceros', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Zebra', 'Elephant', 'Thompson Gazelle', 'Ostrich', 'Zebra', 'Zebra', 'Water Buffalo', 'Lion', 'Zebra', 'Zebra', 'Thompson Gazelle', 'Baboon', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Vulture', 'Giraffe', 'Vulture', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Rhinoceros', 'Gnu', 'Vulture', 'Gnu', 'Zebra', 'Gnu', 'Hyena', 'Zebra', 'Gnu', 'Vulture', 'Crocodile', 'Thompson Gazelle', 'Zebra', 'Zebra', 'Zebra', 'Hyena', 'Thompson Gazelle', 'Giraffe', 'Gnu', 'Thompson Gazelle', 'Thompson Gazelle', 'WartHog', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Baboon', 'Gnu', 'Zebra', 'Gnu', 'Zebra', 'Gnu', 'Zebra', 'Hippopotamus', 'Gnu', 'Gnu', 'Gnu', 'Gnu', 'Gnu', 'Giraffe', 'WartHog', 'Zebra', 'Hyena', 'Zebra', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Thompson Gazelle', 'Thompson Gazelle', 'Hyena', 'Zebra', 'Crocodile', 'Zebra', 'Gnu', 'Zebra', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Vulture', 'Gnu', 'Gnu', 'Zebra', 'Hyena', 'WartHog', 'Vulture', 'Elephant', 'Giraffe', 'WartHog', 'Zebra', 'Baboon', 'Zebra', 'Water Buffalo', 'Zebra', 'Hyena', 'Hyena', 'Zebra', 'Crocodile', 'Baboon', 'Thompson Gazelle', 'Zebra', 'Hyena', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Baboon', 'Thompson Gazelle', 'Gnu', 'Hippopotamus', 'Dik Dik', 'Thompson Gazelle', 'Hippopotamus', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Vulture', 'Dik Dik', 'Gnu', 'Gnu', 'Gnu', 'Zebra', 'Vulture', 'Elephant', 'Crocodile', 'Gnu', 'Gnu', 'Vulture', 'Zebra', 'Gnu', 'Gnu', 'Baboon', 'Zebra', 'Zebra', 'Hippopotamus', 'Hippopotamus', 'Gnu', 'Gnu', 'Zebra', 'Baboon', 'Gnu', 'Gnu', 'Zebra', 'Zebra', 'Thompson Gazelle', 'Giraffe', 'Zebra', 'Vulture', 'Hippopotamus', 'Zebra', 'Baboon', 'Thompson Gazelle', 'Zebra', 'Vulture', 'Vulture', 'Hippopotamus', 'Thompson Gazelle', 'Crocodile', 'Lion', 'Zebra', 'Thompson Gazelle', 'Baboon', 'Dik Dik', 'Gnu', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Baboon', 'Gnu', 'Thompson Gazelle', 'Baboon', 'Baboon', 'Hippopotamus', 'Zebra', 'Zebra', 'Gnu', 'Gnu', 'Hyena', 'Crocodile', 'Zebra', 'Gnu', 'Baboon', 'Gnu', 'Zebra', 'Giraffe', 'Thompson Gazelle', 'Vulture', 'Thompson Gazelle', 'Crocodile', 'Dik Dik', 'Giraffe', 'Elephant', 'Baboon', 'Thompson Gazelle', 'Giraffe', 'Zebra', 'Zebra', 'Vulture', 'Hyena', 'Vulture', 'WartHog', 'Gnu', 'Zebra', 'Gnu', 'WartHog', 'Elephant', 'Thompson Gazelle', 'Zebra', 'Dik Dik', 'Elephant', 'Gnu', 'Ostrich', 'Dik Dik', 'Gnu', 'Hyena', 'Gnu', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Wild Dog', 'Crocodile', 'Giraffe', 'Wild Dog', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Hyena', 'Thompson Gazelle', 'Thompson Gazelle', 'Crocodile', 'Thompson Gazelle', 'Elephant', 'Thompson Gazelle', 'Leopard', 'Zebra', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Crocodile', 'Gnu', 'Giraffe', 'Gnu', 'Zebra', 'Thompson Gazelle', 'WartHog', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Hippopotamus', 'Dik Dik', 'Zebra', 'Gnu', 'Hippopotamus', 'Zebra', 'Baboon', 'Gnu', 'Gnu', 'Zebra', 'WartHog', 'Gnu', 'Giraffe', 'Gnu', 'Zebra', 'Gnu', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Lion', 'Gnu', 'Gnu', 'Gnu', 'Vulture', 'Gnu', 'Thompson Gazelle', 'Thompson Gazelle', 'Zebra', 'Vulture', 'Zebra', 'Giraffe', 'Thompson Gazelle', 'Gnu', 'Vulture', 'Crocodile', 'Thompson Gazelle', 'Zebra', 'Zebra', 'Hyena', 'Zebra', 'Baboon', 'WartHog', 'Gnu', 'Gnu', 'Giraffe', 'Crocodile', 'Hippopotamus', 'Gnu', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Baboon', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Hyena', 'Dik Dik', 'Zebra', 'Elephant', 'Giraffe', 'Gnu', 'Zebra', 'Gnu', 'Hyena', 'Baboon', 'Baboon', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Elephant', 'Gnu', 'Baboon', 'Thompson Gazelle', 'Thompson Gazelle', 'Giraffe', 'Baboon', 'Thompson Gazelle', 'Leopard', 'Gnu', 'Baboon', 'Giraffe', 'Gnu', 'Elephant', 'Thompson Gazelle', 'Zebra', 'Baboon', 'Vulture', 'Lion', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Zebra', 'Vulture', 'Gnu', 'Gnu', 'Zebra', 'Giraffe', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Zebra', 'Gnu', 'Zebra', 'Hyena', 'Hippopotamus', 'Rhinoceros', 'Thompson Gazelle', 'Thompson Gazelle', 'Crocodile', 'Hippopotamus', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Elephant', 'Zebra', 'Crocodile', 'Vulture', 'Zebra', 'WartHog', 'Zebra', 'Zebra', 'Crocodile', 'Gnu', 'Hippopotamus', 'Hippopotamus', 'Baboon', 'Hyena', 'Zebra', 'Vulture', 'Zebra', 'Zebra', 'Zebra', 'Baboon', 'Thompson Gazelle', 'Vulture', 'Thompson Gazelle', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Zebra', 'Gnu', 'Zebra', 'Zebra', 'Thompson Gazelle', 'Hyena', 'Dik Dik', 'Thompson Gazelle', 'Gnu', 'Giraffe', 'Vulture', 'Gnu', 'Gnu', 'Zebra', 'Zebra', 'Gnu', 'Zebra', 'Gnu', 'Elephant', 'Crocodile', 'Rhinoceros', 'Dik Dik', 'Giraffe', 'Zebra', 'Lion', 'Zebra', 'Hippopotamus', 'Thompson Gazelle', 'Cheetah', 'Thompson Gazelle', 'Elephant', 'Baboon', 'Vulture', 'Dik Dik', 'Thompson Gazelle', 'Vulture', 'Giraffe', 'Zebra', 'Wild Dog', 'Thompson Gazelle', 'WartHog', 'Thompson Gazelle', 'Gnu', 'Crocodile', 'Vulture', 'Cheetah', 'WartHog', 'Zebra', 'Lion', 'Zebra', 'Gnu', 'Gnu', 'Water Buffalo', 'Elephant', 'Giraffe', 'Vulture', 'Thompson Gazelle', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Gnu', 'Baboon', 'Thompson Gazelle', 'Zebra', 'Hippopotamus', 'Baboon', 'Thompson Gazelle', 'Hyena', 'Crocodile', 'Gnu', 'Zebra', 'Wild Dog', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Vulture', 'Giraffe', 'Gnu', 'Crocodile', 'Zebra', 'Zebra', 'Gnu', 'Hyena', 'WartHog', 'Zebra', 'Zebra', 'Hippopotamus', 'Zebra', 'Thompson Gazelle', 'Ostrich', 'Crocodile', 'Crocodile', 'Lion', 'Gnu', 'Dik Dik', 'Rhinoceros', 'Crocodile', 'Gnu', 'Thompson Gazelle', 'Hyena', 'Crocodile', 'Zebra', 'Zebra', 'Gnu', 'Gnu', 'Crocodile', 'Gnu', 'Zebra', 'Baboon', 'Hyena', 'Leopard', 'Gnu', 'Vulture', 'Water Buffalo', 'Zebra', 'Leopard', 'Zebra', 'Gnu', 'Gnu', 'Zebra', 'Hippopotamus', 'Gnu', 'Vulture', 'Baboon', 'Dik Dik', 'Elephant', 'Gnu', 'Zebra', 'Gnu', 'Zebra', 'Gnu', 'Zebra', 'Zebra', 'Hyena', 'Thompson Gazelle', 'WartHog', 'Zebra', 'Giraffe', 'Gnu', 'Thompson Gazelle', 'Hippopotamus', 'Elephant', 'Zebra', 'Dik Dik', 'Crocodile', 'Gnu', 'Gnu', 'Cheetah', 'Gnu', 'Elephant', 'Gnu', 'Gnu', 'Gnu', 'Leopard', 'Hippopotamus', 'Baboon', 'Zebra', 'WartHog', 'WartHog', 'Gnu', 'Gnu', 'Zebra', 'Dik Dik', 'Crocodile', 'Gnu', 'Gnu', 'Gnu', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Water Buffalo', 'Hippopotamus', 'Zebra', 'WartHog', 'Crocodile', 'Gnu', 'Zebra', 'Crocodile', 'Gnu', 'WartHog', 'Zebra', 'WartHog', 'Zebra', 'Thompson Gazelle', 'Thompson Gazelle', 'Gnu', 'Hyena', 'Gnu', 'Gnu', 'Dik Dik', 'Baboon', 'WartHog', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Gnu', 'WartHog', 'Gnu', 'Zebra', 'Baboon', 'Dik Dik', 'Gnu', 'Zebra', 'Crocodile', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Crocodile', 'Vulture', 'Elephant', 'Baboon', 'Zebra', 'Gnu', 'Gnu', 'Gnu', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Baboon', 'Hippopotamus', 'Hyena', 'Zebra', 'Elephant', 'Zebra', 'Thompson Gazelle', 'Thompson Gazelle', 'Thompson Gazelle', 'WartHog', 'Gnu', 'Gnu', 'Elephant', 'Gnu', 'WartHog', 'WartHog', 'Gnu', 'Baboon', 'Dik Dik', 'Hippopotamus', 'Crocodile', 'Hyena', 'WartHog', 'Elephant', 'Vulture', 'Gnu', 'Baboon', 'Zebra', 'Thompson Gazelle', 'Hippopotamus', 'Crocodile', 'Zebra', 'Wild Dog', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Thompson Gazelle', 'Vulture', 'Thompson Gazelle', 'Gnu', 'Crocodile', 'Zebra', 'Gnu', 'Zebra', 'Zebra', 'Gnu', 'Gnu', 'Giraffe', 'Thompson Gazelle', 'Hyena', 'Zebra', 'Baboon', 'Lion', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Gnu', 'WartHog', 'Gnu', 'Zebra', 'Gnu', 'Gnu', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Hippopotamus', 'Zebra', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Lion', 'Gnu', 'Baboon', 'Gnu', 'Dik Dik', 'Gnu', 'Giraffe', 'Thompson Gazelle', 'Dik Dik', 'Zebra', 'Gnu', 'Gnu', 'Zebra', 'Gnu', 'WartHog', 'Leopard', 'Zebra', 'Hyena', 'Thompson Gazelle', 'Gnu', 'Thompson Gazelle', 'Hyena', 'Thompson Gazelle', 'Vulture', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Elephant', 'Baboon', 'Zebra', 'Gnu', 'Zebra', 'Zebra', 'Gnu', 'Gnu', 'Baboon', 'Elephant', 'Zebra', 'Baboon', 'Zebra', 'Lion', 'Baboon', 'Zebra', 'Zebra', 'Zebra', 'Zebra', 'Zebra', 'Thompson Gazelle', 'Thompson Gazelle', 'Zebra', 'Thompson Gazelle', 'Elephant', 'Zebra', 'Gnu', 'Zebra', 'Vulture', 'Cheetah', 'Water Buffalo', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Zebra', 'Zebra', 'Gnu', 'WartHog', 'Zebra', 'Dik Dik', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Giraffe', 'Hyena', 'Gnu', 'Vulture', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Water Buffalo', 'Leopard', 'Elephant', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Hyena', 'Leopard', 'Thompson Gazelle', 'Zebra', 'Zebra', 'Baboon', 'Giraffe', 'Gnu', 'Vulture', 'Gnu', 'Gnu', 'Gnu', 'Gnu', 'WartHog', 'Leopard', 'Zebra', 'Thompson Gazelle', 'Vulture', 'Baboon', 'Gnu', 'Baboon', 'Zebra', 'Gnu', 'Ostrich', 'Ostrich', 'Zebra', 'Hippopotamus', 'Vulture', 'Crocodile', 'Thompson Gazelle', 'Thompson Gazelle', 'Dik Dik', 'Gnu', 'Zebra', 'Gnu', 'Zebra', 'Crocodile', 'Gnu', 'Baboon', 'Gnu', 'Gnu', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Zebra', 'Crocodile', 'Gnu', 'Dik Dik', 'Rhinoceros', 'Vulture', 'Gnu', 'Hyena', 'Gnu', 'Lion', 'Zebra', 'Gnu', 'Gnu', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Baboon', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Gnu', 'Gnu', 'Vulture', 'Gnu', 'Gnu', 'Zebra', 'Water Buffalo', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Zebra', 'Zebra', 'Thompson Gazelle', 'Water Buffalo', 'Gnu', 'Giraffe', 'Thompson Gazelle', 'Crocodile', 'Gnu', 'Gnu', 'Gnu', 'Vulture', 'Elephant', 'Gnu', 'WartHog', 'Gnu', 'Gnu', 'Lion', 'Dik Dik', 'Gnu', 'Gnu', 'Zebra', 'Vulture', 'Gnu', 'WartHog', 'Gnu', 'Gnu', 'Gnu', 'Gnu', 'Vulture', 'Zebra', 'Gnu', 'WartHog', 'WartHog', 'Gnu', 'Hyena', 'Vulture', 'Vulture', 'Thompson Gazelle', 'Zebra', 'Zebra', 'Thompson Gazelle', 'Thompson Gazelle', 'Zebra', 'Zebra', 'WartHog', 'Vulture', 'Zebra', 'Crocodile', 'Elephant', 'Thompson Gazelle', 'Lion', 'Thompson Gazelle', 'Hyena', 'Gnu', 'Thompson Gazelle', 'Vulture', 'Gnu', 'Thompson Gazelle', 'Baboon', 'Zebra', 'Vulture', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Vulture', 'Gnu', 'Baboon', 'Thompson Gazelle', 'Gnu', 'Thompson Gazelle', 'Rhinoceros', 'Gnu', 'Zebra', 'Gnu', 'Gnu', 'Gnu', 'Zebra', 'Gnu', 'Gnu', 'Vulture', 'Elephant', 'Baboon', 'Baboon', 'Vulture', 'Zebra', 'Zebra', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Thompson Gazelle', 'Vulture', 'Wild Dog', 'Zebra', 'WartHog', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Gnu', 'Zebra', 'Gnu', 'Vulture', 'Gnu', 'Baboon', 'Thompson Gazelle', 'Gnu', 'Baboon', 'Giraffe', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Thompson Gazelle', 'Lion', 'Lion', 'Gnu', 'Lion', 'Zebra', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Giraffe', 'Gnu', 'Thompson Gazelle', 'Zebra', 'Gnu', 'Hippopotamus', 'Water Buffalo', 'Gnu', 'Giraffe', 'Gnu', 'Vulture', 'Gnu', 'Baboon', 'Gnu', 'Gnu', 'Dik Dik', 'Zebra', 'Zebra', 'Giraffe', 'Gnu', 'Zebra', 'Gnu', 'Baboon', 'Zebra', 'Elephant', 'Zebra', 'Gnu', 'Hyena', 'Zebra', 'Crocodile', 'Gnu', 'Thompson Gazelle', 'Giraffe', 'Wild Dog', 'Gnu', 'Thompson Gazelle', 'Thompson Gazelle', 'Crocodile', 'Thompson Gazelle', 'Gnu', 'Thompson Gazelle', 'Giraffe', 'Baboon', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Thompson Gazelle', 'WartHog', 'Thompson Gazelle', 'Thompson Gazelle', 'Hyena', 'Hyena', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Thompson Gazelle', 'WartHog', 'Zebra', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Hippopotamus', 'Elephant', 'Gnu', 'Baboon', 'Vulture', 'Elephant', 'Baboon', 'Hyena', 'Crocodile', 'Gnu', 'Elephant', 'Crocodile', 'Zebra', 'Thompson Gazelle', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Gnu', 'Zebra', 'Hippopotamus', 'Hyena', 'Hippopotamus', 'Thompson Gazelle', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Baboon', 'Zebra', 'Gnu', 'Hyena', 'Gnu', 'Hippopotamus', 'Gnu', 'WartHog', 'Elephant', 'Vulture', 'Thompson Gazelle', 'Zebra', 'Thompson Gazelle', 'Water Buffalo', 'Zebra', 'Giraffe', 'Baboon', 'Water Buffalo', 'WartHog', 'Zebra', 'Gnu', 'Zebra', 'Zebra', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Zebra', 'Zebra', 'Leopard', 'Vulture', 'Gnu', 'Thompson Gazelle', 'Rhinoceros', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Gnu', 'Gnu', 'Gnu', 'Gnu', 'Zebra', 'Thompson Gazelle', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Lion', 'Gnu', 'Gnu', 'Crocodile', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Gnu', 'Gnu', 'Baboon', 'Thompson Gazelle', 'Gnu', 'Vulture', 'Elephant', 'Thompson Gazelle', 'Gnu', 'Vulture', 'Thompson Gazelle', 'Zebra', 'WartHog', 'Zebra', 'Thompson Gazelle', 'Giraffe', 'Giraffe', 'WartHog', 'Gnu', 'Gnu', 'Thompson Gazelle', 'Gnu', 'Gnu', 'Zebra', 'Thompson Gazelle']#print(short_animal_list)#print(medium_animal_list)#print(long_animal_list)# 1) Pick an animal from the 'animal_types' list and count # how many there are in the 'short_animal_list'. Then count # from the 'medium' list and the 'long' list# 2) Look at the 'animal_types' list and count the number of # each animal from the short, medium, and ling listelephant_count = 0lion_count = 0gnu_count = 0#-------------------------------# ---- Enter Your Code Here ----def Counter(x,y) : for i in short_animal_list : if i == x : y = y + 1 print(i) print('found',i) return (y)Counter('Gnu',gnu_count)#-------------------------------# Outputprint('Animal Count')print('Elephants = ',elephant_count)print('Lions = ',lion_count)print("Gnu = ",gnu_count)
The assignment inside a function does not modify the global variable. To modify a global variable from inside a function, use the global keyword as shown below.def Counter(x,y) : for i in short_animal_list : if i == x : y = y + 1 print(i) print('found',i) print(y) global gnu_count gnu_count = y return (y)
pip install numpy error - Unmatched " I am trying to install numpy in a python3 virtual environmentpython3 -m venv venvsource venv/bin/activatepip install numpyAfter running the above, the installation fails with an error something like this...error Command "gcc ..." failed with exit status 1Unmatched ".Unmatched ".Why does this happen and how can I install numpy correctly
When you install numpy using pip, it runs various shell commands to build the parts of numpy that are written in c. Your environment's $SHELL variable will be used to determine which shell to use. In this case, csh is being used but the command in the installation script expects to be able to use bash like syntax.Make sure your $SHELL is set to /bin/bash before buildingThe syntax for this depends on your shellbash/zsh:export SHELL="/bin/bash"fish:set -x SHELL "/bin/bash/"csh:setenv SHELL /bin/bashNow you should be able to run pip install numpy again, and it might work this time.[This is possibly a {bug/oversight} in numpy]
Pulling API data into Django Template that has tags embedded, is there a way of wrapping the text in an HTML tag? I'm reading a very large API, one of the fields I need, have "a" tags embedded in the item in the dictionary and when I pull it into my template and display it, it shows the "a" tags as text.exp:"Bitcoin uses the <a href="https://www.coingecko.com/en?hashing_algorithm=SHA-256">SHA-256</a> hashing... ...such as <a href="https://www.coingecko.com/en/coins/litecoin">Litecoin</a>, <a href="https://www.coingecko.com/en/coins/peercoin">Peercoin</a>, <a href="https://www.coingecko.com/en/coins/primecoin">Primecoin</a>*"I would like to wrap this in HTML so when it displays on the page it has the actual links rather than the 'a' tags and the URL.What I'm looking to get: "Bitcoin uses the SHA-256 hashing... ...such as Litecoin, Peercoin, Primecoin*"
I figured it out, I used the Humanize function with the |safe tag.Pretty simple answer.In the settings.py add 'django.contrib.humanize' to the INSTALLED_APPS:**INSTALLED_APPS = ['django.contrib.humanize', ]**In the HTML Template add {% load humanize %}For the data you want to format use |safe{{ location.of.data|safe }}This will read the text as HTML.
How can I simplify adding columns with certain values to my dataframe? I have a big dataframe (more than 900000 rows) and want to add some columns depending on the first column (Timestamp with date and time). My code works, but I guess it's far too complicated and slow. I'm a beginner so help would be appreciated! Thanks!df['seconds_midnight'] = 0df['weekday'] = 0df['month'] = 0def date_to_new_columns(date_var, i): sec_after_midnight = dt.timedelta(hours=date_var.hour, minutes=date_var.minute, seconds=date_var.second).total_seconds() weekday = dt.date.isoweekday(date_var) month1 = date_var.month df.iloc[i, 24] = sec_after_midnight df.iloc[i, 25] = weekday df.iloc[i, 26] = month1 returnfor i in range(0, 903308): date_to_new_columns(df.timestamp.iloc[i], i)
If the column is a datetime64/Timestamp column you can use the .dt accessor:In [11]: df = pd.DataFrame(pd.date_range('2019-01-23', periods=3), columns=['date'])In [12]: dfOut[12]: date0 2019-01-231 2019-01-242 2019-01-25In [13]: df.date - df.date.dt.normalize() # timedelta since midnightOut[13]:0 0 days1 0 days2 0 daysName: date, dtype: timedelta64[ns]In [14]: (df.date - df.date.dt.normalize()).dt.seconds # seconds since midnightOut[14]:0 01 02 0Name: date, dtype: int64In [15]: df.date.dt.day_name()Out[15]:0 Wednesday1 Thursday2 FridayName: date, dtype: objectIn [16]: df.date.dt.month_name()Out[16]:0 January1 January2 JanuaryName: date, dtype: object
JavaScript not 'unclicking' button and its affecting Flask I am trying to create buttons on my webpage that apply a filter to a camera feed using a Python backend.My two javascript buttons, Filter on / Filter off have an execution problem. When a button is pressed for the first time the system works. But when the next button is pressed it does not 'unpress' the first button and therefore the requests to flask are mixed together.I've included a print statement in the code to demonstrate the problem.When the filter button is pressed the first time, the loop is consistent and displays the pressed parameter 1, 1, 1, 1, 1, 1, 1. Once I press the second button the results become inconsistent 1, 0, 0, 0, 1, 0, 1, 1, 1The same behaviour is true regardless of which button I press first.I need the results to be 1, 1, 1, 1, 1.... etc or 0, 0, 0, 0, 0 depending on which button is pressed.Assistance will be greatly appreciated,Thanks#### Javascript ### $(function(){ $(document).ready(function(){ $("#filterOn").click(function(){ filterOn(); }); $("#filterOff").click(function(){ filterOff(); }); }); function filterOn(){ $.get('/video_feed/1'); } function filterOff(){ $.get('/video_feed/0'); } ######### Backend Python using Flask ##########def Capture_data(filter): while True: success, image = video.read() print(filter) ###### Troubleshooting line here ######### if filter == 1: image = filtered_spectrum(image) encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90] ret, jpeg2 = cv2.imencode('.jpg', image, encode_param) frame = jpeg2.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')@app.route('video_feed') @app.route('video_feed/<int:toggle>')def video_feed(toggle): if toggle == 0: return Response(Capture_data(0), mimetype='multipart/x-mixed-replace; boundary=frame') if toggle == 1: return Response(Capture_data(1), mimetype='multipart/x-mixed-replace; boundary=frame')
If they are radios, they need the same nameAlso you wrap in too many load directivesfunction filterOn(){ $.get('/video_feed/1'); // normally one needs to do something with that} function filterOff(){ $.get('/video_feed/0');} $(function(){ $("#filterOn").on("click",filterOn) $("#filterOff").on("click",filterOff)})<label><input type="radio" name="filter" id="filterOn">On</label><label><input type="radio" name="filter" id="filterOff">Off</label>
Show the sum for multiple items I've a data dictionary, I want to pickup some items for exemple at the 2nd range, from different lists as value of dictionary every key start with 111####, I created this method but how, I can get the sum off all items and insert it at QTableWidget cell?import sysfrom PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem)from PyQt5.QtGui import QBrush, QColor from PyQt5 import QtCoredata = {'1111':['Title 1','12521','94565','','','','684651','','','44651','','',''], '1112':['Title 2','65115','','466149','46645','555641','','','','412045','98416','',''], '1113':['Title 3','243968','','','466149','46645','555641','98656','','','412045','98416','','']} class Table(QWidget): def __init__(self, *args, parent=None): super().__init__() self.data = data self.setupUi()def setuptUI(self): self.setWindowTitle("QTableWidgetItem") self.resize(1200, 800) conLayout = QHBoxLayout() self.tableWidget =QTableWidget(self) self.tableWidget.setRowCount(55) self.tableWidget.setColumnCount(14) conLayout.addWidget(self.tableWidget)def setdata(self, k, v, n, m): i= 1 l = str(k*10) while I < 4 item = self.data.get(str(int(l)+i))[v] print(item) i= i+1 if v== " ": break #sum_instruction newItem = QTableWidgetItem(str(item)) newItem.setForeground(QBrush(QColor(255, 0, 0))) self.tableWidget.setItem(m, n, newItem)if __name__ == '__main__': app = QApplication(sys.argv) windows = Table(data) windows.setdata(k="113", v=5, n=25, m=4 windows.show() sys.exit(app.exec_())
Try it:import sysfrom PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem)from PyQt5.QtGui import QBrush, QColor from PyQt5 import QtCore# vvvvvvdata = {'1111':['Title 1','12521', '94565','', '', '777777','684651','','','44651','','',''], '1112':['Title 2','65115', '', '466149','46645', '555641','','','','412045','98416','',''], '1113':['Title 3','243968','', '', '466149','46645', '555641','98656','','','412045','98416','','']} # ^^^^^^class Table(QWidget): def __init__(self, data): super().__init__() self.data = data self.setupUi() def setupUi(self): conLayout = QHBoxLayout(self) # self self.tableWidget = QTableWidget(self) self.tableWidget.setRowCount(55) self.tableWidget.setColumnCount(14) conLayout.addWidget(self.tableWidget) def setdata(self, k, v, n, m): print(k, v, n, m) i = 1# l = str(k*10) l = str(int(k)*10) s = 0 while i < 4: item = self.data.get(str(int(l)+i))[v] print(item) i = i+1# if v == " ":# break #sum_instruction s = s + (int(item) if item else 0) newItem = QTableWidgetItem(str(item)) newItem.setForeground(QBrush(QColor(255, 0, 0))) self.tableWidget.setItem(m, n, newItem) n += 1 # +++ newItem = QTableWidgetItem(str(s)) newItem.setForeground(QtCore.Qt.blue) self.tableWidget.setItem(m, n, newItem)if __name__ == '__main__': app = QApplication(sys.argv) windows = Table(data)# windows.setdata(k="113", v=5, n=25, m=4) windows.setdata(k="111", v=5, n=2, m=4) windows.setWindowTitle("QTableWidgetItem") windows.resize(1100, 700) windows.show() sys.exit(app.exec_())
Copying python scripts from local to remote mahcine I have two computers, both windows 64-bit machines. Call the local computer machine A and the remote computer machine B. I have a script.py file on machine A. Without leaving machine A, I want to:Copy script.py onto machine B; Run script.py on machine B;Get the output on machine A.I'm having problems with step 1.Steps 2. and 3. are solved already. I've configured both computers so that I can successfully run from PowerShell6 Invoke-Commands. The PSSessions established between machine A and B are functional. I can successfully run a script.py that is on machine B from machine A:Enter-PSSession -hostname $hostname -username pshell -ScriptBlock{c:\Users\pshell\Anaconda3\python.exe script.py};and get the output back to machine A. However, I don't know find the commands to copy script.py from machine A to machine B. I think it's a relatively easy task but I can't find the relevant commands. Any indications/suggestions not including third-party software/packages are welcome.
From Is there a SCP alternative for PowerShell?: the little tool pscp.py, which comes with Putty can solve your task 1. For an example with PowerShell see this answer.
Python count element occurrence of list1 in list2 In the following code, I want to count the occurrence of every word in word_list in test, the code below can do this job but it may not be efficient, is there any better way to do it?word_list = ["hello", "wonderful", "good", "flawless", "perfect"]test = ["abc", "hello", "vbf", "good", "dfdfdf", "good", "good"]result = [0] * len(word_list)for i in range(len(word_list)): for w in test: if w == word_list[i]: result[i] += 1print(result)
Use collections.Counter to count all the words in test in one go, then just get that count from the Counter for each word in word_list.>>> word_list = ["hello", "wonderful", "good", "flawless", "perfect"]>>> test = ["abc", "hello", "vbf", "good", "dfdfdf", "good", "good"]>>> counts = collections.Counter(test)>>> [counts[w] for w in word_list][1, 0, 3, 0, 0]Or using a dictionary comprehention:>>> {w: counts[w] for w in word_list}{'perfect': 0, 'flawless': 0, 'good': 3, 'wonderful': 0, 'hello': 1}Creating the counter should be O(n), and each lookup O(1), giving you O(n+m) for n words in test and m words in word_list.
Tkinter copy to clipboard not working in PyCharm I just installed PyCharm and opened up a script I had been using in IDLE that did some string manipulation then copied it to the clipboard, but it doesn't work when I run it in PyCharm. from tkinter import Tkr = Tk()r.withdraw()r.clipboard_clear()r.clipboard_append("test")r.destroy()When I run this in IDLE I am able to paste "test" after, but in PyCharm it just says "Process finished with exit code 0" but there is nothing in the clipboard (even if there was before running). I have Python 3.5 as the selected interpreter.
There seems to be problem if the clipboard is manipulated and the program closes too quickly soon after. The following program worked for me but was unreliable when the call to root.after only used one millisecond for the delay. Other possibilities were tried, but code down below should work:import randomimport stringimport tkinterdef main(): root = tkinter.Tk() root.after_idle(run_code, root) root.after(100, root.destroy) root.mainloop()def run_code(root): root.withdraw() root.clipboard_clear() root.clipboard_append(''.join(random.sample(string.ascii_letters, 10))) print('Clipboard is ready.')if __name__ == '__main__': main()The following is a mildly more useful version of the program and demonstrates that you can make many calls to root.after_idle to run your code in a sequential manner. Its design is primarily for use to process command-line arguments and send them to your clipboard for you:import sysimport tkinterdef main(argv): root = tkinter.Tk() root.after_idle(root.withdraw) root.after_idle(root.clipboard_clear) root.after_idle(root.clipboard_append, ' '.join(argv[1:])) root.after_idle(print, 'The clipboard is ready.') root.after(100, root.destroy) root.mainloop() return 0if __name__ == '__main__': sys.exit(main(sys.argv))
Python Data Frame: cumulative sum of column until condition is reached and return the index I am new in Python and am currently facing an issue I can't solve. I really hope you can help me out. English is not my native languge so I am sorry if I am not able to express myself properly.Say I have a simple data frame with two columns:index Num_Albums Num_authors0 10 41 1 52 4 43 7 10004 1 445 3 8Num_Abums_tot = sum(Num_Albums) = 30I need to do a cumulative sum of the data in Num_Albums until a certain condition is reached. Register the index at which the condition is achieved and get the correspondent value from Num_authors.Example:cumulative sum of Num_Albums until the sum equals 50% ± 1/15 of 30 (--> 15±2):10 = 15±2? No, then continue;10+1 =15±2? No, then continue10+1+41 = 15±2? Yes, stop. Condition reached at index 2. Then get Num_Authors at that index: Num_Authors(2)=4I would like to see if there's a function already implemented in pandas, before I start thinking how to do it with a while/for loop....[I would like to specify the column from which I want to retrieve the value at the relevant index (this comes in handy when I have e.g. 4 columns and i want to sum elements in column 1, condition achieved =yes then get the correspondent value in column 2; then do the same with column 3 and 4)].
Opt - 1:You could compute the cumulative sum using cumsum. Then use np.isclose with it's inbuilt tolerance parameter to check if the values present in this series lies within the specified threshold of 15 +/- 2. This returns a boolean array. Through np.flatnonzero, return the ordinal values of the indices for which the True condition holds. We select the first instance of a True value.Finally, use .iloc to retrieve value of the column name you require based on the index computed earlier.val = np.flatnonzero(np.isclose(df.Num_Albums.cumsum().values, 15, atol=2))[0]df['Num_authors'].iloc[val] # for faster access, use .iat 4When performing np.isclose on the series later converted to an array:np.isclose(df.Num_Albums.cumsum().values, 15, atol=2)array([False, False, True, False, False, False], dtype=bool)Opt - 2:Use pd.Index.get_loc on the cumsum calculated series which also supports a tolerance parameter on the nearest method.val = pd.Index(df.Num_Albums.cumsum()).get_loc(15, 'nearest', tolerance=2)df.get_value(val, 'Num_authors')4Opt - 3:Use idxmax to find the first index of a True value for the boolean mask created after sub and abs operations on the cumsum series:df.get_value(df.Num_Albums.cumsum().sub(15).abs().le(2).idxmax(), 'Num_authors')4
How to set Environment Variable for NLTK in Mac? I recently downloaded nltk_data in Macintosh HD 2 (Renamed "External") since my main HD is out of memory, can someone help me in setting environment variables for the same? I tried the following in my .bash_profile however it just runs temporarily till bash runs, I need to make the change permanent:PATH="$/Volumes/External/bin:$PATH"export PATH
Setting environment variables on OS X is a bit tricky, and it's a moving target: Stackoverflow is full of good solutions that no longer work.If your goal is to use the nltk from programs or applications that you launch from Terminal, then it's pretty straightforward; in your .bash_profile or .bashrc, set and export the required variables. If you have trouble launching the right Python or idle executable, add the directory that contains them to your PATH variable pretty much as you show in your question. (But the first $ you show is a mistake: This path is not a shell variable).export PATH="/Volumes/External/bin:$PATH"To allow the nltk to find the corpora and resources you downloaded with nltk.download(), set the NLTK_DATA variable. E.g.,export NLTK_DATA=/Volumes/External/nltk_dataIt looks like your question was answered by the second bullet, but I give both since it's not always clear (to new users) which one is relevant.Be aware that applications you launch from the Launchpad (e.g., the Anaconda launcher) will not be able to see variables you set in this way. That is a more complicated problem to solve, as mentioned above, and as far as I know there is no solution that will work for all applications in recent OS X versions. Just launch your python application or IDE from the command line (by typing idle, subl etc. at the bash prompt), and you'll be all right.
What’s the best way to Convert a list to dict in Python2.7 I have a list like: x = ['user=inci', 'password=1234', 'age=12', 'number=33']I want to convert x to a dict like:{'user': 'inci', 'password': 1234, 'age': 12, 'number': 33}what's the quickest way?
You can do this with a simple one liner:dict(item.split('=') for item in x)List comprehensions (or generator expressions) are generally faster than using map with lambda and are normally considered more readable, see here.
Making my IDE take a specific Python version I have Python 2.7.8 installed and when doing the version check in my command line, it shows that I have Python 2.7.8. However, when I run PyCharm it's running it on version 2.6. Is there a way for me to get it to make PyCharm take the 2.7.8 version?Thanks for the help!
By default, PyCharm picks up the Python installed system-wide. Which Python your project should use is configured under Project Interpreter section of your Project Settings. From there, you can add existing interpreters either locals, or remotes, even create brand-new virtual environments and manage packages inside.
How to call from within Python an application with double quotes around an argument using subprocess? I'm trying to call certutil from inside python. However I need to use quotation marks and have been unable to do so. My code is as follows:import subprocessoutput= subprocess.Popen(("certutil.exe", "-view", '-restrict "NotAfter <= now+30:00, NotAfter >= now+00:00"' ), stdout=subprocess.PIPE).stdoutfor line in output: print(line)output.close()I thought the single quotes would allow me to use double quotes inside the string.Also I have tried using double quotes with the escape character (\"), however I keep getting the same error:Unknown arg: -restrict \\NotAfter\r\n'For some reason it seems to be translating " into \\.Can anyone give insight as to why and how to fix it?
I do not have Python in any version installed. But according to answer on How do I used 2 quotes in os.system? PYTHON and documentation of subprocess, subprocess handles requirement for double quotes on arguments with space automatically.So you should need to use simply:import subprocessoutput= subprocess.Popen(("certutil.exe", "-view", "-restrict", "NotAfter <= now+30:00, NotAfter >= now+00:00" ), stdout=subprocess.PIPE).stdoutfor line in output: print(line)output.close()And the command line used on calling certutil is:certutil.exe -view -restrict "NotAfter <= now+30:00, NotAfter >= now+00:00"
failing scipy.minimize for multiple constraints I would like to minimize the following function using scipy.minimizedef lower_bound(x, mu, r, sigma): mu_h = mu_hat(x, mu, r) sigma_h = sigma_hat(x, sigma) gauss = np.polynomial.hermite.hermgauss(10) return (1 + mu_h + math.sqrt(2) * sigma_h * min(gauss[1]))all the involved function are tested and return values as expected. Now for setting up the minimization process, I definedcons = ({"type": "ineq", "fun": mu_hat, "args": (mu, r)}, {"type": "ineq", "fun": lambda x, sigma: -1.0*sigma_hat(x, sigma), "args": (sigma)}, {"type": "ineq", "fun": lambda x: x}, {"type": "ineq", "fun": lambda x: 1-np.dot(np.ones(x.size), x)})as the constraints. When I run this code scipy.minimize gives me the following error message for the constraints:File "/usr/local/lib/python3.5/dist-packages/scipy/optimize/slsqp.py", line 312, in <listcomp> mieq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in cons['ineq']]))TypeError: <lambda>() argument after * must be an iterable, not floatwhat is not correct with the defined constraints?
The error message says:mieq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in cons['ineq']]))TypeError: <lambda>() argument after * must be an iterable, not floatSo we can infer that c['args'] is of type float, because c['args'] is the only variable with * applied to it. Clearly the lookup of 'args' in c has succeeded, so we know that c is a float where an iterable (list, tuple, etc.) was expected.If we now look at your constraints, the args passed are (mu, r) in one case and (sigma) in the other. The problem is clear now: (sigma) is equivalent to sigma, and is not a tuple. To make a 1-tuple in Python, you must say (sigma,).
Tweepy: simple script with 'Bad Authentication data' error Is this really an authentication problem or has it to do with something else? What do I have to modify to get rid of the error?#!/usr/bin/env pythonimport tweepyckey = 'xxx'csecret = 'xxx'atoken = 'xxx'asecret = 'xxx'auth = tweepy.OAuthHandler(ckey, csecret)auth.set_access_token(atoken, asecret)api = tweepy.API(auth)results = tweepy.api.search(geocode='50,50,5mi')for result in results: print result.text print result.location if hasattr(result, 'location') else "Undefined location"This is the error I getC:\Python27\python.exe C:/untitled/testfile.pyTraceback (most recent call last): File "C:/untitled/testfile.py", line 18, in <module> results = tweepy.api.search(geocode='50,50,5mi') File "build\bdist.win-amd64\egg\tweepy\binder.py", line 197, in _call File "build\bdist.win-amd64\egg\tweepy\binder.py", line 173, in executetweepy.error.TweepError: [{u'message': u'Bad Authentication data', u'code': 215}]
Your doing it wrong:It should be-#!/usr/bin/env pythonimport tweepyckey = 'xxx'csecret = 'xxx'atoken = 'xxx'asecret = 'xxx'auth = tweepy.OAuthHandler(ckey, csecret)auth.set_access_token(atoken, asecret)api = tweepy.API(auth)# here's where you went wrong (tried and tested), should be#results = api.search(geocode='50,50,5mi')# try with the following lat longresults = api.search(geocode='39.833193,-94.862794,5mi') for result in results: print result.text print result.location if hasattr(result, 'location') else "Undefined location"
Iterating Through a List to create a Stock checker So to begin I am new to programming in general (3 months or so in) and although learning through books is good I do like to try and apply my knowledge and learn through experience. At my work our warehouse staff often pick orders wrong so I am trying to develop something that will pull an order list from a .txt file and check it against the picked item. I feel this is a task I can use to consolidate some of my current knowledge whilst also learning new things.from tkinter.filedialog import askopenfilename#This splits the order .txt file into a listdef picklist(ordernum): with open(ordernum, "r") as f: mylist = [line.strip() for line in f]return mylistdef test(list): pickeditem = input("Please scan the first item") for i in range(len(list)): if list[i] == pickeditem: print("Correct item.") else: while list[i] != pickeditem: input("Wrong item! Please scan again:") if list[i] == pickeditem: print("Correct item.")def order(): print("Please pick the order you want to complete") order = askopenfilename() #gets order .txt from user pcklist = picklist(order) print("You pick list is: ",pcklist) test(pcklist)order()So the general idea is to creata a .txt file with a list of item serial codes that need pulling and then get that in python within the order function that I created. I then use the picklist function to split the items that are stored in the .txt file into a list so that I can get the user to scan one item at a time to verify it is the correct one. This is where I'm trying to call on what is currently called the test function. I want this function to take each item within the list and if it is equal to the item scanned to print that is is the correct item. This works kind of fine, well perfectly fine for the first item. The problem is getting it to iterate onto the next item in the list. So if item one is 2155 and item 2155 is scanned it will say correct item. The issue is it will then say "Wrong item! Please scan again:" because I assume pythong has now moved onto item 2 in the list. But, if I then input the code for 2 it will say wrong item! Please scan again.I've tried using list indexing to no avial - maybe I should be doing this in a single function and not splitting it as I am.I am certainly not looking for anyone to finish the code for me but really point me in the right direction of what I need to learn. The final goal of the project is for it also to hold information regarding the warehouse location for each item, the amount of each item needed, and the ability to pull the picklist off of our internal order system. However, they're things I want to integrate bit by bit as I learn. I understand this probably is not the slickest, most pythonic code ever but really im after something easy to read, understand and edit in the future.For now I just need to understand what I need to learn / how I need to think about this issue so that I can check each item in the .txt file provided matches each item scanned by the user.Thanks in advance.
For each item in the list you want to scan a picked item and compare them; if the comparison fails you want to continually scan picked items until they match. You are really close - in the else suite the comparison with the new scanned item needs to be in the loop, the indentation is wrong; you also need to assign input's return value to pickeditem, while list[i] != pickeditem: pickeditem = input("Wrong item! Please scan again:") if list[i] == pickeditem: print("Correct item.")Then at the bottom of the for loop, you need to scan the next item picked to compare it to the next item in the list.def test(list): pickeditem = input("Please scan the first item") for i in range(len(list)): if list[i] == pickeditem: print("Correct item.") else: while list[i] != pickeditem: pickeditem = input("Wrong item! Please scan again:") if list[i] == pickeditem: print("Correct item.") pickeditem = input("Please scan the next item")The else suite could be simplified a bit - the while statement makes the comparison for you so you don't need to check it again with the if statement:def test(list): pickeditem = input("Please scan the first item") for i in range(len(list)): if list[i] == pickeditem: print("Correct item.") else: while list[i] != pickeditem: pickeditem = input("Wrong item! Please scan again:") print("Correct item.") pickeditem = input("Please scan the next item")You should always try to simplify the logic to minimize potential for problems/errors and it can make the code easier to read. The if/else statement is not really needed because the comparison is being made with the while statement.def test(list): pickeditem = input("Please scan the first item") for i in range(len(list)): while list[i] != pickeditem: pickeditem = input("Wrong item! Please scan again:") print("Correct item.") pickeditem = input("Please scan the next item")When iterating with a for loop you don't need to use indices, you can iterate over the sequence items directly. You shouldn't use python keywords, function or class names for your variable names, i changed the list name to a_list.def test(a_list): pickeditem = input("Please scan the first item") for item in a_list: while item != pickeditem: pickeditem = input("Wrong item! Please scan again:") print("Correct item.") pickeditem = input("Please scan the next item")If you need to keep track of the item indices while iterating, use enumerate.You might be interested in the SO answer for: Asking a user for input till they give a valid response.
Character @ in a :: literal I am trying to include in my source .rst file literal producing text like::: @reboot myscriptHowever @reboot appears in boldface. Did not find how to avoid it.
Very easy -- just precede with the following line:.. highlight:: noneOtherwise Sphinx assumes it is Python code (default)!
python SimpleHTTPServer suspended, how to stop? I accidentally hit ctrl z instead of ctrl c to stop python SimpleHTTPServer and it came up saying[1] + 35296 suspended python -m SimpleHTTPServernow I cannot restart it on the same port as port 8000 is in useTraceback (most recent call last):File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 162, in _run_module_as_main"__main__", fname, loader, pkg_name)File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_codeexec code in run_globalsFile "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SimpleHTTPServer.py", line 220, in <module>test()File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SimpleHTTPServer.py", line 216, in testBaseHTTPServer.test(HandlerClass, ServerClass)File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/BaseHTTPServer.py", line 595, in testhttpd = ServerClass(server_address, HandlerClass)File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 419, in __init__self.server_bind()File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/BaseHTTPServer.py", line 108, in server_bindSocketServer.TCPServer.server_bind(self)File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 430, in server_bindself.socket.bind(self.server_address)File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 224, in methreturn getattr(self._sock,name)(*args)socket.error: [Errno 48] Address already in useHow can I stop this process so that I can use port 8000 again?Thanks
The process is suspended in the background, you'll have to kill it for it to release the port.If you're in the same terminal, running fg will bring it to the front and reactivate it, letting you interrupt it normally with CTRL+C.If you're not, you can use that number that got printed (the process ID, or PID) to kill it, but you'll first have to reactivate it, so that it can react:kill -CONT 35296kill 35296
Pandas: Rolling mean over array of windows Similar to this answer, I can calculate multiple rolling meansd1 = df.set_index('DateTime').sort_index()ma_1h = d1.groupby('Event').rolling('H').mean()ma_2h = d1.groupby('Event').rolling('2H').mean()But how can I do this performantly if I want to do it for a list of arrays?window_array = ['H','3H','6H','9H'] # etcAnd that my rolling means are included back into my original dataframe
I believe you need convert offsets and create new DataFrames in loop by list comprehension, last concat:from pandas.tseries.frequencies import to_offsetdf1 = pd.concat([d1.groupby('Event').rolling(to_offset(x)).mean() for x in window_array], axis=1, keys=window_array)Sample:rng = pd.date_range('2017-04-03', periods=10, freq='38T')df = pd.DataFrame({'DateTime': rng, 'a': range(10), 'Event':[4] * 3 + [3] * 3 + [1] * 4}) print (df)from pandas.tseries.frequencies import to_offsetwindow_array = ['H','3H','6H','9H']d1 = df.set_index('DateTime').sort_index()a = pd.concat([d1.groupby('Event')['a'].rolling(to_offset(x)).mean() for x in window_array], axis=1, keys=window_array)print (a) H 3H 6H 9HEvent DateTime 1 2017-04-03 03:48:00 6.0 6.0 6.0 6.0 2017-04-03 04:26:00 6.5 6.5 6.5 6.5 2017-04-03 05:04:00 7.5 7.0 7.0 7.0 2017-04-03 05:42:00 8.5 7.5 7.5 7.53 2017-04-03 01:54:00 3.0 3.0 3.0 3.0 2017-04-03 02:32:00 3.5 3.5 3.5 3.5 2017-04-03 03:10:00 4.5 4.0 4.0 4.04 2017-04-03 00:00:00 0.0 0.0 0.0 0.0 2017-04-03 00:38:00 0.5 0.5 0.5 0.5 2017-04-03 01:16:00 1.5 1.0 1.0 1.0