lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
Does an immutable object in python mean that its value can not be changed after its conception ? If that is the case what will happen when we try to change its value . Let me try to explain my doubt with an example.For instance I initialized a String object S with value `` Hello World '' .Then I typed in the line , So ...
S = 'Hello World ' S = 'Hello Human '
What happens to a immutable object in python when its value is changed ?
Python
What are the necessary maths to achieve the camera panning effect that 's used in 3ds max ? In 3ds max the distance between the cursor and the mesh will always remain the same throughout the entire movement ( mouse_down+mouse_motion+mouse_up ) .My naive and failed attempt has been trying to move the camera on the plane...
def glut_mouse ( self , button , state , x , y ) : self.last_mouse_pos = vec2 ( x , y ) self.mouse_down_pos = vec2 ( x , y ) def glut_motion ( self , x , y ) : pos = vec2 ( x , y ) move = self.last_mouse_pos - pos self.last_mouse_pos = pos self.pan ( move ) def pan ( self , delta ) : forward = vec3.normalize ( self.tar...
How to implement camera pan like in 3dsMax ?
Python
i want to expand a listby ne.g . for n = 2 : I 'm searching for the smallest possible way to achieve this without any additional librarys.Its easy to do a loop and append each item n times to a new list ... but is there a other way ?
[ 1,2,3,4 ] [ 1,1,2,2,3,3,4,4 ]
Smallest way to expand a list by n
Python
Is it possible to 'rollback ' the random number generator by a specified number of steps to a earlier state to get repeated random numbers ? I want to be able to do something like this : My only current idea to accomplish this is to store all generated random numbers into a list to go back to . However , I would person...
print ( random.random ( ) ) 0.5112747213686085print ( random.random ( ) ) 0.4049341374504143print ( random.random ( ) ) 0.7837985890347726random.rollback ( 2 ) # go back 2 stepsprint ( random.random ( ) ) 0.4049341374504143print ( random.random ( ) ) 0.7837985890347726
Rolling back the random number generator in python ?
Python
I 'm using Python 3.3BUTIs this a bug in the sub method or does the sub method not recognize \0 on purpose for some reason ?
re.sub ( `` ( . ) ( . ) '' , r '' \2\1\g < 0 > '' , '' ab '' ) returns baab re.sub ( `` ( . ) ( . ) '' , r '' \2\1\0 '' , '' ab '' ) returns ba
Why \g < 0 > behaves differently than \0 in re.sub ?
Python
I am a location in a dataframe , underneath lat lon column names . I want to show how far that is from the lat lon of the nearest train station in a separate dataframe.So for example , I have a lat lon of ( 37.814563 144.970267 ) , and i have a list as below of other geospatial points . I want to find the point that is...
< bound method NDFrame.to_clipboard of STOP_ID STOP_NAME LATITUDE \0 19970 Royal Park Railway Station ( Parkville ) -37.781193 1 19971 Flemington Bridge Railway Station ( North Melbo ... -37.788140 2 19972 Macaulay Railway Station ( North Melbourne ) -37.794267 3 19973 North Melbourne Railway Station ( West Melbourne )...
Python location , show distance from closest other location
Python
However , this message does n't get the HTML mime type when it is sent . In my outlook , I see the code ...
MYMESSAGE = `` < div > Hello < /div > < p > < /p > Hello '' send_mail ( `` testing '' , MYMESSAGE , '' noreply @ mydomain.com '' , [ 'assdf @ gmail.com ' ] , fail_silently=False )
How do I send an email in Django with a certain mimetype ?
Python
I have a simple Python server that uses http.server . The goal is not to show the video in a html page , or to download the video file , but to display the video in the browser directly . This is what I have so far : The problem that I have is that the response does n't contain the full video . file.mp4 is 50MB , but w...
import http.serverclass SuperHandler ( http.server.SimpleHTTPRequestHandler ) : def do_GET ( self ) : path = self.path encodedFilePath = 'file.mp4 ' with open ( encodedFilePath , 'rb ' ) as videoFile : self.send_response ( 200 ) self.send_header ( 'Content-type ' , 'video/mp4 ' ) self.end_headers ( ) self.wfile.write (...
Browsers close socket before the response is fully downloaded
Python
C does n't guarantee any evaluation order so a statement like f ( g1 ( ) +g2 ( ) , g3 ( ) , g4 ( ) ) might execute g1 ( ) , g2 ( ) , g3 ( ) , and g4 ( ) in any order ( although f ( ) would be executed after all of them ) What about Python ? My experimentation for Python 2.7 shows that it appears to be left-to-right ord...
def somefunc ( prolog , epilog ) : print prolog def f ( a , b , *args ) : print epilog return f def f ( text ) : print text return 1somefunc ( 'f1 ' , 'f2 ' ) ( f ( 'hey ' ) , f ( 'ho ' ) , f ( 'hahaha ' ) , f ( 'tweedledee ' ) +f ( 'tweedledum ' ) ) f1heyhohahahatweedledeetweedledumf2
Is Python 's order of evaluation of function arguments and operands deterministic ( + where is it documented ) ?
Python
I 'm making a simple tkinter Text editor , but i want all default bindings of the Text widget removed if possible.For example when i press Ctrl + i it inserts a Tab character by default.I made an event binding that prints how many lines are in the text box , I set the event binding to Ctrl + i as well.When i run it , I...
from tkinter import *class comd : # Contains primary commands # Capital Rule -- -- -- -- -- -- -- -- -- -- -- -- -- -- # G = Get | I = Insert | D = Draw | S = Set # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - def Ggeo ( self ) : # Get Geometry ( Get window geometry ) x = root.winfo_width ( ) y = root....
Remove tkinter text default binding
Python
Given some matrix , I need to mirror all the rows in the matrix . For example would become I managed to do it for the ( 2 x 2 ) -case . But I 'm having trouble mirroring something like this : This has to becomeI want to do this with loops/recursion . If I use recursion , I would probably have as basic step that the inn...
[ [ 2 , 1 ] , [ 4 , 3 ] ] [ [ 1 , 2 ] , [ 3 , 4 ] ] [ [ 1 , 2 , 3 , 4 ] , [ 1 , 2 , 3 , 4 ] ] [ [ 4 , 3 , 2 , 1 ] , [ 4 , 3 , 2 , 1 ] ] matrix = [ [ 1 , 2 , 3 , 4 ] , [ 1 , 2 , 3 , 4 ] ] def mirror ( matrix ) : # This corresponds to the basic step . The two inner most elements get swapped . if len ( matrix ) == 2 : for...
Mirroring rows in matrix with loops/recursion ?
Python
I have below two functions : I was hoping that foo will run faster then bar but I have checked in ipython with % % timeit that foo is taking slightly longer then bar The difference increases as I increase value of n hence I tried to check function with dis.dis ( foo ) and dis.dis ( bar ) but it was identical.So what wo...
def foo ( n=50000 ) : return sum ( i*i for i in range ( n ) ) # just called sum ( ) directly without def bar ( n=50000 ) : return sum ( [ i*i for i in range ( n ) ] ) # passed constructed list to sum ( ) In [ 2 ] : % % timeit ... : foo ( 50000 ) ... : 100 loops , best of 3 : 4.22 ms per loopIn [ 3 ] : % % timeit ... : ...
python function call with/without list comprehension
Python
As a workaround for MySQL truncating unicode strings when encountering `` high '' ( ordinal > = 2^16 ) code points , I 've been using a little Python method that steps through the string ( strings are sequences , remember ) , does ord ( ) on the character , and preempts the truncation , either by substituting something...
# # # `` good '' machine , Python2.7.3 $ uname -a & & echo $ LANGLinux *** 3.2.0-60-virtual # 91-Ubuntu SMP Wed Feb 19 04:13:28 UTC 2014 x86_64 x86_64 x86_64 GNU/Linuxen_US.UTF-8 $ python2.7Python 2.7.3 ( default , Feb 27 2014 , 19:58:35 ) [ GCC 4.6.3 ] on linux2Type `` help '' , `` copyright '' , `` credits '' or `` l...
Python 2.7.6 splits single `` high '' unicode code point in two
Python
I have a numpy array data of shape ( N , 20 , 20 ) with N being some very large number.I want to get the number of unique values in each of the 20x20 sub-arrays.with a loop that would be : How could I vectorize this loop ? speed is a concern.If I try np.unique ( data ) I get the unique values for the whole data array n...
values = [ ] for i in data : values.append ( len ( np.unique ( i ) ) )
vectorize numpy unique for subarrays
Python
I 'm trying to create a function that will do a least squares fit based on a passed in lambda function . I want to create an array of zeroes of length equal to that of the number of arguments taken by the lambda function for the initial guess to the lambda function . so if its linear I want [ 0,0 ] and for quadratic I ...
# polynomial functionslinear = lambda p , x : p [ 0 ] * x + p [ 1 ] quadratic = lambda p , x : p [ 0 ] * x**2 + p [ 1 ] * x + p [ 2 ] cubic = lambda p , x : p [ 0 ] * x**3 + p [ 1 ] * x**2 + p [ 2 ] * x + p [ 3 ] # polynomial functions forced through 0linear_zero = lambda p , x : p [ 0 ] * x quadratic_zero = lambda p ,...
how do I find out how many arguments a lambda function needs
Python
I 've run into some confusing behaviour of the magic comparison methods.Suppose we have the following class : The class does what it is supposed to do , comparing a MutNum object to a regular int or float is no problem . However , and this is what I do n't understand , it even compares fine when the magic methods are g...
class MutNum ( object ) : def __init__ ( self , val ) : self.val = val def setVal ( self , newval ) : self.val = newval def __str__ ( self ) : return str ( self.val ) def __repr__ ( self ) : return str ( self.val ) # methods for comparison with a regular int or float : def __eq__ ( self , other ) : return self.val == o...
Python magic method confusion
Python
Python allows unicode identifiers . I defined Xᵘ = 42 , expecting XU and Xᵤ to result in a NameError . But in reality , when I define Xᵘ , Python ( silently ? ) turns Xᵘ into Xu , which strikes me as somewhat of an unpythonic thing to do . Why is this happening ?
> > > Xᵘ = 42 > > > print ( ( Xu , Xᵘ , Xᵤ ) ) ( 42 , 42 , 42 )
Unicode subscripts and superscripts in identifiers , why does Python consider XU == Xᵘ == Xᵤ ?
Python
I would like to set or clear the invalid state flag of a ttk.Entry whenever the contents change . I 'm doing this by connecting a StringVar to the entry , and in a trace ( ) callback , calling state ( [ 'valid ' ] ) or state ( [ ' ! invalid ' ] ) . The flag is correctly set by my callback , but then , whenever the focu...
> > > import tkinter as tk > > > from tkinter import ttk > > > win = tk.Tk ( ) > > > entry = ttk.Entry ( win ) > > > entry.pack ( ) > > > entry [ 'validate ' ] 'none ' > > > entry.state ( ) ( ) > > > entry.state ( [ 'invalid ' ] ) ( ' ! invalid ' , ) > > > entry.state ( ) ( 'invalid ' , ) > > > entry.state ( ) ( )
How can I ensure my ttk.Entry 's invalid state is n't cleared when it loses focus ?
Python
I am working on a script which needs to process a rather large ( 620 000 words ) lexicon on startup . The input lexicon is processed word-by-word into a defaultdict ( list ) , with keys being letter bi and trigrams and values being lists of words that contain the key letter n-gram usingsuch asThe resulting structure co...
for word in lexicon_file : word = word.lower ( ) for letter n-gram in word : lexicon [ n-gram ] .append ( word ) > lexicon [ `` ab '' ] [ `` abracadabra '' , `` abbey '' , `` abnormal '' ] > normal lexicon creation45 seconds > cPickle deserialization80 seconds
Python defaultdict ( list ) de/serialization performance
Python
I have been experimenting with GNU Radio and came across the tunnel.py program . This program allows you to tunnel IP traffic over a wireless radio link using Linux TUN/TAP devices . For the most part it is working however one part of the code is confusing me.There is a class which implements a 'basic MAC layer ' . Thi...
class cs_mac ( object ) : def __init__ ( self , tun_fd , verbose=False ) : self.tun_fd = tun_fd # file descriptor for TUN/TAP interface self.verbose = verbose self.tb = None # top block ( access to PHY ) def set_top_block ( self , tb ) : self.tb = tb def phy_rx_callback ( self , ok , payload ) : if self.verbose : print...
Do I have a threading issue here ?
Python
I am reading the PyMOTW threading postThe first example : I run it , and get the result : The - is a space , and the format will be difference every timeBut I do n't know why there is space ? Some times it will output empty line also , why ?
import threadingdef worker ( ) : `` '' '' thread worker function '' '' '' print 'Worker ' returnthreads = [ ] for i in range ( 5 ) : t = threading.Thread ( target=worker ) threads.append ( t ) t.start ( ) Worker-WorkerWorker-WorkerWorker
Why there is space in the code example in python threading
Python
I 'm trying to guess which operator has priority : > ( greater than ) or == ( equal ) . This is my experiment : As far as I know , this has two possible solutions.Neither one returns False , so how is the first code resolved by Python ?
> > > 5 > 4 == 1False > > > ( 5 > 4 ) == 1True > > > 5 > ( 4 == 1 ) True
Priority of operators : > and ==
Python
Setting aside any strongly-held feelings about Django vs Flask , I have a whole bunch of Flask-style routes I 'd like to convert to Django . They look like your usual Flask routes : This gets even more complex with converters in Flask like path : So I have all of these routes , and I 'd rather not try to figure out reg...
'/foo/ < spam > / < int : eggs > / ' '/foo/ < path : location > '
Is there a way , in Django , to define routes using Flask-style route syntax ?
Python
Possible Duplicate : Python “ is ” operator behaves unexpectedly with integers I stumbled upon the following Python weirdity : Is every number a unique object ? Are different variables holding the same elemental values ( for example , two , ii ) the same object ? How is the id of a number generated by Python ? In the a...
> > > two = 2 > > > ii = 2 > > > id ( two ) == id ( ii ) True > > > [ id ( i ) for i in [ 42,42,42,42 ] ] [ 10084276 , 10084276 , 10084276 , 10084276 ] > > > help ( id ) Help on built-in function id in module __builtin__ : id ( ... ) id ( object ) - > integer Return the identity of an object . This is guaranteed to be ...
Python identity : Multiple personality disorder , need code shrink
Python
I have a dataframe ( edata ) as given belowFrom this dataframe I want to calculate the sum of all counts where the logical AND of both variables ( Domestic and Catsize ) results in Zero ( 0 ) such that The code I use to perform the process is This code works fine , however , if the number of variables in the dataframe ...
Domestic Catsize Type Count 1 0 1 1 1 1 1 8 1 0 2 11 0 1 3 14 1 1 4 21 0 1 4 31 1 0 00 1 00 0 0 g=edata.groupby ( 'Type ' ) q3=g.apply ( lambda x : x [ ( ( x [ 'Domestic ' ] ==0 ) & ( x [ 'Catsize ' ] ==0 ) | ( x [ 'Domestic ' ] ==0 ) & ( x [ 'Catsize ' ] ==1 ) | ( x [ 'Domestic ' ] ==1 ) & ( x [ 'Catsize ' ] ==0 ) ) ]...
Logical AND of multiple columns in pandas
Python
I am trying to print a list of python objects that contain a list as a property and i am having some unexpected results : here is my code : What I expect to get is this : topic1 VideoName1 VideoURL1 VideoName2 VideoURL2 topic2 VideoName3 VideoURL3 VideoName4 VideoURL4but what I actually get is this : topic1 VideoName1 ...
class video ( object ) : name = `` url = `` class topic ( object ) : topicName = `` listOfVideo = [ ] def addVideo ( self , videoToAdd ) : self.listOfVideo.append ( videoToAdd ) def getTopic ( self ) : return self.topicName def getListOfVideo ( self ) : return self.listOfVideotopic1 = topic ( ) topic1.topicName = 'topi...
list of objects python
Python
I have a dictionary in Python where the keys are pathnames . For example : I was wondering , what 's a good way to print all `` subpaths '' given any key.For example , given a function called `` print_dict_path '' that does this , something likeorwould print out something like : The only method I can think of is someth...
dict [ `` /A '' ] = 0dict [ `` /A/B '' ] = 1dict [ `` /A/C '' ] = 1dict [ `` /X '' ] = 10dict [ `` /X/Y '' ] = 11 print_dict_path ( `` /A '' ) print_dict_path ( `` /A/B '' ) `` B '' = 1 '' C '' = 1
Printing a particular subset of keys in a dictionary
Python
I 'm trying to a 2 columns csv file ( error.csv ) with semi-column separator which contains double quoted semi-columns : And I 'm trying : I understand that the problem comes from having a double quoted `` g '' inside my double quotes in line 3 but I ca n't figure out how to deal with it . Any ideas ?
col1 ; col22016-04-17_22:34:25.126 ; '' Linux ; Android '' 2016-04-17_22:34:25.260 ; '' { `` g '' :2 } iPhone ; iPhone '' logs = pd.read_csv ( 'error.csv ' , na_values= '' null '' , sep= ' ; ' , quotechar= ' '' ' , quoting=0 )
python pandas read_csv unable to read character double quoted twice
Python
I have an array like this : tmp.shape = ( 128 , 64 , 64 ) I am counting all zeros along the 128 axis like this : I have an array c.shape = ( 64 , 64 ) Now I want to add the values of c to tmp along the 128 axis but only if the values of tmp are > 0 : Is that possible to do in a short way ? Or do I have to use multiple ...
nonzeros = np.count_nonzero ( tmp , axis=0 ) // shape = ( 64 , 64 ) for i in range ( tmp.shape [ 0 ] ) : axis1 = tmp [ i , : , : ] tmp [ i , : , : ] += ( c / nonzeros ) // only if tmp [ i , : , : ] > 0 tmp [ i , tmp > 0.0 , tmp > 0.0 ] += ( c / nonzeros ) for i in range ( tmp.shape [ 0 ] ) : for x in range ( tmp.shape ...
Only add value if value is greater zero in Python of multidimensional array
Python
Here is my setup : Python 3.4Using the Trading APIAttempting to call eBay 's `` VerifyAddItem '' I marked where I get the Error , in PicURL , and I 'm trying to post multiple pictures with multiple URLs . I 'm currently just trying out two pictures let 's say http : //i.ebayimg.com/picture1 and http : //i.ebayimg.com/p...
`` PictureDetails '' : { `` PictureURL '' : [ `` http : //i.ebayimg.com/picture1 '' , `` http : //i.ebayimg.com/picture2 '' ] } `` PictureDetails '' : [ { `` PictureURL '' : `` http : //i.ebayimg.com/picture1 '' } , { `` PictureURL '' : `` http : //i.ebayimg.com/picture2 '' } ] VerifyAddItem : Class : RequestError , Se...
How to add multiple pictures in Python ebay sdk
Python
I have a list of 5 million string elements , which are stored as a pickle object.To remove duplicates , I use set ( a ) , then I made it a list again through list ( set ( a ) ) . My question is : Even if I restart python , and read the list from the pickle file , will the order of list ( set ( a ) ) be the same every t...
a = [ 'https : //en.wikipedia.org/wiki/Data_structure ' , 'https : //en.wikipedia.org/wiki/Data_mining ' , 'https : //en.wikipedia.org/wiki/Statistical_learning_theory ' , 'https : //en.wikipedia.org/wiki/Machine_learning ' , 'https : //en.wikipedia.org/wiki/Computer_science ' , 'https : //en.wikipedia.org/wiki/Informa...
Does python list ( set ( a ) ) change its order every time ?
Python
I 'm trying to connect to an FTP but I am unable to run any commands . The ftp.nlst throws this error : Error : [ WinError 10060 ] A connection attempt failed because the connected party did not properly respond after a period of time , or established connection failed because connected host has failed to respondI 've ...
ftp_server = ipftp_username = usernameftp_password = passwordftp = ftplib.FTP ( ftp_server ) ftp.login ( ftp_username , ftp_password ) '230 Logged on'ftp.nlst ( ) Status : Connection established , waiting for welcome message ... Status : Insecure server , it does not support FTP over TLS.Status : Logged in Status : Ret...
Can not list FTP directory using ftplib – but FTP client works
Python
I am trying to detect the square inside 4 bars . The goal is to compare their centroids . For the most part , my method ( described below ) correctly identifies the majority of cases . In images where the focus was bad or the lighting was too low , the processed image has a broken or disconnected square whose contour i...
methods = [ 'cv2.threshold ( gray , 127 , 255 , cv2.THRESH_BINARY ) [ 1 ] ' , 'cv2.threshold ( cv2.GaussianBlur ( gray , ( 5 , 5 ) , 0 ) , 0 , 255 , cv2.THRESH_BINARY + cv2.THRESH_OTSU ) [ 1 ] ' , 'cv2.adaptiveThreshold ( gray , 255 , cv2.ADAPTIVE_THRESH_MEAN_C , cv2.THRESH_BINARY , 51 , 2 ) ' , 'cv2.adaptiveThreshold ...
Detecting a broken shape using OpenCV
Python
I 'm fairly new to sckit-learn and am confused because the TfidVectorizer is sometimes returning a different vector for the same document.My corpus contains > 100 documents . I 'm running : to initialize the TfidVectorizerand to fit it to the documents in the corpus . corpus is a list of text strings.Afterwards , if I ...
vectorizer = TfidfVectorizer ( ngram_range= ( 1 , 2 ) , token_pattern=r'\b\w+\b ' , min_df=1 ) X = vectorizer.fit_transform ( corpus ) test = list ( vectorizer.transform ( [ corpus [ 0 ] ] ) .toarray ( ) [ 0 ] ) test == list ( X.toarray ( ) [ 0 ] ) [ 0.16971458376720741 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 ,...
scikit TfidfVectorizer.transform ( ) returns varying results for same document
Python
I have a dictionary of list which is like - I want to convert this to a data frame.The output should look like-
from collections import defaultdictdefaultdict ( list , { 'row1 ' : [ 'Affinity ' ] , 'row2 ' : [ 'Ahmc ' , 'Garfield ' , 'Medical Center ' ] , 'row3 ' : [ 'Alamance ' , 'Macbeth ' ] , 'row4 ' : [ ] , 'row5 ' : [ 'Mayday ' ] } ) ID SYN1 SYN2 SYN3 SYN4 SYN5row1 Affinity row2 Ahmc Garfield Medical Center row3 Alamance Ma...
Create dataframe from dictionary of list with variable length
Python
I 'm having trouble writing an algo that can read a CSV of employee/managers , and output a directed graph featuring the employee/manager relationships . My foobar example : given the following CSV fileHow can I build a DiGraph such that the following organizational structure can be shown : Obviously this is a graph pr...
john , jill , johntom , johntim , jillfelisa , tomray , tombob , timjim , timpam , felisaben , rayjames , raymike , pamrashad , benhenry , james john / \ jill tom / / \ tim felisa ray / \ / / \bob jim pam ben james / / \ mike rashad henry
Build graph of organizational structure
Python
I understand what I am asking here is probably not the best code design , but the reason for me asking is strictly academic . I am trying to understand how to make this concept work . Typically , I will return self from a class method so that the following methods can be chained together . My understanding is by return...
class Test ( object ) : def __init__ ( self ) : self.hold = None def methoda ( self ) : self.hold = 'lol ' return self , 'lol ' def newmethod ( self ) : self.hold = self.hold * 2 return self , 2t = Test ( ) t.methoda ( ) .newmethod ( ) print ( t.hold )
How can I return self and another variable in a python class method while method chaining ?
Python
We have a small web app that we want to convert into something native . Right now , it 's got a lot of moving parts ( the backend , the browser etc . ) and we 'd like to convert it into a single tight application . We decided to use PyGame to do this and it 's been fine so far except for a font rendering issue . The st...
# -*- coding : utf-8 -*-import timeimport pygame # Pygame setup and create root windowpygame.font.init ( ) screen = pygame.display.set_mode ( ( 320 , 200 ) ) empty = pygame.Surface ( ( 320 , 200 ) ) font_file = pygame.font.match_font ( `` freesans '' ) # Select andfont = pygame.font.Font ( font_file , 30 ) # open the f...
Devanagari text rendering improperly in PyGame
Python
I want to be able to run and debug unit tests for a Django project from within Visual Studio Code . I am an experienced developer , but fairly new to both Django and Visual Studio Code . The crux of the problem is that either the tests are undiscoverable within Visual Studio Code , or if they are discoverable , I get a...
import osos.environ.setdefault ( `` DJANGO_SETTINGS_MODULE '' , `` my_app_project.settings '' ) from django.core.wsgi import get_wsgi_applicationapplication = get_wsgi_application ( ) .└── mysite ├── db.sqlite3 ├── manage.py ├── mysite │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── po...
Ca n't debug Django unit tests within Visual Studio Code
Python
I am using Tensorflow 2.0 and facing the following situation : If items is a dict of Tensors like for example : Is there a way of using input_signature argument of tf.function so I can force tf2 to avoid creating multiple graphs when item1 is for example tf.zeros ( [ 2,1 ] ) ?
@ tf.functiondef my_fn ( items ) : ... . # do stuff return item1 = tf.zeros ( [ 1 , 1 ] ) item2 = tf.zeros ( 1 ) items = { `` item1 '' : item1 , `` item2 '' : item2 }
Use dictionary in tf.function input_signature in Tensorflow 2.0
Python
So I currently have a line of code which looks like this : I would like for the result to take into account any DST affects that might occur ( such as if I am at 11/4/2012 00:30 AM and add 3 hours , I would get 02:30 AM , due to a fall back for DST ) . I 've looked at using pytz and python-dateutil , and neither of the...
t1 = datetime ( self.year , self.month , self.day , self.hour , self.minute , self.second ) ... t2 = timedelta ( days=dayNum , hours=time2.hour , minutes=time2.minute , seconds=time2.second ) sumVal = t1 + t2
Python DST & Time Zone Detection After Addition
Python
I have about 500GB of text file seperated in months . In these text files the first 43 lines are just connection information ( not needed ) . the next 75 lines are descriptors for an observation . This is followed by 4 lines ( not needed ) then the next observation which is 75 lines . The thing is all I want are these ...
ID : 5523Date : 20052012Mixed : < Null > ..
Quickest way of Importing 500GB Text File taking only the sections wanted
Python
I have the following hypothetical Python program that uses some of the garbage collector functions ( documentation ) : The program prints 0 , which seems weird to me because : Upon first assignment , the str object is created and is referenced by a.Upon the second assignment , the second str object is created and a and...
import gc # Should turn automatic garbage collection offgc.disable ( ) # Create the stringa = `` Awesome string number 1 '' # Make the previously assigned string unreachable # ( as an immutable object , will be replaced , not edited ) a = `` Let 's replace it by another string '' # According to the docs , collect the g...
garbage collection does n't remove unreachable object after being turned off for a while
Python
I 've been trying to clear images for OCR : ( the lines ) I need to remove these lines to sometimes further process the image and I 'm getting pretty close but a lot of the time the threshold takes away too much from the text : Edit : Additionally , using constant numbers will not work in case the font changes.Is there...
copy = img.copy ( ) blur = cv2.GaussianBlur ( copy , ( 9,9 ) , 0 ) thresh = cv2.adaptiveThreshold ( blur,255 , cv2.ADAPTIVE_THRESH_GAUSSIAN_C , cv2.THRESH_BINARY_INV,11,30 ) kernel = cv2.getStructuringElement ( cv2.MORPH_RECT , ( 9,9 ) ) dilate = cv2.dilate ( thresh , kernel , iterations=2 ) cnts = cv2.findContours ( d...
Cleaning image for OCR
Python
I have a pandas dataframe where I have a column values like this : What I want is to create another column , modified_values , that contains a list of all the different numbers that I will get after splitting each value . The new column will be like this : Beware the values in this list should be int and not strings.Th...
0 16 01 7 1 2 02 53 14 18 0 [ 16 , 0 ] 1 [ 7 , 1 , 2 , 0 ] 2 [ 5 ] 3 [ 1 ] 4 [ 18 ]
Splitting a string into list and converting the items to int
Python
I use python3.3 and just found out that it accepts keyword arguments in some of its CPython functions : But some other functions do n't accept keyword arguments : My question is : what is the difference between those functions ? Which functions in CPython accept keyword arguments , which functions do n't ? And of cours...
> > > `` I like python ! `` .split ( maxsplit=1 ) [ ' I ' , 'like python ! ' ] > > > sum ( [ 1,2,3,4 ] , start = 10 ) Traceback ( most recent call last ) : File `` < pyshell # 58 > '' , line 1 , in < module > sum ( [ 1,2,3,4 ] , start = 10 ) TypeError : sum ( ) takes no keyword arguments
Python accepts keyword arguments in CPython functions ?
Python
I have two pandas DataFrames with identical index and column names.I can join them together and assign suffixes.But what I want is to make ' L ' and ' R ' sub-columns under both ' X ' and ' Y'.The desired DataFrame looks like this : Is there a way I can combine the two original DataFrames to get this desired DataFrame ...
> > > df_L = pd.DataFrame ( { ' X ' : [ 1 , 3 ] , ' Y ' : [ 5 , 7 ] } ) > > > df_R = pd.DataFrame ( { ' X ' : [ 2 , 4 ] , ' Y ' : [ 6 , 8 ] } ) > > > df_L.join ( df_R , lsuffix='_L ' , rsuffix='_R ' ) X_L Y_L X_R Y_R0 1 5 2 61 3 7 4 8 > > > pd.DataFrame ( columns=pd.MultiIndex.from_product ( [ [ ' X ' , ' Y ' ] , [ ' L...
Convert column suffixes from pandas join into a MultiIndex
Python
In python , it 's common to have vertically-oriented lists of string . For example : This looks good , readable , do n't violate 80-columns rule ... But if comma is missed , like this : Python will still assume this code valid by concatenating two stings : ( . Is it possible to somehow safeguard yourself from such typo...
subprocess.check_output ( [ 'application ' , '-first-flag ' , '-second-flag ' , '-some-additional-flag ' ] ) subprocess.check_output ( [ 'application ' , '-first-flag ' # missed comma here '-second-flag ' , '-some-additional-flag ' ] )
How do you protect yourself from missing comma in vertical string list in python ?
Python
I have been searching since a couple of days for a solution without success.We have a windows service build to copy some files from one location to another one.So I build the code shown below with Python 3.7.The full coding can be found on Github.When I run the service using python all is working fine , I can install t...
' '' Windows service to copy a file from one location to another at a certain interval . ' '' import sysimport timefrom distutils.dir_util import copy_treeimport servicemanagerimport win32serviceutilimport win32servicefrom HelperModules.CheckFileExistance import check_folder_exists , create_folderfrom HelperModules.Rea...
pyinstaller Error starting service : The service did not respond to the start or control request in a timely fashion
Python
I 'm writing a class RecurringInterval which - based on the dateutil.rrule object - represents a recurring interval in time . I have defined a custom , human-readable __str__ method for it and would like to also define a parse method which ( similar to the rrulestr ( ) function ) parses the string back into an object.H...
import refrom dateutil.rrule import FREQNAMESimport pytestclass RecurringInterval ( object ) : freq_fmt = `` { freq } '' start_fmt = `` from { start } '' end_fmt = `` till { end } '' byweekday_fmt = `` by weekday { byweekday } '' bymonth_fmt = `` by month { bymonth } '' @ classmethod def match_pattern ( cls , string ) ...
In Python , how to parse a string representing a set of keyword arguments such that the order does not matter
Python
This question is related to ( but perhaps not quite the same as ) : Does Django have HTML helpers ? My problem is this : In Django , I am constantly reproducing the basic formatting for low-level database objects . Here 's an example : I have two classes , Person and Address . There are multiple Addresses for each Pers...
class Person ( models.Model ) : ... class Address ( models.Model ) : contact = models.ForeignKey ( Person ) def detail ( request , person_id ) : person = get_object_or_404 ( Person , pk=person_id ) return render_to_response ( 'persons/details.html ' , { 'title ' : unicode ( person ) , 'addresses ' : person.address_set....
In Django , where is the best place to put short snippets of HTML-formatted data ?
Python
PEP 412 , implemented in Python 3.3 , introduces improved handling of attribute dictionaries , effectively reducing the memory footprint of class instances . __slots__ was designed for the same purpose , so is there any point in using __slots__ any more ? In an attempt to find out the answer myself , I run the followin...
class Slots ( object ) : __slots__ = [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' ] def __init__ ( self ) : self.a = 1 self.b = 1 self.c = 1 self.d = 1 self.e = 1 class NoSlots ( object ) : def __init__ ( self ) : self.a = 1 self.b = 1 self.c = 1 self.d = 1 self.e = 1 > > > sys.getsizeof ( [ Slots ( ) for i in range ( 1000 )...
Does PEP 412 make __slots__ redundant ?
Python
I have a pandas dataframe of values I read in from a csv file . I have a column labeled 'SleepQuality ' and the values are float from 0.0 - 100.0 . I want to create a new column labeled 'SleepQualityGroup ' where values from the original column btw 0 - 49 have a value of 0 in the new column , 50 - 59 = 1 , 60 - 69 = 2 ...
SleepQuality SleepQualityGroup80.4 490.1 566.4 250.3 186.2 475.4 345.7 091.5 561.3 2 54 158.2 1
How to create new values in a pandas dataframe column based on values from another column
Python
I have several dataframes.Dataframe # 1Dataframe # 2I want to merge this dataframe and obtain the following one : I know that I can do an outer merge but I do not know how to move from there to obtain the final dataframe I presented above . Any ideas ?
Feature Coeffa 0.5b 0.3c 0.35d 0.2 Feature Coeffa 0.7b 0.2y 0.75x 0.1 Feature | DF1 | DF2a 1 1b 1 1c 1 0d 1 0y 0 1x 0 1
Merging two data frames into a new one with unique items marked with 1 or 0
Python
I want to randomise the case of a string , heres what I have : Im wondering if you could use list comprehension to make it faster.I couldnt seem to use the lower ( ) and upper ( ) functions in randomchoicei tried to do something likebut i think thats wrong . something like that though is possible ?
word= '' This is a MixeD cAse stRing '' word_cap= '' for x in word : if random.randint ( 0,1 ) : word_cap += x.upper ( ) else : word_cap += x.lower ( ) word = word_capprint word `` .join ( randomchoice ( x.upper ( ) , x.lower ( ) ) for x in word )
Pythons fastest way of randomising case of a string
Python
Is there a way to startup python quietly , perhaps by setting some environment variable or supplying command line option ? Instead of seeing this : Sometimes I want this behaviour , straight to the prompt : I would also be interested in an answer for ipython .
wim @ SDFA100461C : /tmp $ pythonPython 2.7.5+ ( default , Sep 19 2013 , 13:48:49 ) [ GCC 4.8.1 ] on linux2Type `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > wim @ SDFA100461C : /tmp $ python > > >
Python quiet startup
Python
I have a file foo.py that makes extensive use of the Faker third-party module . As such , pylint generates a lot of 'no-member ' errors.I would like to disable these in foo.py . So at the top , I triedinserting : But , in a quite-annoying fashion , pylint now spits out a suppressed message every time it hits one of the...
# pragma pylint : disable=no-member foo.py:1:0 : I0011 : Locally disabling no-member ( E1101 ) ( locally-disabled ) ... other misc stuff ... foo.py:177:0 : I0020 : Suppressed 'no-member ' ( from line 1 ) ( suppressed-message ) foo.py:83:0 : I0020 : Suppressed 'no-member ' ( from line 1 ) ( suppressed-message ) foo.py:8...
Pylint : How do I cleanly suppress things without subsequent 'suppressed-message ' nonsense ?
Python
I have been working on a python script to analyze CSVs . Some of these files are fairly large ( 1-2 million records ) , and the script was taking hours to complete.I changed the way the records are processed from a for-in loop to a while loop , and the speedup was remarkable . Demonstration below : Almost an order of m...
> > > def for_list ( ) : ... for d in data : ... bunk = d**d ... > > > def while_list ( ) : ... while data : ... d = data.pop ( 0 ) ... bunk = d**d ... > > > data = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] > > > import timeit > > > timeit.timeit ( for_list ) 1.0698931217193604 > > > timeit.timeit ( while_list ) 0.145...
Python : Why is popping off a queue faster than for-in block ?
Python
I am running python2.7 with django 1.4.I have the following code in my views.py page which returns the language names in a select list : python code : ( views.py ) HTML code : select list : The problem is when the page is viewed in a rtl language like Arabic the select list is rendered as follows with the brackets of t...
available_languages = [ ] for lv in language_versions : language = LANGUAGES [ lv.language_code ] if lv.language_code == user_language_code : language_label = ( lv.language_code , u '' % s '' % ( language.name_native ) ) else : language_label = ( lv.language_code , u '' % s / % s '' % ( language.name , language.name_na...
python / django - bidi brackets issue in html select list
Python
I created some APIs on the Django project using Django rest framework.I set IsAdminUser to permission classes.When I run the project locally and make a request to it with auth info , it works.I deployed it to AWS server by using Elastic Beanstalk and make a request , and it returns error 403Here is my APIWhat am I miss...
Authentication credentials were not provided class HamListApiView ( ListAPIView ) : queryset = Ham.objects.all ( ) serializer_class = HamSerializer permission_classes = [ permissions.IsAdminUser ]
Authentication credentials were not provided . when deployed to AWS
Python
So far to execute a Python program , I 'm using I want to run the Python script simply using file name , likesimilar to shell scripts likeor move file.sh to bin and then run
> python file.py > file.py > sh file.sh > chmod +x file.sh > ./file.sh > file.sh
ways to execute python
Python
At a high level , what I 'm trying to accomplish is : My first thought of how to do that is : This works fine . To be more Pythonic , I figured - list comprehensions , right ? So : Unfortunately , this adds a copy of word to the result for each character that is n't a digit . So for f ( [ 'foo ' ] ) , I end up with [ '...
given a list of words , return all the words that do not consist solely of digits import stringresult = [ ] for word in words : for each_char in word : if each_char not in string.digit : result.append ( word ) breakreturn result return [ word for word in words for char in word if not char in string.digits ]
Python list-comprehension for words that do not consist solely of digits
Python
I am working on developing a python package . I use pip freeze > requirements.txt to add the required package into the requirement.txt file . However , I realized that some of the packages , instead of the package version , have some path in front of them.Whereas , inside the environment , I get : Do you have any idea ...
numpy==1.19.0packaging==20.4pandas @ file : ///opt/concourse/worker/volumes/live/38d1301c-8fa9-4d2f-662e-34dddf33b183/volume/pandas_1592841668171/workpandocfilters==1.4.2 > > > pandas.__version__ ' 1.0.5 '
pip freeze creates some weird path instead of the package version
Python
The python PEP 8 linter does n't like this : It tells me to use `` isinstance ( ) '' instead . But to use isinstance I would have to do something likewhich seems much more unwiedly , and I do n't really see the point.Is the linter being wise in some way that I ca n't see ? Or am I being wise in some way the linter ca n...
assert type ( a ) == type ( b ) assert isinstance ( a , type ( b ) ) and isinstance ( b , type ( a ) )
`` E271 : do not compare types , use isinstance ( ) '' error
Python
When I 'm maintaining and distributing a Python package , should I keep the MANIFEST file that the commandgenerates under version control , or should I add it to .gitignore ?
python setup.py sdist
Should I keep the MANIFEST file that setup.py generates under version control ?
Python
TL ; DR : The print ( ) result is not updating in a Windows Console . Executes fine in IDLE . Program is executing even though Windows Console is not updating.BackgroundI have a file , test.py that contains : Edit : Included the conditions that I used to see if the Console was updating . Eventually the series of X valu...
count = 0while True : print ( `` True '' ) count += 1 if count == 10 : print ( `` XXXXXXXXX '' ) count = 0 line [ 10 ] > > Progress 05 % line [ 10 ] > > Progress 06 % line [ 10 ] > > Progress 11 % ... line [ 10 ] > > Progress 50 % def check_queue ( q , dates , dct ) : out = 0 height = 0 # print the initial columns and ...
Does using print ( ) too much cause it to fail ?
Python
Lets say I have a python model fibo.py defined as below : In my interpreter session , I do the following : So far so good ... restart the interpreter : I expected the error as I have only imported fib and fib2 . But I do n't understand why the statement was printed when I only imported fib and fib2.Secondly if I change...
# Fibonacci numbers moduleprint `` This is a statement '' def fib ( n ) : a , b = 0,1 while b < n : print b a , b = b , a+bdef fib2 ( n ) : a , b = 0,1 result= [ ] while ( b < n ) : result.append ( b ) a , b = b , a+b return result > > import fiboThis is a statement > > > fibo.fib ( 10 ) 112358 > > > fibo.fib2 ( 10 ) [...
Python : Importing Module
Python
How do I round a Python Decimal instance to a specific number of digits while rounding to the nearest decimal ? I 've tried using the .quantize ( Decimal ( '.01 ' ) ) method outlined in the docs , and suggested in previous answers , but it does n't seem to round correctly despite trying different ROUND_ options . I 've...
assert Decimal ( ' 3.605 ' ) .round ( 2 ) == Decimal ( ' 3.61 ' ) assert Decimal ( '29342398479823.605 ' ) .round ( 2 ) == Decimal ( '29342398479823.61 ' ) assert Decimal ( ' 3.604 ' ) .round ( 2 ) == Decimal ( ' 3.60 ' ) assert Decimal ( ' 3.606 ' ) .round ( 2 ) == Decimal ( ' 3.61 ' )
How to round Python Decimal instance
Python
I want to create an standalone app which can be used globally on other Macs other than mine.I followed the tutorial from this page : https : //www.metachris.com/2015/11/create-standalone-mac-os-x-applications-with-python-and-py2app/ However after the Building for Deployment step is finished and i want to run the app in...
`` *MYAPP* has encountered a fatal error , and will not terminate.A Python runtime not could be located . You may need to install a framework build of Python , or edit the PyRuntimeLocations array in this application 's Info.plist file '' `` '' '' This is a setup.py script generated by py2appletUsage : python setup.py ...
Creating a standalone macOS application with Python and py2app
Python
My problem is about parsing log files and removing variable parts on each line in order to group them . For instance : I have about 120+ matching rules like the above.I have found no performance issues while searching successively on 100 different regexes . But a huge slow down occurs when applying 101 regexes.The exac...
s = re.sub ( r ' ( ? i ) User [ _0-9A-z ] + is ' , r '' User .. is `` , s ) s = re.sub ( r ' ( ? i ) Message rejected because : ( .* ? ) \ ( .+\ ) ' , r'Message rejected because : \1 ( ... ) ' , s ) for a in range ( 100 ) : s = re.sub ( r ' ( ? i ) caught here'+str ( a ) + ' : .+ ' , r ' ( ... ) ' , s ) # range ( 100 )...
Python re module becomes 20 times slower when looping on more than 100 different regex
Python
I have Django app in Production working together with Celery and Amazon SQS . Every day in my celery logs I can see that there was SSL error : which follows by next error while trying to reconnect to broker : Sometimes queues are crashing after this message and I have to restart my Celery workers . In general I am not ...
[ ERROR/MainProcess ] Empty body : SQSError : 599 gnutls_handshake ( ) failed : An unexpected TLS packet was received . [ 2016-12-14 16:06:28,917 : WARNING/MainProcess ] consumer : Connection to broker lost . Trying to re-establish the connection ... Traceback ( most recent call last ) : File `` /home/ubuntu/virtualenv...
Django +Celery +SQS - > boto.exception.SQSError : SQSError : 599 gnutls_handshake ( )
Python
I have two python dictionaries that I 'm trying to sum the values together on . The answer in : Is there any pythonic way to combine two dicts ( adding values for keys that appear in both ) ? gets me most of the way . However I have cases where the net values may be zero or negative but I still want the values in the f...
from collections import Counter A = Counter ( { ' a ' : 1 , ' b ' : 2 , ' c ' : -3 , ' e ' : 5 , ' f ' : 5 } ) B = Counter ( { ' b ' : 3 , ' c ' : 4 , 'd ' : 5 , ' e ' : -5 , ' f ' : -6 } ) C = A + Bprint ( C.items ( ) )
combining two python dictionaries into one when the net values are not positive
Python
Whilst researching performance trade-offs between Python and C++ , I 've devised a small example , which mostly focusses on a dumb substring matching.Here is the relevant C++ : The above is built with -O3.And here is Python : Both of them take a large-ish set of patterns and input file , and filter down the list of pat...
using std : :string ; std : :vector < string > matches ; std : :copy_if ( patterns.cbegin ( ) , patterns.cend ( ) , back_inserter ( matches ) , [ & fileContents ] ( const string & pattern ) { return fileContents.find ( pattern ) ! = string : :npos ; } ) ; def getMatchingPatterns ( patterns , text ) : return filter ( te...
String matching performance : gcc versus CPython
Python
So , I 'm trying to match an exception with a doctest.The issue is that this works with py2.7 but not with python 3 . The format of exception trace has been changed so now it include the full module name . I.e . in python 3 I have package.module.AuthError instead.Is there a way to match both ? Seems like IGNORE_EXCEPTI...
> > > api = Api ( `` foo '' , `` bar '' ) # doctest : +IGNORE_EXCEPTION_DETAILTraceback ( most recent call last ) : ... AuthError
Python doctest exceptions
Python
For approaches to retrieving partial matches in a numeric list , go to : How to return a subset of a list that matches a condition ? Python : Find in listBut if you 're looking for how to retrieve partial matches for a list of strings , you 'll find the best approaches concisely explained in the answer below.SO : Pytho...
l = [ 'ones ' , 'twos ' , 'threes ' ] wanted = 'three ' any ( s.startswith ( wanted ) for s in l )
How to retrieve partial matches from a list of strings ?
Python
I have a string Please not that the keys to the dictionary entries are unquoted , so a simple eval ( `` { a : ' b ' , c : 'd ' , e : '' } '' ) as suggested in a previous question does not work.What would be the most convenient way to convert this string to a dictionary ?
`` { a : ' b ' , c : 'd ' , e : '' } '' { ' a ' : ' b ' , ' c ' : 'd ' , ' e ' : '' }
How to turn a string with unquoted keys into a dict in Python
Python
I want to split strings only by suffixes . For example , I would like to be able to split dord word to [ dor , wor ] .I though that \wd would search for words that end with d. However this does not produce the expected resultsHow can I split by suffixes ?
import rere.split ( r'\wd ' , '' dord word '' ) [ 'do ' , ' wo ' , `` ]
Split by suffix with Python regular expression
Python
There have been a few questions on how to implement enums in Python . Most solutions end up being more or less equivalent to something like this : Others have suggest more complicated ways of constructing enums , but ultimatly the tend to look like this example when all is said and done.Based on my experience in Java a...
class Animal : DOG=1 CAT=2
Pythonic design without enums
Python
I need to do a numerical integration in 6D in python . Because the scipy.integrate.nquad function is slow I am currently trying to speed things up by defining the integrand as a scipy.LowLevelCallable with Numba.I was able to do this in 1D with the scipy.integrate.quad by replicating the example given here:10000 loops ...
import numpy as npfrom numba import cfuncfrom scipy import integratedef integrand ( t ) : return np.exp ( -t ) / t**2nb_integrand = cfunc ( `` float64 ( float64 ) '' ) ( integrand ) # regular integration % timeit integrate.quad ( integrand , 1 , np.inf ) # integration with compiled function % timeit integrate.quad ( nb...
How can you implement a C callable from Numba for efficient integration with nquad ?
Python
I have the following data frame : and I want to convert it to Note that the number of columns equals the number of unique values , and the number and order of rows are preserved
a1 | a2 | a3 | a4 -- -- -- -- -- -- -- -- -- -- - Bob | Cat | Dov | Edd Cat | Dov | Bob | EddEdd | Cat | Dov | Bob Bob | Cat | Dov | Edd -- -- -- -- -- -- -- -- -- -- -a1 | a2 | a3 | a4a3 | a1 | a2 | a4a4 | a2 | a3 | a1
How to swap a group of column headings with their values in Pandas
Python
=============
`` `` '' module a.py '' '' '' test = `` I am test '' _test = `` I am _test '' __test = `` I am __test '' ~ $ pythonPython 2.6.2 ( r262:71600 , Apr 16 2009 , 09:17:39 ) [ GCC 4.0.1 ( Apple Computer , Inc. build 5250 ) ] on darwinType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > >...
Why there is a difference in `` import '' vs. `` import * '' ?
Python
It is clear when doingWe get something multiindex by level ' A ' and ' B ' and one column with the mean of each grouphow could I have the count ( ) , std ( ) simultaneously ? so result looks like in a dataframe
data.groupby ( [ ' A ' , ' B ' ] ) .mean ( ) A B mean count std
How to apply different aggregation functions to same column by using pandas Groupby
Python
TLDR : numpy.cos ( ) works 30 % longer on a particular numbers ( exactly 24000.0 for example ) . Adding a small delta ( +0.01 ) causes numpy.cos ( ) to work as usual.I have no idea why.I stumbled across a strange problem during my work with numpy . I was checking cache work and accidentally made a wrong graph - how num...
import numpy as npimport timeitst = 'import numpy as np'cmp = [ ] cmp_list = [ ] left = 0right = 50000step = 1000 # Loop for additional average smoothingfor _ in range ( 10 ) : cmp_list = [ ] # Calculate np.cos depending on its argument for i in range ( left , right , step ) : s= ( timeit.timeit ( 'np.cos ( { } ) '.for...
numpy.cos works significantly longer on certain numbers
Python
I ’ m a Python newbie and have the following pandas dataframe - I ’ m trying to write code that populates the ‘ signal ’ column as it is below : My pseudo-code version would take the following stepsLook down the [ ‘ long_entry_flag ’ ] column until entry condition is True ( day 3 initially ) Then we enter ‘ 1 ’ into [ ...
Days long_entry_flag long_exit_flag signal 1 FALSE TRUE 2 FALSE FALSE 3 TRUE FALSE 1 4 TRUE FALSE 1 5 FALSE FALSE 1 6 TRUE FALSE 1 7 TRUE FALSE 1 8 FALSE TRUE 9 FALSE TRUE 10 TRUE FALSE 1 11 TRUE FALSE 1 12 TRUE FALSE 1 13 FALSE FALSE 1 14 FALSE TRUE 15 FALSE FALSE 16 FALSE TRUE 17 TRUE FALSE 1 18 TRUE FALSE 1 19 FALSE...
Use columns 1 and 2 to populate column 3
Python
I 'm packaging my first Django app and I want to leave out my settings_local.py file from the egg . Ideally I 'm looking for a way to just have everything in my .gitignore file also excluded from the egg.I 've tried the following variations in my MANIFEST.in file ( one per egg creation attempt ) : I also tried adding t...
prune project_name settings_local.pyprune project_name/settings_local.pyexclude project_name settings_local.pyexclude project_name/settings_local.py exclude_package_data= { `` : 'settings_local.py ' } ,
How can I exclude files in my .gitignore when packaging a Python egg ?
Python
I 'm having a strange problem with the Pandas .isin ( ) method . I 'm doing a project in which I need to identify bad passwords by length , common word/password lists , etc ( do n't worry , this is from a public source ) . One of the ways is to see if someone is using part of their name as a password . I 'm using .isin...
# Extracting first and last names into their own columnsusers [ 'first_name ' ] = users.user_name.str.extract ( ' ( ^.+ ) ( \ . ) ' , expand = False ) [ 0 ] users [ 'last_name ' ] = users.user_name.str.extract ( '\ . ( .+ ) ' , expand = False ) # Flagging the users with passwords that matches their namesusers [ 'uses_n...
Odd issue with .isin ( ) and strings ( Python/Pandas )
Python
As the title says : So far this is where I 'm at my code does work however I am having trouble displaying the information in order . Currently it just displays the information randomly.Any help would be greatly appreciated .
def frequencies ( filename ) : infile=open ( filename , ' r ' ) wordcount= { } content = infile.read ( ) infile.close ( ) counter = { } invalid = `` ‘ ' ` , . ? ! : ; -_\n— ' ' '' for word in content : word = content.lower ( ) for letter in word : if letter not in invalid : if letter not in counter : counter [ letter ]...
I 'm trying to count all letters in a txt file then display in descending order
Python
I 'm puzzled by how circular imports are handled in Python . I 've tried to distill a minimal question and I do n't think this exact variant was asked before . Basically , I 'm seeing a difference betweenandwhen I have a circular dependency between lib.foo and lib.bar . I had expected that both would work the same : th...
import lib.foo import lib.foo as f from project.package import moduleAfrom project.package import moduleB # ! /bin/shrm -r lib ; mkdir libtouch lib/__init__.pycat > lib/foo.py < < EOF # lib.foo moduleprint ' { foo ' # import lib.bar # worksimport lib.bar as b # also works # from lib import bar # also worksprint 'foo } ...
Difference between `` import lib.foo '' and `` import lib.foo as f '' in Python
Python
I need to define a dictionary of python lambda functions through a for cycle . Each lambda function needs the value of the relative dictionary key to work , but my hope is to avoid to pass such key as an argument . Here is a dummy version of my problem . Given I expect dic1 and dic2 to do the same thing , however only ...
a = { 'bar ' : 0 , 'foo ' : 1 } # a reference dictionary dic1 = { 'bar ' : lambda x : x [ 'bar ' ] , 'foo ' : lambda x : x [ 'foo ' ] } dic2 = { key : lambda x : x [ key ] for key in a } print ( dic1 [ 'bar ' ] ( a ) , dic1 [ 'foo ' ] ( a ) ) print ( dic2 [ 'bar ' ] ( a ) , dic2 [ 'foo ' ] ( a ) ) 0 11 1 0 10 1
Defining a python dictionary of lambdas through a for cycle
Python
I would like to use a variable number of arguments in a task for pyinvoke.Like so : The above is only one of many variations I tried out but it seems pyinvoke ca n't handle a variable number of arguments . Is this true ? The above code results inSimilar , if I define pdf_combine ( out_file , in_file ) , without the ast...
from invoke import task @ task ( help= { 'out_file : ' : 'Name of the output file . ' , 'in_files ' : 'List of the input files . ' } ) def pdf_combine ( out_file , *in_files ) : print ( `` out = % s '' % out_file ) print ( `` in = % s '' % list ( in_files ) ) $ invoke pdf_combine -o binder.pdf -i test.pdf test1.pdfNo i...
How to use a variable number of arguments in pyinvoke
Python
Let 's say I have timeseries data ( time on the x-axis , coordinates on the y-z plane.Given a seed set of infected users , I want to fetch all users that are within distance d from the points in the seed set within t time . This is basically just contact tracing.What is a smart way of accomplishing this ? The naive app...
points_at_end_of_iteration = [ ] for p in seed_set : other_ps = find_points_t_time_away ( t ) points_at_end_of_iteration += find_points_d_distance_away_from_set ( other_ps ) for user , time , pos in infected_set : info = get_next_info ( user , time ) # info will be a tuple : ( t , pos ) intersecting_users = find_inters...
Contact Tracing in Python - working with timeseries
Python
I want to know how Python knows ( if it knows ) that a value-type object is already stored in its memory ( and also knows where it is ) .For this code , when assigning the value 1 for b , how does it know that the value 1 is already in its memory and stores its reference in b ?
> > > a = 1 > > > b = 1 > > > a is bTrue
How does Python know the values already stored in its memory ?
Python
I 've written a program that fetches the desired information from a blog or any page . The next thing , I want to achieve is to retrieve the first image from that page , that belongs to the respective post ( Just like Facebook does when a post is shared ) .I was able to achieve this to some extent by fetching the first...
d = feedparser.parse ( 'http : //rss.cnn.com/rss/edition.rss ' ) for entry in d.entries : try : if entry.title is not None : print entry.title print `` '' except Exception , e : print e try : if entry.link is not None : print entry.link print `` '' except Exception , e : print e try : if entry.published [ 5:16 ] is not...
Fetching the first image from a website that belongs to the post
Python
SQLAlchemy doc explain how to create a partitioned table . But it does not explains how to create partitions.So if I have this : I know that most of the I 'll be doing SELECT * FROM measures WHERE logdate between XX and YY . But that seems interesting .
# Skipping create_engine and metadataBase = declarative_base ( ) class Measure ( Base ) : __tablename__ = 'measures ' __table_args__ = { postgresql_partition_by : 'RANGE ( log_date ) ' } city_id = Column ( Integer , not_null=True ) log_date = Columne ( Date , not_null=True ) peaktemp = Column ( Integer ) unitsales = Co...
Postgresql partition and sqlalchemy
Python
In the first case , I use a very simple DataFrame to try using pandas.cut ( ) to count the number of unique values in one column within a range of another column . The code runs as expected : However , in the following code , pandas.cut ( ) counts the number of unique values wrong . I expect the first bin ( 1462320000 ...
df = pd.DataFrame ( { 'No ' : [ 1,1.5,2,1,3,5,10 ] , 'useragent ' : [ ' a ' , ' c ' , ' b ' , ' c ' , ' b ' , ' a ' , ' z ' ] } ) print type ( df ) print dfdf.groupby ( pd.cut ( df [ 'No ' ] , bins=np.arange ( 0,4,1 ) ) ) .useragent.nunique ( ) print type ( df ) print len ( df ) print df.time.nunique ( ) print df.hash....
Why does pandas.cut ( ) behave differently in unique count in two similar cases ?
Python
Hello i have a problem which i am not able to implement a solution on.I have following two DataFrames : What i want is following DataFrame : I already tried following : This does not work . Can you help me and suggest a more comfortable implementation ? Manyy thanks in advance !
> > > df1A B date1 1 01-20162 1 02-20171 2 03-20172 2 04-2020 > > > df2A B 01-2016 02-2017 03-2017 04.20201 1 0.10 0.22 0.55 0.772 1 0.20 0.12 0.99 0.1251 2 0.13 0.15 0.15 0.2452 2 0.33 0.1 0.888 0.64 > > > df3A B date value1 1 01-2016 0.102 1 02-2017 0.121 2 03-2017 0.152 2 04-2020 0.64 summarize_dates = self.summariz...
Merge two DataFrames based on columns and values of a specific column with Pandas in Python 3.x
Python
When I execute simple command like `` net start '' , I am getting output successfully as shown below.Python script : Output : But When I execute long commands ( for example : `` net start `` windows search '' ) I am NOT getting any output.Python script : Output : I have tried `` net start \ '' windows search\ '' `` . a...
import osdef test ( ) : cmd = ' net start ' output = os.popen ( cmd ) .read ( ) print outputtest ( ) C : \Users\test\Desktop\service > python test.pyThese Windows services are started : Application Experience Application Management Background Intelligent Transfer Service Base Filtering Engine Task Scheduler TCP/IP NetB...
How to execute commands with double quotes ( net start `` windows search '' ) using python 'os ' module ?
Python
I 'm working on an application that uses LevelDB and that uses multiple long-lived processes for different tasks.Since LevelDB does only allow a single process maintaining a database connection , all our database access is funneled through a special database process.To access the database from another process we use a ...
loop = asyncio.get_event_loop ( ) return await loop.run_in_executor ( thread_pool_executor , self._callmethod , method_name , args , )
How to efficiently use asyncio when calling a method on a BaseProxy ?
Python
Short version : I have a similar setup to StackOverflow . Users get Achievements . I have many more achievements than SO , lets say on the order of 10k , and each user has in the 100s of achievements . Now , how would you recommend ( to recommend ) the next achievement for a user to try for ? Long version : The objects...
class User ( models.Model ) : alias = models.ForeignKey ( Alias ) class Alias ( models.Model ) : achievements = models.ManyToManyField ( 'Achievement ' , through='Achiever ' ) class Achievement ( models.Model ) : points = models.IntegerField ( ) class Achiever ( models.Model ) : achievement = models.ForeignKey ( Achiev...
How to recommend the next achievement
Python
EDIT : stupid logic of mine got ahead of me . The none are just the returns from the comprehension call.Ok , I 'm running some tests in python , and I ran into a bit of a difference in execution orders , which leads me to an understanding of how it is implemented , but I 'd like to run it by you fine people to see if I...
> > > a = [ `` a '' , '' b '' , '' c '' , '' d '' , '' e '' ] > > > def test ( self , arg ) : ... print `` testing % s '' % ( arg ) ... a.pop ( ) ... > > > [ test ( elem ) for elem in a ] testing atesting btesting c [ None , None , None ] > > > a [ ' a ' , ' b ' ] # now we try another syntax > > > a = [ `` a '' , '' b ...
python list comprehension VS for behaviour