lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
I initially had some code that aggregated results into a list . When I refactored this code to use a list comphrehension , I am getting unexpected results : If I run this code I get this output : Why do I get different results for third huh ( ) function ?
import asyncio @ asyncio.coroutinedef coro ( ) : return `` foo '' # Writing the code without a list comp works , # even with an asyncio.sleep ( 0.1 ) . @ asyncio.coroutinedef good ( ) : yield from asyncio.sleep ( 0.1 ) result = [ ] for i in range ( 3 ) : current = yield from coro ( ) result.append ( current ) return re...
Why am I getting different results when using a list comprehension with coroutines with asyncio ?
Python
I am working on this python notebook in Google Collab : https : //github.com/AllenDowney/ModSimPy/blob/master/notebooks/chap01.ipynbI had to change the configuration line because the one stated in the original was erroring out : However , I think the original statement was meant to show values of assignments ( if I 'm ...
# Configure Jupyter to display the assigned value after an assignment # Line commented below because errors out # % config InteractiveShell.ast_node_interactivity='last_expr_or_assign ' # Edit solution given below % config InteractiveShell.ast_node_interactivity='last_expr ' meter = UNITS.metersecond = UNITS.seconda = ...
Google Collab How to show value of assignments ?
Python
Here 's a small example : ( In both cases the file has -*- coding : utf-8 -*- ) In Python 2 : Whereas , in Python 3 : The above behaviour is 100 % perfect , but switching to Python 3 is currently not an option . What 's the best way to replicate 3 's results in 2 , that works in both narrow and wide Python builds ? The...
reg = ur '' ( ( ? P < initial > [ +\- ] ) ( ? P < rest > .+ ? ) ) $ '' re.match ( reg , u '' hello '' ) .groupdict ( ) # = > { u'initial ' : u'\ud83d ' , u'rest ' : u'\udc4dhello ' } # unicode why must you do this re.match ( reg , `` hello '' ) .groupdict ( ) # = > { 'initial ' : `` , 'rest ' : 'hello ' }
Treat an emoji as one character in a regex
Python
I just came across something that was quite strange . Why does it raise TypeError and yet change the list inside the tuple ?
> > > t = ( [ ] , ) > > > t [ 0 ] .append ( 'hello ' ) > > > t ( [ 'hello ' ] , ) > > > t [ 0 ] += [ 'world ' ] Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : 'tuple ' object does not support item assignment > > > t ( [ 'hello ' , 'world ' ] , )
Why does += of a list within a Python tuple raise TypeError but modify the list anyway ?
Python
I want to obtain the true value of the operating system 's argv [ 0 ] in a Python program . Python 's sys.argv [ 0 ] is not this value : it is the name of the Python script being executed ( with some exceptions ) . What I want is a foo.py that will print `` somestring '' when executed asThe trivial programwill print ``...
exec -a `` somestring '' python foo.py # ! /usr/bin/env pythonimport sysprint sys.argv [ 0 ]
How can you obtain the OS 's argv [ 0 ] ( not sys.argv [ 0 ] ) in Python ?
Python
I want to scatter plot the first two columns of the following pandas.DataFrame , with the third column as color values . If I try : I get And the X-axis disappears.I tried ax.set_axis_on ( ) and ax.axis ( 'on ' ) to no avail .
> > > df = pd.DataFrame ( { ' a ' : { '1128 ' : -2 , '1129 ' : 0 , '1146 ' : -4 , '1142 ' : -3 , '1154 ' : -2 , '1130 ' : -1 , '1125 ' : -1 , '1126 ' : -2 , '1127 ' : -5 , '1135 ' : -2 } , ' c ' : { '1128 ' : 5300 , '1129 ' : 6500 , '1146 ' : 8900 , '1142 ' : 8900 , '1154 ' : 9000 , '1130 ' : 5600 , '1125 ' : 9400 , '1...
Scatter plot with colormap makes X-axis disappear
Python
I try to understand how the logging module really works . The following code does n't react like I expected.It just print out this to the console.But why ? Should n't there be info and debug , too ? Why not ? The question is not how to fix this . I know about handlers and things like that . I just try to understand how...
# ! /usr/bin/env python3import loggingl = logging.getLogger ( ) l.setLevel ( logging.DEBUG ) print ( 'enabled for DEBUG : { } '.format ( l.isEnabledFor ( logging.DEBUG ) ) ) l.debug ( 'debug ' ) l.info ( 'info ' ) l.warning ( 'warning ' ) l.error ( 'error ' ) l.critical ( 'critical ' ) warningerrorcritical
Why does logging.setLevel ( ) has no effect here with Python ?
Python
On most types/classes in Python , I can call .mro ( ) without arguments . But not on type and its descendants : It appears I can get what I want with type ( type ( 4 ) ) .mro ( type ( 4 ) ) , but why ca n't I call mro ( ) directly as I do elsewhere ?
In [ 32 ] : type ( 4 ) .mro ( ) Out [ 32 ] : [ int , object ] In [ 33 ] : type ( type ( 4 ) ) .mro ( ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -TypeError Traceback ( most recent call last ) < ipython-input-33-48a6f7fcd2fe > in < module > ( ) -- -- >...
Why does .mro ( ) on a metaclass have a different signature ? ` descriptor 'mro ' of 'type ' object needs an argument `
Python
I am looking for a simple way to visualize some of my data in numpy , and I discovered the mlabwrap package which looks really promising . I am trying to create a simple plot with the ability to be updated as the data changes . Here is the matlab code that I am trying to duplicateto pythonHowever , the second to last c...
> > h = plot ( [ 1,2,3 ] , [ 1,2,3 ] , '-o ' ) ; > > set ( h , 'XData ' , [ 0,0,0 ] ) ; > > drawnow ( ) ; > > from mlabwrap import mlab > > h = mlab.plot ( [ 1,2,3 ] , [ 1,2,3 ] , '-o ' ) > > mlab.set ( h , 'XData ' , [ 0,0,0 ] ) > > mlab.drawnow ( ) ; error : One or more output arguments not assigned during call to ``...
numpy to matlab interface with mlabwrap
Python
I count the occurrences of items in a list usingWhich gives me this : I want to separate the parts of the list items ( 3 and 1575 for example ) and store them in a list of lists . How do I do this ?
timesCrime = Counter ( districts ) Counter ( { 3 : 1575 , 2 : 1462 , 6 : 1359 , 4 : 1161 , 5 : 1159 , 1 : 868 } )
Split the result of 'counter '
Python
I have several files across several folders like this : How can I extract all the documents into a single folder appending the folder name for each moved document : I tried to extract them with : UPDATEAlso , I tried to : The above gave me the path of each file . However , I do not understand how to rename and move the...
dir├── 0│ ├── 103425.xml│ ├── 105340.xml│ ├── 109454.xml││── 1247│ └── doc.xml├── 14568│ └── doc.xml├── 1659│ └── doc.xml├── 10450│ └── doc.xml├── 10351│ └── doc.xml new_dir├── 0_103425.xml├── 0_105340.xml├── 0_109454.xml├── 1247_doc.xml├── 14568_doc.xml├── 1659_doc.xml├── 10450_doc.xml├── 10351_doc.xml import osfor pa...
How to move and rename documents placed in several nested folders into a new single folder with python ?
Python
Is there a way to connect to an RFC2217 networked serial port with Twisted Python ? Pyserial seems to support it via the serial.serial_for_url ( `` rfc2217 : // ... '' ) function . And they indicate that twisted uses pyserial for managing serial connections , however twisted.internet.serialport.SerialPort seems to expe...
socat PTY , link=/dev/myport TCP:192.168.1.222:9001 try : s = serial.serial_for_url ( ... ) except AttributeError : s = serial.Serial ( ... )
Use RFC2217 network serial ports with Twisted Python ?
Python
I have WSGI middleware that needs to capture the HTTP status ( e.g . 200 OK ) that inner layers of middleware return by calling start_response . Currently I 'm doing the following , but abusing a list does n't seem to be the “ right ” solution to me : The reason for the list abuse is that I can not assign a new value t...
class TransactionalMiddlewareInterface ( object ) : def __init__ ( self , application , **config ) : self.application = application self.config = config def __call__ ( self , environ , start_response ) : status = [ ] def local_start ( stat_str , headers= [ ] ) : status.append ( int ( stat_str.split ( ' ' ) [ 0 ] ) ) re...
What is the appropriate way to intercept WSGI start_response ?
Python
So , I recently got into programming in python and decided to make a simple code which ran some simple maths e.g calculating the missing angle in a triangle and other simple things like that . After I made the program and a few others , I thought that maybe other people I know could use this so I decided to try and mak...
a = int ( input ( `` What 's one of the angles ? `` ) ) b = int ( input ( `` What 's the other angle in the triangle ? `` ) ) c = ( a + b ) d = 180f = int ( 180 - c ) print ( f )
A simple looping command In Python
Python
For educational purposes , I 'm trying to scrape this page gradually with Python and lxml , starting with movie names.From what I 've read so far from the Python docs on lxml and the W3Schools on XPath , this code should yield me all movie titles in a list : Basically , it should give me every h3 element anywhere in th...
from lxml import htmlimport requestspage = requests.get ( 'http : //www.rottentomatoes.com/browse/dvd-top-rentals/ ' ) tree = html.fromstring ( page.text ) movies = tree.xpath ( '//h3 [ @ class= '' movieTitle '' ] /text ( ) ' ) print movies movies = tree.xpath ( '//h3 [ @ class ] /text ( ) ' ) print movies [ 'From RT U...
How to scrape this webpage with Python and lxml ? empty list returned
Python
As a `` sanity check '' I tried two ways to use transfer learning that I expected to behave the same , if not in running time than at least in the results.The first method was use of bottleneck features ( as explained here https : //blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html...
Epoch 1/5016/16 [ ============================== ] - 0s - loss : 1.3095 - acc : 0.4375 - val_loss : 0.4533 - val_acc : 0.7500Epoch 2/5016/16 [ ============================== ] - 0s - loss : 0.3555 - acc : 0.8125 - val_loss : 0.2305 - val_acc : 1.0000Epoch 3/5016/16 [ ============================== ] - 0s - loss : 0.136...
Training a dense layer from bottleneck features vs. freezing all layers but the last - should be the same , but they behave differently
Python
I want to detect features inside an image ( retina scan ) . The image consists of a retina scan inside a rectangular box with black background . I am working with Python 3.6 , and I am using Canny Edge Detection to detect features inside the image . I understand that the algorithm for canny edge detection uses edge gra...
import cv2import matplotlib.pyplot as pltfrom matplotlib.pyplot import imread as imreadplt.figure ( 1 ) img_DR = cv2.imread ( 'img.tif',0 ) edges_DR = cv2.Canny ( img_DR,20,40 ) plt.subplot ( 121 ) , plt.imshow ( img_DR ) plt.title ( 'Original Image ' ) , plt.xticks ( [ ] ) , plt.yticks ( [ ] ) plt.subplot ( 122 ) , pl...
Obtain features inside image and remove boundary
Python
As you know I can do df [ df.column.isin ( set ) ] to get the part of the DataFrame where the column value is in that set . But now my source set is dependent on the value of column1 . How do I make the function lookup a dictionary for the source set on the go , as it filters the dataframe ? let 's say i have and my df...
dict1= { ' a ' : [ 1,2,3 ] , ' b ' : [ 1,2 ] , ' c ' : [ 4,5,6 ] } column1 column2a 4b 2c 6 column1 column2b 2c 6
How to use series.isin with different sets for different values ?
Python
I 'm looking for a way to element-wise multiply two 2d arrays of shape ( a , b ) and ( b , c ) , respectively . Over the ' b ' axis , which the two arrays have in common.For instance , an example of what I 'd like to broadcast ( vectorize ) is : Does anyone know what to do here ? Is there a better way ?
import numpy as np # some dummy dataA = np.empty ( ( 2 , 3 ) ) B = np.empty ( ( 3 , 4 ) ) # naive implementationC = np.vstack ( np.kron ( A [ : , i ] , B [ i , : ] ) for i in [ 0 , 1 , 2 ] ) # this should give ( 3 , 2 , 4 ) C.shape
numpy : broadcast multiplication over one common axis of two 2d arrays
Python
I 'm expecting to get set ( [ nan,0,1 ] ) but I get set ( [ nan , 0.0 , nan , 1.0 ] ) :
> > > import numpy as np > > > import pandas as pd > > > l= [ np.nan,0,1 , np.nan ] > > > set ( pd.Series ( l ) ) set ( [ nan , 0.0 , nan , 1.0 ] ) > > > set ( pd.Series ( l ) .tolist ( ) ) set ( [ nan , 0.0 , nan , 1.0 ] ) > > > set ( l ) set ( [ nan , 0 , 1 ] )
Reducing pandas series with multiple nan values to a set gives multiple nan values
Python
I 'm working on a deep learning project in which we use RNN . I want to encode the data before it 's fed to the network . Input is Arabic verses , which have diacritics that are treated as separate characters in Python . I should encode/represent the character with the character following it with a number if the charac...
map ( lambda ch , next_ch : encode ( ch + next_ch ) if is_diacritic ( next_ch ) else encode ( ch ) , verse ) XXA ) L_I ! I % M < LLL > MMQ*Q [ ' X ' , ' X ' , ' A ) ' , 'L_ ' , ' I ! ' , ' I % ' , 'M < ' , ' L ' , ' L ' , ' L > ' , 'M ' , 'M ' , ' Q* ' , ' Q ' ] X+Y_XX+YYYY_ [ ' X ' , ' X+ ' , 'X_ ' , ' Y ' , ' Y+ ' , ...
Encoding Arabic letters with their diacritics ( if exists )
Python
I have recently been working on creating a prime-number finding program . However , I came to notice that one function was much slower when it used arguments than when it used pre-set values.Across 3 different versions , it becomes clear that the variables are significantly slowing down the program , and I would like t...
def version1 ( n , p ) : return ( ( n*n - 2 ) & ( ( 1 < < p ) - 1 ) ) + ( ( n*n - 2 ) > > p ) timeit.timeit ( `` version1 ( 200 , 500000000 ) '' , `` from __main__ import version1 '' , number=100 ) def version2 ( ) : return ( ( 200*200 - 2 ) & ( ( 1 < < 500000000 ) - 1 ) ) + ( ( 200*200 - 2 ) > > 500000000 ) timeit.tim...
Why does using arguments make this function so much slower ?
Python
I am working with a DataFrame which looks like thisand I am trying to compute the following output.In my current approach I 'm trying to iterate through the columns , then replace values with the contents of a third column.For example , if List [ 0 ] [ 1 ] is equal to Numb [ 1 ] [ 1 ] replace column List [ 0 ] [ 1 ] wi...
List Numb Name1 1 one1 2 two2 3 three4 4 four3 5 five List Numb Nameone 1 oneone 2 twotwo 3 threefour 4 fourthree 5 five
pandas map one column to the combination of two columns
Python
It seems vims python sripting is designed to edit buffer and files rather than work nicely with vims registers . You can use some of the vim packages commands to get access to the registers but its not pretty.My solution for creating a vim function using python that uses a registeris something like this.Setting registe...
function printUnnamedRegister ( ) python < < EOFprint vim.eval ( ' @ @ ' ) EOFendfunction function setUnnamedRegsiter ( ) python < < EOFs = `` Some \ '' crazy\ '' string\nwith interesting characters '' vim.command ( 'let @ @ = '' % s '' ' % myescapefn ( s ) ) EOFendfunction function printUnnamedRegister ( ) python < < ...
Can you access registers from python functions in vim
Python
I create an virtual environment in my conda named 'keras_ev ' and install the keras in it by after that when i the notebook does not show my keras_ev environment and i fail to import the keras in my notebook.Does anybody know how to fix this ! Thank you
conda install keras activate keras_evjupyter notebook
Keras installation
Python
If I install one package Eg : pip install bpython on newly created virtualenv what I receive when I executeOutput : Question : Should we need to put all these in requirement.txt file or just bpython==0.17Once i was asked to clean up requirement.txt file , so i did updated the code from TOAnd I am still not sure whether...
pip freeze blessings==1.6.1bpython==0.17certifi==2018.1.18chardet==3.0.4curtsies==0.2.11greenlet==0.4.12idna==2.6Pygments==2.2.0requests==2.18.4six==1.11.0urllib3==1.22wcwidth==0.1.7 pip freeze > requirement.txt comm -12 < ( pip list -- format=freeze -- not-required ) < ( pip freeze ) > requirements.txt
Should we put all required and their dependent packages on requirement.txt or only required packages
Python
I need to speed up the following code : N is around 30 , so the code is very slow ( it takes about 33 hours on my laptop ) . The argument of the function f ( ) is the binary representation of the index i , and f ( ) can be an arbitrary vectorizable function . I 'm not an expert , but in order to speed up the code , I w...
for i in range ( 0 , 2**N ) : output [ i ] = f ( np.array ( map ( int , bin ( i ) [ 2 : ] .zfill ( N ) ) ) ) list ( itertools.product ( [ 0 , 1 ] , repeat=N ) )
How can I speed up this two-lines code ?
Python
In sympy I have defined a two kets and a corresponding bra , when I apply the bra to the kets ... ... I get this result : How do I set 'Dead ' and 'Alive ' as orthogonal states , so that d.doit ( ) gives sqrt ( 2 ) /2 ? So far I 've only been able to substitute the brakets by hand : But how do I make the brakets evalua...
from sympy import sqrtfrom sympy.physics.quantum import Bra , Ket , qapplysuperpos = ( Ket ( 'Dead ' ) +Ket ( 'Alive ' ) ) /sqrt ( 2 ) d = qapply ( Bra ( 'Dead ' ) *superpos ) sqrt ( 2 ) * < Dead|Alive > /2 + sqrt ( 2 ) * < Dead|Dead > /2 d.subs ( Bra ( 'Dead ' ) *Ket ( 'Dead ' ) ,1 ) .subs ( Bra ( 'Dead ' ) *Ket ( 'Al...
Evaluate inner product of bra and ket in Sympy Quantum
Python
Google Cloud Datastore is a non-relational database , and is built on the concept of eventual consistency . It also supplies a means to get strong consistency through ancestor queries and entity groups . However , I am not getting strong consistency when using ancestor queries within a transaction.Consider this : Since...
class Child ( ndb.Model ) : @ classmethod def create ( cls ) : child = cls ( ) child.put ( ) print Child.query ( ) .fetch ( ) Child.create ( ) [ ] class Parent ( ndb.Model ) : passclass Child ( ndb.Model ) : @ classmethod def create ( cls , parent ) : child = cls ( parent=parent ) child.put ( ) print Child.query ( ance...
Strong consistency within transactions in Google Cloud Datastore
Python
I have the following C declaration of a struct : So pretty typical tree with some payload . I tried to rewrite this to the following ctypes declaration : This unfortunately did not work , because at that time python compiler does not know the type VNODE yet.So I rewrote it to the following class : This did not work , b...
struct vnode { char firstchar ; uint8_t wordlength ; bool is_red ; struct vnode *left ; struct vnode *right ; struct textelem *texts ; } ; class VNODE ( Structure ) : _fields_ = [ ( `` firstchar '' , c_char ) , ( `` wordlength '' , c_ubyte ) , ( `` is_red '' , c_bool ) , ( `` left '' , POINTER ( VNODE ) ) , ( `` right ...
How can I setup a Structure in ctypes with pointer to itself ?
Python
In Perl one uses : In Python I found : But , what happens when the file given in the command line does NOT exist ? python test.py test1.txt test2.txt filenotexist1.txt filenotexist2.txt test3.txt was given as the argument.I tried various ways of using try : except : nextfile , but I could n't seem to make it work.For t...
while ( < > ) { # process files given as command line arguments } import fileinputfor line in fileinput.input ( ) : process ( line )
What is the equivalent of Perl 's ( < > ) in Python ? fileinput does n't work as expected
Python
With most Python interpreters that I 've used , Ctrl+C will cause the interpreter to print out `` KeyboardInterrupt '' and remain open . However , in a recent install on a new computer , Ctrl+C is causing the interpreter to exit , which is undesirable.Setting the signal.SIGINT handler still exits.There is n't a startup...
import timetry : time.sleep ( 100 ) except KeyboardInterrupt : pass
Windows Python interpreter exits on Ctrl+C
Python
I want to read a file and write it back out . Here 's my code : This does n't work , why ? ? ? ? ? Edit : The rewritten file is corrupt ( python 2.7.1 on windows )
file = open ( zipname , ' r ' ) content = file.read ( ) file.close ( ) alt = open ( ' x.zip ' , ' w ' ) alt.write ( content ) alt.close ( )
Read a zip an write it to an other file python
Python
Given a dataframe like this : How do I read it in using pd.read_clipboard ? I 've tried this : But it throws an error : How can I fix this ? Other pd.read_clipboard questions : How do you handle column names having spaces in them when using pd.read_clipboard ? How to handle custom named index when copying a dataframe u...
CA B 1.1 111 20 222 313.3 222 24 333 655.5 333 226.6 777 74 df = pd.read_clipboard ( index_col= [ 0 , 1 ] ) ParserError : Error tokenizing data . C error : Expected 2 fields in line 3 , saw 3
Copying MultiIndex dataframes with pd.read_clipboard ?
Python
I have 2 csv files with the same column names , but different values.The first column is the index ( time ) and one of the data columns is a unique identifier ( id ) The index ( time ) is different for each csv file.I have read the data into 2 dataframes using read_csv , giving me the following : I would like to create...
+ -- -- -- -+ -- -- -- + -- -- -- -+ | id | size | price |+ -- -- -- -+ -- -- -- -+ -- -- -- + -- -- -- -+| time | | | |+ -- -- -- -+ -- -- -- -+ -- -- -- + -- -- -- -+| t0 | ID1 | 10 | 110 || t2 | ID1 | 12 | 109 || t6 | ID1 | 20 | 108 |+ -- -- -- -+ -- -- -- -+ -- -- -- + -- -- -- -+ + -- -- -- -+ -- -- -- + -- -- -- ...
pandas : concatenate dataframes , forward-fill and multiindex on column data
Python
I 'm trying to build the Swagger settings for SecurityDefinition in order to get the following result in openapi.json : In my settings.py I have addded the following swagger settings : The issue is that in the openapi.json which generated by Swagger there is not the security dict and I have no clue how it is generated....
`` securityDefinitions '' : { `` password '' : { `` type '' : `` oauth2 '' , `` tokenUrl '' : `` http : //example.com/oauth/token '' , `` flow '' : `` password '' , `` scopes '' : { `` write '' : `` allows modifying resources '' , `` read '' : `` allows reading resources '' } } } , '' security '' : [ { `` password '' :...
Django REST Swagger : How to use security section in Swagger settings ?
Python
I 'm working with tkinter on Python 3.4.1 ( Windows 7 ) , and I 'm finding that ttk 's Entry.xview_moveto function is not working properly . Here is some simple code : The xview_moveto function should scroll the text all the way to the left , but it does n't . However , I noticed that if I useit works just fine . Why d...
from tkinter import *from tkinter import ttka = Tk ( ) text = StringVar ( a , value='qwertyuiopasdfghjklzxcvbnm1234567890 ' ) b = ttk.Entry ( a , textvariable=text ) b.grid ( ) b.xview_moveto ( 1 ) b.after ( 500 , b.xview_moveto , 1 )
Why does tkinter 's Entry.xview_moveto fail ?
Python
I have to solve the Travelling Salesman Problem using a genetic algorithm that I will have to write for homework.The problem consists of 52 cities . Therefore , the search space is 52 ! . I need to randomly sample ( say ) 1000 permutations of range ( 1 , 53 ) as individuals for the initial population of my genetic algo...
> > > random.sample ( itertools.permutations ( range ( 1 , 53 ) ) , 1000 ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > File `` /usr/lib/python2.6/random.py '' , line 314 , in sample n = len ( population ) TypeError : object of type 'itertools.permutations ' has no len ( ) > > > r...
Sampling Permutations of [ 1,2,3 , ... , N ] for large N
Python
I have a Tornado Python server which accepts a variable bitrate mp3 file one chunk at a time ( the chunks are made up of a fixed number of frames ) .All I am doing is passing that binary forward , however , I want to know the duration of the chunk . Because it is variable bitrate I can not do a simple calculation . I w...
def _on_read_frames ( self , data ) : logging.info ( 'read from input : \n % s ' , data ) binary_audio = base64.b64decode ( data ) # need to find out how many miliseconds went by here
Python decode MP3 in chunks on Mac OS
Python
I have written a function in cython that will search a STL vector of strings for a given string and return true if it is found , false otherwise . Performance is very important here ! I would ideally like to have a templated function to do the same thing so I do n't have to write a function for each data type . I am su...
from libcpp cimport boolfrom libcpp.string cimport stringfrom libcpp.vector cimport vectorfrom cython.operator cimport dereference as deref , preincrement as inccpdef bool is_in_vector ( string a , vector [ string ] v ) : cdef vector [ string ] .iterator it = v.begin ( ) while it ! = v.end ( ) : if deref ( it ) == a : ...
Templated STL containers as argument to function in cython
Python
As mentioned here , Below code , Output : Question : Why __eq__ gets called on accessing jimbut not on bob ?
class Person ( object ) : def __init__ ( self , name , ssn , address ) : self.name = name self.ssn = ssn self.address = address def __hash__ ( self ) : print ( 'in hash ' ) return hash ( self.ssn ) def __eq__ ( self , other ) : print ( 'in eq ' ) return self.ssn == other.ssnbob = Person ( 'bob ' , '1111-222-333 ' , Non...
When does __eq__ gets called using hash ( ) ?
Python
I 'm starting to learn to use google app engine and , in much of the code I 've come across , they declare the instance of the webapp.WSGIApplication as a global variable . This does n't seem to be necessary , as the code works fine when it is locally declared in the main function.I was always advised that global varia...
class Guestbook ( webapp.RequestHandler ) : def post ( self ) : greeting = Greeting ( ) if users.get_current_user ( ) : greeting.author = users.get_current_user ( ) greeting.content = self.request.get ( 'content ' ) greeting.put ( ) self.redirect ( '/ ' ) application = webapp.WSGIApplication ( [ ( '/ ' , MainPage ) , (...
Why is an instance of webapp.WSGIApplication always defined as a global variable in google app engine code ?
Python
I 've been learning Ruby and Python concurrently and one of the things I noticed is that these 2 languages seem to treat scope differently . Here 's an example of what I mean : It appears that def block can access variables declared outside of its immediate scope in Python but not in Ruby . Can someone confirm whether ...
# Pythona = 5def myfunc ( ) : print amyfunc ( ) # = > Successfully prints 5 # Rubya = 5def myfunc puts aendmyfunc # = > Throws a `` NameError : undefined local variable or method ` a ' for main : Object ''
Scope in Ruby and Python
Python
I 'm in the process of writing my first RESTful web service atop GAE and the Python 2.7 runtime ; I 've started out using Guido 's shiny new ndb API.However , I 'm unsure how to solve a particular case without the implicit back-reference feature of the original db API . If the user-agent requests a particular resource ...
class Contact ( ndb.Expando ) : `` '' '' The One `` '' '' # basic info name = ndb.StringProperty ( ) birth_day = ndb.DateProperty ( ) # If I were using db , a collection called 'phone_numbers ' would be implicitly # created here . I could use this property to retrieve related phone numbers # when this entity was querie...
Following backreferences of unknown kinds in NDB
Python
GivenI 'd likeCurrently I have brute forced it with : Finally , I 'd like to get toby running this right to left . Currently I haveI 'm not fussy about inplace or create a new list , but right now this smells to me . I ca n't see a way to store a temporary 'last ' value and use map/lambda , and nothing else is coming t...
a = [ None,1,2,3 , None,4 , None , None ] a = [ None,1,2,3,3,4,4,4 ] def replaceNoneWithLeftmost ( val ) : last = None ret = [ ] for x in val : if x is not None : ret.append ( x ) last = x else : ret.append ( last ) return ret a = [ 1,1,2,3,3,4,4,4 ] def replaceNoneWithRightmost ( val ) : return replaceNoneWithLeftmost...
Replace None in list with leftmost non none value
Python
I want to convert a DICOM image from int16 to uint8 . I have done it in Python using Z_axis = bytescale ( img ) , but this gives different results than using im2uint8 in MATLAB . In MATLAB , The minimum and maximum values of a DICOM image after converting to uint8 using im2uint8 are ( 124 , 136 ) , respectively . But t...
for person in range ( 0 , len ( dirs1 ) ) : if not os.path.exists ( os.path.join ( directory , dirs1 [ person ] ) ) : Pathnew = os.path.join ( directory , dirs1 [ person ] ) os.makedirs ( Pathnew ) for root , dirs , files in os.walk ( os.path.join ( path , dirs1 [ person ] ) ) : dcmfiles = [ _ for _ in files if _.endsw...
Difference between the functions `` im2uint8 '' ( in MATLAB ) and `` bytescale '' ( in Python )
Python
I try to run a simple linear fit in scikit-learn : As a result I get : Does anybody know what is the reason of this problem and how the problem can be resolved ? P.S . I use the version 0.16.1 of scikit-learn . But I had this problem also with an older version . I do it under Ubuntu.ADDEDToday I have tried another esti...
from sklearn import linear_modelclf = linear_model.LinearRegression ( ) clf.fit ( [ [ 0 , 0 ] , [ 1 , 1 ] , [ 2 , 2 ] ] , [ 0 , 1 , 2 ] ) Illegal instruction ( core dumped )
Why does scikit-learn cause core dumped ?
Python
Why is utc == 2016-11-27 22:46:00+00:00instead of 2016-11-27 21:46:00+00:00Thanks
> > > t = datetime.datetime ( 2016 , 11 , 27 , 14 , 46 , 0 , 0 ) tz = pytz.timezone ( 'America/Vancouver ' ) utc = tz.localize ( t ) .astimezone ( pytz.utc ) now = datetime.datetime.utcnow ( ) > > > print t , tz , utc , now2016-11-27 14:46:00 America/Vancouver 2016-11-27 22:46:00+00:00 2016-10-27 21:49:33.723605
Converting local time to UTC using pytz adds DST ?
Python
How can I most optimally remove identical items from a list and sort it in Python ? Say I have a list : I could iterate over a copy of the list ( since you should not mutate the list while iterating over it ) , item for item , and remove all of the item except for one : Which removes the redundant items : and then sort...
my_list = [ ' a ' , ' a ' , ' b ' , ' c ' , 'd ' , ' a ' , ' e ' , 'd ' , ' f ' , ' e ' ] for item in my_list [ : ] : # must iterate over a copy because mutating it count = my_list.count ( item ) # see how many are in the list if count > 1 : for _ in range ( count-1 ) : # remove all but one of the element my_list.remov...
How do I remove identical items from a list and sort it in Python ?
Python
The error that I am getting when I use import torchvision is this : Error MessageI do n't know what to do . I have tried changing the version of python from the native one to the one downloaded through anaconda . I am using anaconda as a package manager and have installed torch vision through anaconda as well as throug...
`` *Traceback ( most recent call last ) : File `` /Users/gokulsrin/Desktop/torch_basics/data.py '' , line 4 , in < module > import torchvisionModuleNotFoundError : No module named 'torchvision'* ''
Despite installing the torch vision pytorch library , I am getting an error saying that there is no module named torch vision
Python
I am using : SQLAlchemy 0.7.9 and Python 2.7.3 with Bottle 0.11.4 . I am an amateur at python.I have a class ( with many columns ) derived from declarative base like this : I am currently using this 'route ' in Bottle to dump out a row/class in json like this : My first question is : How can I have each column have som...
class Base ( object ) : @ declared_attr def __tablename__ ( cls ) : return cls.__name__.lower ( ) id = Column ( Integer , primary_key = True ) def to_dict ( self ) : serialized = dict ( ( column_name , getattr ( self , column_name ) ) for column_name in self.__table__.c.keys ( ) ) return serializedBase = declarative_ba...
SQLAlchemy Declarative : Adding a static text attribute to a column
Python
How do I check if two file pointers point to the same file or not.My use case is I am watching a file for changes and doing something , but logback rolls over this file to old date and creates a new file . But the file pointer variable in python is still pointing to the old file . If fp1 ! = fp2 , I would like to updat...
> > > fp1 = open ( `` /data/logs/perf.log '' , `` r '' ) > > > fp1 < open file '/data/logs/perf.log ' , mode ' r ' at 0x7f5adc07cc00 > > > > fp2 = open ( `` /data/logs/perf.log '' , `` r '' ) > > > fp2 < open file '/data/logs/perf.log ' , mode ' r ' at 0x7f5adc07cd20 > > > > fp1 == fp2False > > > fp1 is fp2False mv /da...
Check if two file pointers point to same file in Python
Python
Is it possible to change or assign new parent to the Model instance that already in datastore ? For example I need something like thisbut it does n't works this way because task.parent is built-in method . I was thinking about creating a new Key instance for the task but there is no way to change key as well.Any though...
task = db.get ( db.Key ( task_key ) ) project = db.get ( db.Key ( project_key ) ) task.parent = projecttask.put ( )
Change|Assign parent for the Model instance on Google App Engine Datastore
Python
I am trying to extract some features from a given document , given a pre-defined set of features . However the output , is a 2x3 array , filled in with zeros instead of : Any help would be much appreciated
from sklearn.feature_extraction.text import CountVectorizerfeatures = [ ' a ' , ' b ' , ' c ' ] doc = [ ' a ' , ' c ' ] vectoriser = CountVectorizer ( ) vectoriser.vocabulary = featuresvectoriser.fit_transform ( doc ) desired_output = [ [ 1 , 0 , 0 ] [ 0 , 0 , 1 ] ]
CountVectorizer returns only zeros
Python
Given the following Python function : If I turn it into a UDF and apply it to a column object , it works ... ... Except if the column is generated by rand : However , the following two work : The error : Why does this happen , and how can I use a rand column expression created within a UDF ?
def f ( col ) : return col from pyspark.sql import functions as Ffrom pyspark.sql.types import DoubleTypedf = spark.range ( 10 ) udf = F.udf ( f , returnType=DoubleType ( ) ) .asNondeterministic ( ) df.withColumn ( 'new ' , udf ( F.lit ( 0 ) ) ) .show ( ) df.withColumn ( 'new ' , udf ( F.rand ( ) ) ) .show ( ) # fails ...
Why does a PySpark UDF that operates on a column generated by rand ( ) fail ?
Python
In my country many websites get censored and blocked and are instead redirected to a certain page . I do n't know how they exactly do this . But is it possible to programmatically determine if a website is blocked or is not blocked without loading the whole thing ? The reason I want to do this is to use a web search AP...
< html > < head > < meta http-equiv= '' Content-Type '' content= '' text/html ; charset=windows-1256 '' > < title > M3-5 < /title > < /head > < body > < iframe src= '' http : //10.10.34.34 ? type=Invalid Site & policy=MainPolicy `` style= '' width : 100 % ; height : 100 % '' scrolling= '' no '' marginwidth= '' 0 '' mar...
Checking website redirection , programmatically
Python
I 'm trying to figure out if I can speed up the generation of permutations . Specifically I 'm using 8 out of [ a-z ] and I 'd like to use 8 out of [ a-zA-Z ] and 8 out of [ a-zA-Z0-9 ] . Which I know will quickly take a great deal of time and space.Even just a permutation of length 8 from the lowercase ASCII character...
import stringimport itertoolsfrom itertools import permutationscomb = itertools.permutations ( string.ascii_lowercase , 8 ) f = open ( '8letters.txt ' , ' w ' ) for x in comb : y = `` .join ( x ) f.write ( y + '\n ' ) f.close ( )
Can generating permutations be done in parallel ?
Python
I am trying to write an `` enum class '' in python . A slight nuisance I am currently experiencing is the inability to define enum values inside the enum class . That is , I can do this : But I would like to do this , or a similarly legible equivalent : Unfortunately , I am getting the following error : name 'Fruit ' i...
class Fruit : def __init__ ( self , name ) : self.name = nameclass Fruits ( Enum ) : Apple = Fruit ( `` apple '' ) class Fruit ( Enum ) : def __init__ ( self , name ) : self.name = name Apple = Fruit ( `` apple '' )
Python 2.x - creating static instance of class in same class
Python
I am trying to get two variables from one input like this : But I want to make the y variable optional , so if the user only inputs x it would only print that value . I get a ValueError if only inserted the x argument.Anyone knows how to do this ?
x , y = input ( ) .split ( ) print ( x , y )
Make an input optional in Python
Python
Using python 3 , one has the option to use typehints . My question is , if a function returns None , should one add this , or leave it blank.i.e.And which PEP addresses this ?
def hint ( p : str ) - > None : passdef no_hint ( p : str ) : pass
typehints - > None or leave blank
Python
In a previous life I did a fair bit of Java development , and found JUnit Theories to be quite useful . Is there any similar mechanism for Python ? Currently I 'm doing something like : But this is rather clunky , if the first `` case '' fails , all others fail to be run .
def some_test ( self ) : cases = [ ( 'some sample input ' , 'some expected value ' ) , ( 'some other input ' , 'some other expected value ' ) ] for value , expected in cases : result = method_under_test ( value ) self.assertEqual ( expected , result )
Unit test Theories in Python ?
Python
From here : Return a proxy object that delegates method calls to a parent or sibling class of type . This is useful for accessing inherited methods that have been overridden in a class . The search order is same as that used by getattr ( ) except that the type itself is skipped . If the second argument is omitted , the...
super ( [ type [ , object-or-type ] ] )
What is the type of the super object returned by super ( ) ?
Python
I am trying to create an excel workbook using xlsxwriter , but when I try to do workbook.close ( ) i get following exception : I am querying a database , then creating 3 sheets and filling tables in them , this is the code : The above code works perfectly fine in python3 on my local machine , however on server we are t...
Traceback ( most recent call last ) : File `` /usr/local/bin/fab '' , line 11 , in < module > sys.exit ( program.run ( ) ) File `` /usr/local/lib/python2.7/site-packages/invoke/program.py '' , line 363 , in run self.execute ( ) File `` /usr/local/lib/python2.7/site-packages/invoke/program.py '' , line 532 , in execute ...
Unable to close worksheet in xlsxwriter
Python
I believe I 'm getting bitten by some combination of nested scoping rules and list comprehensions . Jeremy Hylton 's blog post is suggestive about the causes , but I do n't really understand CPython 's implementation well-enough to figure out how to get around this . Here is an ( overcomplicated ? ) example . If people...
import itertoolsdef digit ( n ) : digit_list = [ ( x , False ) for x in xrange ( 1 , n+1 ) ] digit_list [ 0 ] = ( 1 , True ) return itertools.cycle ( digit_list ) > > > D = digit ( 5 ) > > > [ D.next ( ) for x in range ( 5 ) ] # # This list comprehension works as expected [ ( 1 , True ) , ( 2 , False ) , ( 3 , False ) ...
Unexpected list comprehension behaviour in Python
Python
print.__doc__ outputs : where asOutputs : Prints the values to a stream , or to sys.stdout by default . Optional keyword arguments : file : a file-like object ( stream ) ; defaults to the current sys.stdout . sep : string inserted between values , default a space . end : string appended after the last value , default a...
SyntaxError : invalid syntax > > > getattr ( __builtin__ , '' print '' ) .__doc__ print ( value , ... , sep= ' ' , end='\n ' , file=sys.stdout )
print.__doc__ vs getattr ( __builtin__ , '' print '' ) .__doc__
Python
Today I had a python exam where following question was asked : Given the following code extract , Complete the code so the output is : 10 7 5.How is it possible to get such output in python using range function ?
nums = list ( range ( ? , ? , ? ) ) print ( nums )
Python range with Uneven gap
Python
My problem StringPrint result : This works fine , I just write the string `` CT142H.0000 '' by hand tiping with keyboard ( Its the same code ) Print result : Why python encode the first string when I append it into a list ? -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -This is currently solved ,...
# -*- coding : utf-8 -*-print ( `` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # '' ) foo = `` СТ142Н.0000 '' print ( type ( foo ) ) print ( `` foo : `` +foo ) foo_l = [ ] foo_l.append ( foo ) print ( `` List : `` ) print ( foo_l ) print ( `` List decode : `` ) print ( [ x.decode ( `` UTF-8 '' ) for x...
Python 2.7 - Why python encode a string when .append ( ) in a list ?
Python
I 'm trying to interact with an NCURSES program.As an example I 'm using GNU Screen and run aptitude inside . ( you could try it with mc instead . ) The program below starts a screen session with -x to connect to my session.I want to navigate by pressing Arrow-down and Arrow-up.If I send ' q ' for quit I see a box pop ...
from twisted.internet import protocol , reactorclass MyPP ( protocol.ProcessProtocol ) : def connectionMade ( self ) : reactor.callLater ( 1.0 , self.foo ) def foo ( self ) : self.transport.write ( '\033 [ B ' ) def processExited ( self , reason ) : print `` processExited , status % s '' % ( reason.value.exitCode , ) d...
How do I interact with a child process pretending to be a terminal ?
Python
for a project , I am using Django on the back-end and AngularJs on the front end.Basically , what I want is to run the Angular app only when the url starts with projectkeeper/.In other words , lets say my website is example.com . I want the angular app to run for the URLs example.com/projectkeeper/dashboard/ , example....
urlpatterns = [ url ( r'^projectkeeper/ $ ' , TemplateView.as_view ( template_name='base.html ' ) ) , ] myapp.config ( [ ' $ routeProvider ' , function ( $ routeProvider ) { $ routeProvider .when ( '/dashboard/ ' , { title : 'Dashboard ' , controller : 'DashboardController ' , templateUrl : 'static/app_partials/project...
Using Django URLs with AngularJs routeProvider
Python
I use the Python-Qt bindings from PySide and I want to draw a scene with amongst others a rectangle and the rectangle is not fully visible because the view should only show a part of the scene where the rectangle is not fully contained.Here is a minimal example : I expect to see the lower part of a rectangle instead I ...
from PySide.QtGui import *app = QApplication ( [ ] ) scene = QGraphicsScene ( ) scene.addRect ( 0 , 0 , 100 , 100 ) view = QGraphicsView ( scene ) view.setSceneRect ( -60 , 20 , 100 , 100 ) view.show ( ) app.exec_ ( )
Why is a rectangle partly outside of view drawn as a triangle ?
Python
I 'm having trouble with encodings.I 'm using version Python 2.7.2+ ( default , Oct 4 2011 , 20:03:08 ) [ GCC 4.6.1 ] on linux2I have chars with accents like é à.My scripts uses utf-8 encoding Users can type strings usings raw_input ( ) with .called in the main loop 'pseudo ' shellData are stored as pickle in files.I m...
# ! /usr/bin/python # -*- coding : utf-8 -*- def rlinput ( prompt , prefill= '' ) : readline.set_startup_hook ( lambda : readline.insert_text ( prefill ) ) try : return raw_input ( prompt ) finally : readline.set_startup_hook ( ) while to_continue : to_continue , feedback = action ( unicode ( rlinput ( u'todo > ' ) , '...
Lost with encodings ( shell and accents )
Python
After getting back into Python , I 'm starting to notice and be annoyed more and more by my C # coding style requiring braces everywherepreferring the ( subjective ) much cleaner looking python counter-partis there any way I can go about hiding these braces ( as they do take up about 30 % of my coding screen on average...
if ( ... ) { return ... ; } else { return ... ; } if ... : return ... else return ...
Hide curly braces in C #
Python
A colleague of mine wrote code analogous to the following today , asked me to have a look , and it took me a while to spot the mistake : The problem here is that there 's no self parameter to super ( ) in B 's constructor . What surprised me is that absolutely nothing happens in this case , i.e . no error , nothing . W...
class A ( ) : def __init__ ( self ) : print ( ' A ' ) class B ( A ) : def __init__ ( self ) : super ( B ) .__init__ ( ) b = B ( )
Second parameter of super ( ) ?
Python
I can see two very similar ways of having properties in Python ( a ) Property class ( b ) Property decoratorQuestionAre those two pieces of code identical ( e.g . bytecode wise ) ? Do they show the same behavior ? Are there any official guides which `` style '' to use ? Are there any real advantages of one over the oth...
class Location ( object ) : def __init__ ( self , longitude , latitude ) : self.set_latitude ( latitude ) self.set_longitude ( longitude ) def set_latitude ( self , latitude ) : if not ( -90 < = latitude < = 90 ) : raise ValueError ( 'latitude was { } , but has to be in [ -90 , 90 ] ' .format ( latitude ) ) self._latit...
Is there an advantage of using the property decorator compared to the property class ?
Python
I have the following list : seqList = [ 0 , 6 , 1 , 4 , 4 , 2 , 4 , 1 , 7 , 0 , 4 , 5 ] I want to print the items in the list only when it is present more than once ( in this case value 1 and 4 ) and I want to ignore the first value in the list ( in this case value 0 ) To count how many times each value is present in t...
from collections import CounterseqList = [ 0 , 6 , 1 , 4 , 4 , 2 , 4 , 1 , 7 , 0 , 4 , 6 ] c = dict ( Counter ( seqList ) ) print ( c ) { 0 : 2 , 6 : 1 , 1 : 2 , 4 : 4 , 2 : 1 , 7 : 1 , 5 : 1 } -value 1 appears multiple times ( 2 times ) -value 4 appears multiple times ( 4 times )
How do I print values only when they appear more than once in a list in python
Python
I ca n't find concise information about what is going on in this very simple program : The output of this simple test is : I clearly do not understand how python handles each case . Could any one provide a link so that I can read about it , or a short explanation of what is happening ? Thanks a lot .
print 'case 1 ' # a and b stay differenta = [ 1,2,3 ] b = ab = [ 4,5,6 ] print ' a = ' , aprint ' b = ' , bprintprint 'case 2 ' # a and b becomes equala = [ 1,2,3 ] b = ab [ 0 ] = 4 b [ 1 ] = 5 b [ 2 ] = 6 print ' a = ' , aprint ' b = ' , bprintprint 'case 3 ' # a and b stay different nowa = [ 1,2,3 ] b = a [ : ] b [ 0...
Python variable handling , I do n't understand it
Python
Lets say I have a table that look like this : I want to get rid of the Date column , then aggregate by Company AND region to find the average of Count and sum of Amount.Expected output : I looked into this post here , and many other posts online , but seems like they are only performing one kind of aggregation action (...
Company Region Date Count AmountAAA XXY 3-4-2018 766 8000AAA XXY 3-14-2018 766 8600AAA XXY 3-24-2018 766 2030BBB XYY 2-4-2018 66 3400BBB XYY 3-18-2018 66 8370BBB XYY 4-6-2018 66 1380 Company Region Count AmountAAA XXY 766 18630BBB XYY 66 13150 aggregation = { 'Count ' : { 'Total Count ' : 'mean ' } , 'Amount ' : { 'Tot...
pandas : how to group by multiple columns and perform different aggregations on multiple columns ?
Python
This is the same question as this question , which is marked as a duplicate of this one.The problem , and the reason I 'm still asking , is that the solution provided ( using pandas.read_clipboard ( ) ) currently does n't work.I use Python 3.5 and whenever I try to copy data from the clipboard I get an error : '' It se...
c1 c2 c3 c40 1 2 2 11 1 3 2 32 3 4 4 33 4 5 6 54 5 6 9 7
Pasting data into a pandas dataframe
Python
I am using opencv module to read and write the image . here is the code and below is the image i am reading and second image is after saving it on disk using cv2.imwrite ( ) . It is significantly visible that colors are dull in second image . Is there any workaround to this problem or I am missing on some sort of setti...
import cv2img = cv2.imread ( 'originalImage.jpg ' ) cv2.imwrite ( 'test.jpg ' , img )
Color gets dull : opencv cv2.imread cv2.imwrite
Python
I am new to python decorators . I have understood the basic concepts with the help of simple examples . But when I tried to read this more practical decorator , I feel lost . Given below is the code followed by my questions : My doubts : When we prefix the decorator to a function , does that mean that we are creating a...
class countcalls ( object ) : `` Decorator that keeps track of the number of times a function is called . '' __instances = { } def __init__ ( self , f ) : self.__f = f self.__numcalls = 0 countcalls.__instances [ f ] = self def __call__ ( self , *args , **kwargs ) : self.__numcalls += 1 return self.__f ( *args , **kwar...
Unable to understand this python decorator
Python
Using Django 1.6 and Rest Framework 2 . I have a uri below that I want to present a second resource as a child of that resource , with create , list , get and delete methodsI am new and still learning , I tried this url config : then registering the router I added : and the following viewset : The error I am getting ( ...
/rest/parent_resource/951 /rest/parent_resource/951/child_resource router.register ( r'parent_resource ' , diliMarketplace.MarketPlaceProposalViewSet_Internal ) url ( r'^rest/parent_resource/ ( ? P < parent_resource_pk > [ 0-9 ] + ) /child_resource/ $ ' , ChildViewset.as_view ( ) ) url ( r'^rest/ ' , include ( router.u...
routing one rest resource as a child of a second rest resource
Python
When I have this codeYou can write your name after that string . But , how to have something display at the end of the input ? So no matter what you write , the ' ) ' character appears as you are writing ?
input ( 'Write your name : ' ) > > > Write your name : My name > > > Write your name : ( Name ) > > > Write your name : ( Name Name ) > > > Write your name : ( Name Name Name )
How to input text between two strings ?
Python
For example , the implementation of Keras ' Adagrad has been : And the Function 'get_update ( ) ' seems one step update . However should the accumulators be stored the history information ? Why it has been initialized to zeros at each step ? How it can be an accumulator through the whole training process ? What does th...
class Adagrad ( Optimizer ) : '' '' '' Adagrad optimizer.It is recommended to leave the parameters of this optimizerat their default values. # Arguments lr : float > = 0 . Learning rate . epsilon : float > = 0. decay : float > = 0 . Learning rate decay over each update. # References - [ Adaptive Subgradient Methods for...
How Adagrad works in Keras ? What does self.weights mean in Keras Optimizer ?
Python
I was looking at how Python implements the property descriptor internally . According to the docs property ( ) is implemented in terms of the descriptor protocol , reproducing it here for convenience : My question is : why are n't the last three methods implemented as follows : Is there a reason for returing new instan...
class Property ( object ) : `` Emulate PyProperty_Type ( ) in Objects/descrobject.c '' def __init__ ( self , fget=None , fset=None , fdel=None , doc=None ) : self.fget = fget self.fset = fset self.fdel = fdel if doc is None and fget is not None : doc = fget.__doc__ self.__doc__ = doc def __get__ ( self , obj , objtype=...
Python property descriptor design : why copy rather than mutate ?
Python
I have a python project where I use : pipenvtoxpytestand many more.Basically , I want to add tox to my gitlab pipelines . And almost everything seems to work , calling mypy , flake8 or black from tox works fine . But when I call tox -e py37 ( so I want to run the tests ) with coverage enabled , the tests are run , I ca...
[ tox ] envlist = flake8 , mypy , black , py37 [ testenv ] extras = testscommands= pytest -- cov -ra -- tb=short { posargs } [ run ] branch = Truesource = fooomit = foo/__init__.py foo/__main__.py foo/bar/__init__.py foo/baz/__init__.py [ report ] exclude_lines = pragma : no cover if __name__ == .__main__.show_missing ...
Tox 0 % coverage
Python
To find the loss during training a model we can use cntk.squared_error ( ) function , like this : But I am interested in finding the loss in terms of absolute error . The below code does n't work : It gives error as : AttributeError : module 'cntk ' has no attribute 'absolute_error'Is there any inbuilt function in CNTK...
loss = cntk.squared_error ( z , l ) loss = cntk.absolute_error ( z , l )
CNTK absolute error
Python
I want to selectively hide some resources based on some form of authentication in web.py , but their existence is revealed by 405 responses to any HTTP method that I have n't implemented.Here 's an example : When an undefined method request is issued , the resource is revealed : I could implement the same check for the...
import weburls = ( '/secret ' , 'secret ' , ) app = web.application ( urls , globals ( ) ) class secret ( ) : def GET ( self ) : if web.cookies ( ) .get ( 'password ' ) == 'secretpassword ' : return `` Dastardly secret plans ... '' raise web.notfound ( ) if __name__ == `` __main__ '' : app.run ( ) $ curl -v -X DELETE h...
web.py : How to selectively hide resources with 404s for any HTTP method ?
Python
I ’ m using django-allauth to authenticate users ( uses Patreon 's API v1 ) , which adds a json to the database with the info below . I would like to show extra content on the site if the user 's pledge matches a particular tier ( or is above one ) .At first I though relationships.pledges.data.id would have the ID of t...
{ `` attributes '' : { `` about '' : null , `` can_see_nsfw '' : true , `` created '' : `` 2019-05-20T20:29:02.000+00:00 '' , `` default_country_code '' : null , `` discord_id '' : null , `` email '' : `` admin @ email.com '' , `` facebook '' : null , `` facebook_id '' : null , `` first_name '' : `` Adm '' , `` full_na...
How to find user 's patreon pledge tier using django-allauth for authentication
Python
I have a class that need to make some magic with every operator , like __add__ , __sub__ and so on.Instead of creating each function in the class , I have a metaclass which defines every operator in the operator module.The approach works fine , but I think It would be better if I generate the replacement operator only ...
import operatorclass MetaFuncBuilder ( type ) : def __init__ ( self , *args , **kw ) : super ( ) .__init__ ( *args , **kw ) attr = '__ { 0 } { 1 } __ ' for op in ( x for x in dir ( operator ) if not x.startswith ( '__ ' ) ) : oper = getattr ( operator , op ) # ... I have my magic replacement functions here # ` func ` f...
Intercept operator lookup on metaclass
Python
I 've been using the dis module to observe CPython bytecode . But lately , I 've noticed some inconvenient behavior of dis.dis ( ) .Take this example for instance : I first define a function multiplier with a nested function inside of it inner : I then use dis.dis ( ) to disassemble it : As you can see , it disassemble...
> > > def multiplier ( n ) : def inner ( multiplicand ) : return multiplicand * n return inner > > > > > > from dis import dis > > > dis ( multiplier ) 2 0 LOAD_CLOSURE 0 ( n ) 3 BUILD_TUPLE 1 6 LOAD_CONST 1 ( < code object inner at 0x7ff6a31d84b0 , file `` < pyshell # 12 > '' , line 2 > ) 9 LOAD_CONST 2 ( 'multiplier....
Is there a way to make dis.dis ( ) print code objects recursively ?
Python
I have pandas dataframe of length 7499042 like this : each value in pandas dataframe is numpy array of length 50.Now I am extracting it like this : I have layers like this : But when I am passing my input to this while training . It is showing the error : The shape of input it is showing is ( 7499042 , ) . Please help ...
' X ' ' y ' [ 0.1,0.2 ... ] 0.2 [ 0.3,0.4 , .. ] 0.3.. input = df [ ' X ' ] .values main_input = Input ( shape= ( 50,1 ) , name='main_input ' ) lstm_out=LSTM ( 32 , activation='tanh ' , recurrent_activation='sigmoid ' , return_sequences=True ) mean_pooling=AveragePooling1D ( pool_size=2 , strides=2 , padding='valid ' )...
Keras : ValueError : Error when checking input
Python
I have a file with x number of string names and their associated IDs . Essentially two columns of data.What I would like , is a correlation style table with the format x by x ( having the data in question both as the x-axis and y axis ) , but instead of correlation , I would like the fuzzywuzzy library 's function fuzz...
import pandas as pdfrom fuzzywuzzy import fuzzdf = pd.read_csv ( 'random_data_file.csv ' ) df = df [ [ 'ID ' , 'String ' ] ] df [ 'String_Dup ' ] = df [ 'String ' ] # creating duplicate of data in questiondf = df.set_index ( 'ID ' ) df = df.groupby ( 'ID ' ) [ [ 'String ' , 'String_Dup ' ] ] .apply ( fuzz.ratio ( ) )
Python fuzzy string matching as correlation style table/matrix
Python
Python classes have this neat feature where you can decorate a class method with the @ property decorator , which makes the method appear as a statically-valued member rather than a callable . For example , this : results in the following behavior : So finally , my question : is there any built-in syntax that provides ...
class A ( object ) : def my_method ( self ) : return `` I am a return value . '' @ property def my_property ( self ) : return `` I am also a return value . '' > > > a = A ( ) > > > a.my_method ( ) ' I am a return value . ' > > > a.my_property ' I am also a return value . '
Is there an equivalent to Python-style class properties in ES6 ?
Python
I have a model : What is the impact of changing unique_together to Should I be careful before deploying this update ? There are more than 150.000 users online at the same time , what could happen in the worst case ?
class MyModel ( models.Model ) : name = models.CharField ( max_length=10 ) nickname = models.CharField ( max_length=10 ) title = models.CharField ( max_length=10 ) score = models.CharField ( max_length=10 ) class Meta : unique_together = [ 'name ' , 'nickname ' ] unique_together = [ 'name ' , 'title ' ]
django - unique_together change - any danger in prod db ?
Python
As any Python programmer knows , you should use == instead of is to compare two strings for equality . However , are there actually any cases where ( s is `` '' ) and ( s == `` '' ) will give different results in Python 2.6.2 ? I recently came across code that used ( s is `` '' ) in code review , and while pointing out...
> > > a = `` '' > > > b = `` abc '' [ 2:2 ] > > > c = `` .join ( [ ] ) > > > d = re.match ( ' ( ) ' , 'abc ' ) .group ( 1 ) > > > e = a + b + c + d > > > a is b is c is d is eTrue
Can ( s is `` '' ) and ( s == `` '' ) ever give different results in Python 2.6.2 ?
Python
Consider this dictionary of pandas series . The index on all series are integers and have some potential overlap , but certainly do not coincide . I made an observation that pd.concat seems slow when combining things along axis=1 when I have large indices , lots of non-overlap , and many items to concatenate . It promp...
dict_of_series = { 's % s ' % i : pd.Series ( 1 , np.unique ( np.random.randint ( 1000 , 10000 , size=1000 ) ) ) for i in range ( 100 ) } % % timeitpd.concat ( dict_of_series , axis=0 ) .unstack ( 0 ) % % timeitpd.concat ( dict_of_series , axis=1 )
Why is pd.concat ( { } , axis=1 ) slower than pd.concat ( { } , axis=0 ) .unstack ( 0 ) ?
Python
From my understanding , is supposed to close the file once the with statement completed . However , now I seein one place , looked around and figured out , that closing is supposed to close the file upon finish of the with statement.So , what 's the difference between closing the file and closing the file ?
with open ( ... ) as x : with closing ( open ( ... ) ) as x :
What is the difference between 'with open ( ... ) ' and 'with closing ( open ( ... ) ) '
Python
I would like to plot the surface of my data which is given by 3D vectors in cartesian coordinates x , y , z . The data can not be represented by a smooth function.So first we generate some dummy data with the function eq_points ( N_count , r ) which returns an array points with the x , y , z coordinates of each point o...
# credit to Markus Deserno from MPI # https : //www.cmu.edu/biolphys/deserno/pdf/sphere_equi.pdfdef eq_points ( N_count , r ) : points = [ ] a = 4*np.pi*r**2/N_count d = np.sqrt ( a ) M_theta = int ( np.pi/d ) d_theta = np.pi/M_theta d_phi = a/d_theta for m in range ( M_theta ) : theta = np.pi* ( m+0.5 ) /M_theta M_phi...
How can I plot the surface of a structure which is given by vectors in python ?
Python
I have a column of string names , and I would like to find often occuring patterns ( words ) .Is there a way to return , say , strings with a higher ( or equal ) length than X , and occur more often than Y times in the the whole column ? Referring to the comment by Tim : I would like the nested ones to be removed , so ...
column < - c ( `` bla1okay '' , `` okay1243bla '' , `` blaokay '' , `` bla12okay '' , `` okaybla '' ) getOftenOccuringPatterns < - function ( ... .. ) getOftenOccuringPatterns ( column , atleaststringsize=3 , atleasttimes=4 ) > what times [ 1 ] bla 5 [ 2 ] okay 5 getOftenOccurringPatterns ( column , atleaststringsize=3...
Get often occuring string patterns from column in R or Python
Python
Say I have an expression as follows : One could factorize it as : or asor asamong other possibilities . For other expressions , the # of possibilities can be much larger.My question is , does SymPy have any utility that allows the user to choose which of them to display ? Is there a way to specify the common factor/s t...
a*b*c + b*c + a*d b* ( a*c + c ) + ( a*d ) c* ( a*b + b ) + ( a*d ) a*d + b*c* ( a + 1 ) a , b , c , d = symbols ( `` a , b , c , d '' ) # These two equations are mathematically equivalent : eq1 = a*b*c + b*c + a*deq2 = a*d + b*c* ( a + 1 ) print collect ( eq1 , a ) print collect ( eq2 , a ) a* ( b*c + d ) + b*ca*d + b...
Choosing between different expression factorizations in SymPy