lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
I 'm developing a Tensorflow sequence model that uses a beam search through an OpenFST decoding graph ( loaded from a binary file ) over the logits output from a Tensorflow sequence model.I 've written a custom op that allows me to perform decoding over the logits , but each time , I 'm having the op call fst : :Read (...
FstDecodingOp.Initialize ( 'BINARY_FILE.bin ' ) # loads the BINARY_FILE.bin into memory ... for o in output : FstDecodingOp.decode ( o ) # uses BINARY_FILE.bin to decode REGISTER_OP ( `` FstDecoder '' ) .Input ( `` log_likelihoods : float '' ) .Attr ( `` fst_decoder_path : string '' ) ... ... .template < typename Devic...
How do I write a Tensorflow custom op containing a persistent C++ object ?
Python
I want to switch J1 's position with the card under it after the deck array is shuffled . Is there a way to reference J1 without knowing its position in the array ? Thank you .
import randomdeck = [ 'AC ' , '2C ' , '3C ' , '4C ' , '5C ' , '6C ' , '7C ' , '8C ' , '9C ' , 'TC ' , 'JC ' , 'QC ' , 'KC ' , 'AS ' , '2S ' , '3S ' , '4S ' , '5S ' , '6S ' , '7S ' , '8S ' , '9S ' , 'TS ' , 'JS ' , 'QS ' , 'KS ' , 'AH ' , '2H ' , '3H ' , '4H ' , '5H ' , '6H ' , '7H ' , '8H ' , '9H ' , 'TH ' , 'JH ' , 'Q...
Knowing an item 's location in an array
Python
With JS , i send a AJAX post request.On my Apache2 mod_Python server , I wish for my python file to access data . How can i do this ? PS : here is how to reproduce the problem . Create testjson.html : and create testjson.py containing : Create a .htaccess containing : Here is the result : testjson.html:10 POST http : /...
$ .ajax ( { method : '' POST '' , url : '' https : //my/website/send_data.py '' , data : JSON.stringify ( data ) , contentType : 'application/json ; charset=UTF-8 ' def index ( req ) : # data = ? ? < script type= '' text/javascript '' > xhr = new XMLHttpRequest ( ) ; xhr.open ( `` POST '' , `` testjson.py '' ) ; xhr.se...
How to send data via POST or GET in Mod_Python ?
Python
Is there any way to type an abstract parent class method such that the child class method is known to return itself , instead of the abstract parent.This is more to improve autocompletes for IDEs like PyCharm or VScode 's python plugin .
class Parent ( ABC ) : @ abstractmethod def method ( self ) - > [ what to hint here ] : passclass Child1 ( Parent ) def method ( self ) : pass def other_method ( self ) : passclass GrandChild1 ( Child1 ) def other_method_2 ( self ) : pass
Type-Hinting Child class returning self
Python
Given a matrix of order n*n. I need to find the length of the largest sorted sub-matrix ( sorted both in row-wise and column-wise manner in increasing order ) .I made the following code which is not giving out the correct output because of some error in my logic.My pseudo code : Given array : expected output=8 ( length...
arr= [ map ( int , raw_input ( ) .split ( ) ) for j in range ( n ) ] # given lista= [ [ 0 for j in range ( n ) ] for i in range ( n ) ] # empty lista [ 0 ] [ 0 ] =1for i in range ( n ) : for j in range ( 1 , n ) : if i==0 and arr [ i ] [ j-1 ] < =arr [ i ] [ j ] : # compare list element with the right element a [ i ] [...
How to find the Largest sorted sub matrix ( sorted row-wise as well as column-wise ) of a given matrix ?
Python
It seems to be a commonplace that accesses to lexical scope can be worked out at compile time ( or by a static analyzer , since my example is in Python ) based simply on location in the source code.Here is a very simple example where one function has two closures with different values for a.I have no problem with the i...
def elvis ( a ) : def f ( s ) : return a + ' for the ' + s return ff1 = elvis ( 'one ' ) f2 = elvis ( 'two ' ) print f1 ( 'money ' ) , f2 ( 'show ' )
Does lexical scope have a dynamic aspect ?
Python
Question : Say I have a list a = [ 'abd ' , ' the dog ' , ' 4:45 AM ' , '1234 total ' , 'etc ... ' , ' 6:31 PM ' , ' 2:36 ' ] How can I go about removing elements such as 4:45 AM and 6:31 PM and ' 2:36 ' ? i.e , how can I remove elements of the form number : number|number and those with AM/PM on the end ? To be honest ...
[ x for x in a if x ! = something ]
How can I remove all strings that fit certain format from a list ?
Python
Django 1.11 and later allow using F-expressions for adding nulls last option to queries : However , we want to use this functionality for creating Indexes . A standard Django Index inside a model definition : I tried something along the lines of : which returns AttributeError : 'OrderBy ' object has no attribute 'start...
queryset = Person.objects.all ( ) .order_by ( F ( 'wealth ' ) .desc ( nulls_last=True ) ) indexes = [ models.Index ( fields= [ '-wealth ' ] ) , ] indexes = [ models.Index ( fields= [ models.F ( 'wealth ' ) .desc ( nulls_last=True ) ] ) , ]
Django `` NULLS LAST '' for creating Indexes
Python
I am an AMPL user trying to write a linear programming optimization model using Python ( My first Python code ) . I am trying to find how to declare indexed parameters over compound sets . For example , in AMPL , i would say : Set A Set B Set C param x { A , B , C } param y { A , B , C } param z { A , B , C } The above...
import pyodbc con = pyodbc.connect ( 'Trusted_Connection=yes ' , driver = ' { SQL Server Native Client 10.0 } ' , server = 'Server ' , database='db ' ) cur = con.cursor ( ) cur.execute ( `` execute dbo.SP @ Param = % d '' % Param ) result = cur.fetchall ( ) Comp_Key , x , y , z= dict ( ( A , B , C , [ x , y , z ] ) for...
AMPL vs. Python - Importing tables ( multi-dimensional dictionaries ? )
Python
I got a headache looking for this : How do you use s/// in an expression as opposed to an assignment . To clarify what I mean , I 'm looking for a perl equivalent of python 's re.sub ( ... ) when used in the following context : The only way I know how to do this in perl so far is : Note the extra assignment .
newstring = re.sub ( 'ab ' , 'cd ' , oldstring ) $ oldstring =~ s/ab/cd/ ; $ newstring = $ oldstring ;
How can I use Perl 's s/// in an expression ?
Python
In the Python standard library documentation , the example implementation of __subclasshook__ is : CPython 's implementation of collections.abc indeed follows this format for most of the __subclasshook__ member functions it defines.What is the purpose of explicitly checking the cls argument ?
class MyIterable ( metaclass=ABCMeta ) : [ ... ] @ classmethoddef __subclasshook__ ( cls , C ) : if cls is MyIterable : if any ( `` __iter__ '' in B.__dict__ for B in C.__mro__ ) : return True return NotImplemented
Why check if cls is the class in __subclasshook__ ?
Python
This is my custom extension of one of Andrew NG 's neural network from deep learning course where instead of producing 0 or 1 for binary classification I 'm attemptingto classify multiple examples.Both the inputs and outputs are one hot encoded.With not much training I receive an accuracy of 'train accuracy : 67.516580...
train_set_x = np.array ( [ [ 1,1,1,1 ] , [ 0,1,1,1 ] , [ 0,0,1,1 ] ] ) train_set_y = np.array ( [ [ 1,1,1 ] , [ 1,1,0 ] , [ 1,1,1 ] ] ) ValueError Traceback ( most recent call last ) < ipython-input-11-0d356e8d66f3 > in < module > ( ) 27 print ( A ) 28 -- - > 29 np.multiply ( train_set_y , A ) 30 31 def initialize_with...
Modify neural net to classify single example
Python
I have a task requiring an operation on every element of a list , with the outcome of the operation depending on other elements in the list.For example , I might like to concatenate a list of strings conditional on them starting with a particular character : This code solves the problem : resulting in : But this seems ...
x = [ '*a ' , ' b ' , ' c ' , '*d ' , ' e ' , '*f ' , '*g ' ] concat = [ ] for element in x : if element.startswith ( '* ' ) : concat.append ( element ) else : concat [ len ( concat ) - 1 ] += element concatOut [ 16 ] : [ '*abc ' , '*de ' , '*f ' , '*g ' ]
Operate on a list in a pythonic way when output depends on other elements
Python
Using argparse ( or something else ? ) I would like each positional argument to have an optional argument with default value.The arguments would be as so : and I want it to parse this into something usable , like a list of the positional arguments and a list of the optional arguments with defaults filled in . e.g . if ...
script.py arg1 arg2 -o 1 arg3 -o 2 arg4 arg5 positional = [ arg1 , arg2 , arg3 , arg4 , arg5 ] optional = [ 0 , 1 , 2 , 0 , 0 ]
Optional argument for each positional argument
Python
I am trying to solve this problem from leetcode , going to copy here for convenienceAfter ( unsuccessfully ) trying it , I googled the solution and this worksI understand the logic except why na and nb are assigned a value of 0x7FFFFFFF . It looks like it is int32 's maximum value . Can someone help me explain the sign...
Given an integer array , find three numbers whose product is maximum and output the maximum product.Example 1 : Input : [ 1,2,3 ] Output : 6Example 2 : Input : [ 1,2,3,4 ] Output : 24Note : The length of the given array will be in range [ 3,104 ] and all elements are in the range [ -1000 , 1000 ] .Multiplication of any...
Maximum Product of Three Numbers
Python
I came over this , where `` not None '' equals both True and False simultaneously.At first I expected that this would be because of the order of operators , but however when testing a similar expression : Can anyone explain why this is happening ?
> > > not NoneTrue > > > not None == TrueTrue > > > not None == FalseTrue > > > not FalseTrue > > > not False == FalseFalse > > > not False == TrueTrue
Logical paradox in python ?
Python
Characters such as - , + etc are not parsed the same way as alphanumeric ASCII characters by Python 's readline based cmd module . This seems to be linux specific issue only , as it seems to work as expected on Mac OS.Sample codeExpected behavior on Mac OSIncorrect behavior on LinuxI tried adding - to cmd.Cmd.identchar...
import cmdclass Test ( cmd.Cmd ) : def do_abc ( self , line ) : print line def complete_abc ( self , text , line , begidx , endidx ) : return [ i for i in [ '-xxx ' , '-yyy ' , '-zzz ' ] if i.startswith ( text ) ] try : import readlineexcept ImportError : print `` Module readline not available . `` else : import rlcomp...
Python cmd on linux does not autocomplete special characters or symbols
Python
I am converting decimal degrees to print as DMS . The conversion algorithm is what you would expect , using modf , with the addition that sign is taken out of the MS portion and left in only for the D portion . Everything is fine except for the case where the Degree is negative zero , -0 . An example is -0.391612 which...
def dec_to_DMS ( decimal_deg ) : deg = modf ( decimal_deg ) [ 1 ] deg_ = fabs ( modf ( decimal_deg ) [ 0 ] ) min = modf ( deg_ * 60 ) [ 1 ] min_ = modf ( deg_ * 60 ) [ 0 ] sec = modf ( min_ * 60 ) [ 1 ] return deg , min , secdef print_DMS ( dms ) : # dms is a tuple # make sure the `` - '' is printed for -0.xxx format =...
How to print negative zero in Python
Python
I have a data frame which has missing dates How do I insert 4/14/1979 at the 4th rowprint data
print data Date Longitude Latitude Elevation Max Temperature \4/11/1979 83.75 24.197701 238 44.769 20.007 4/12/1979 83.75 24.197701 238 41.967 18.027 4/13/1979 83.75 24.197701 238 43.053 20.549 4/15/1979 83.75 24.197701 238 40.826 20.189 Date Longitude Latitude Elevation Max Temperature \4/11/1979 83.75 24.197701 238 4...
how to insert new row in pandas data frame at desired index
Python
I am trying to build an OCR for recognising seven segment display as mentioned belowUsing preprocessing tools of open CV I got it here Now I am trying to follow this tutorial - https : //www.pyimagesearch.com/2017/02/13/recognizing-digits-with-opencv-and-python/ But on the part I am getting error as -The error is solve...
digitCnts = contours.sort_contours ( digitCnts , method= '' left-to-right '' ) [ 0 ] digits = [ ] import numpy as np import cv2import imutils # import the necessary packagesfrom imutils.perspective import four_point_transformfrom imutils import contoursimport imutilsimport cv2 # define the dictionary of digit segments ...
Unable to use sort_contors for building seven segment OCR
Python
Without resorting to `` .join , is there a Pythonic way to use PyYAML 's yaml.load_all with fileinput.input ( ) for easy streaming of multiple documents from multiple sources ? I 'm looking for something like the following ( non-working example ) : Expected output : Of course , yaml.load_all expects either a string , b...
# example.pyimport fileinputimport yamlfor doc in yaml.load_all ( fileinput.input ( ) ) : print ( doc ) $ cat > pre.yaml < < < ' -- - prefix-doc ' $ cat > post.yaml < < < ' -- - postfix-doc ' $ python example.py pre.yaml - post.yaml < < < ' -- - hello'prefix-dochellopostfix-doc $ python example.py pre.yaml - post.yaml ...
How to use yaml.load_all with fileinput.input ?
Python
I have this scenario . Where i am writing one apps in Android usging bash/python . So that via PC i can connect to the Android and from Android using USB i can connect the destination PC/Server . But what API is available to send all my Android requests to USB , so that i can remotely have assistance for the Server PC ...
$ ip addr 2 : eth0 : < BROADCAST , MULTICAST , UP , LOWER_UP > mtu 1500 qdisc pfifo_fast state UP qlen 1000 link/ether d4 : be : d9:55:91:4a brd ff : ff : ff : ff : ff : ff inet 192.168.0.219/24 brd 192.168.0.255 scope global eth0 inet6 fe80 : :d6be : d9ff : fe55:914a/64 scope link valid_lft forever preferred_lft forev...
What framework of Android can be used to connect PC to Android and Android to other PC ?
Python
I have a large nested dictionary and I want to print its structure and one sample element in each level . For example : If I pretty print this using pprint , I 'll get all the elements which is very long , part of the output will be like the following : Is there a built-in way or a library to show only few top elements...
from collections import defaultdictnested = defaultdict ( dict ) for i in range ( 10 ) : for j in range ( 20 ) : nested [ 'key'+str ( i ) ] [ 'subkey'+str ( j ) ] = { 'var1 ' : 'value1 ' , 'var2 ' : 'value2 ' } from pprint import pprintpprint ( nested ) { 'key0 ' : { 'subkey0 ' : { 'var1 ' : 'value1 ' , 'var2 ' : 'valu...
Print the structure of large nested dictionaries in a compact way without printing all elements
Python
My case right now : Is it bad to have the code like that ? Does it clutter too much , or what are the implications of something like that ?
try : try : condition catch try : condition catchcatch major failure
Is it bad nesting try/catch statements ?
Python
With some help from here , I have this working almost exactly the way I want . Now I need to be able to add the ability to remove data from a file before the files are compared.The reason for this is the strings , `` data '' , that i 'm removing is known to differ each time the file is saved.I have written a regex to s...
HOSTNAME_RE = re.compile ( r'hostname + ( \S+ ) ' ) def get_file_info_from_lines ( filename , file_lines ) : hostname = None a_hash = hashlib.sha1 ( ) for line in file_lines : a_hash.update ( line.encode ( 'utf-8 ' ) ) match = HOSTNAME_RE.match ( line ) if match : hostname = match.group ( 1 ) return hostname , filename...
Using regex to replace file data
Python
I 'm using pandas to do a ring buffer , but the memory use keeps growing . what am I doing wrong ? Here is the code ( edited a little from the first post of the question ) : this is what I get : not sure if it 's related to this : https : //github.com/pydata/pandas/issues/2659Tested on MacBook Air with Anaconda Python
import pandas as pdimport numpy as npimport resourcetempdata = np.zeros ( ( 10000,3 ) ) tdf = pd.DataFrame ( data=tempdata , columns = [ ' a ' , ' b ' , ' c ' ] ) i = 0while True : i += 1 littledf = pd.DataFrame ( np.random.rand ( 1000 , 3 ) , columns = [ ' a ' , ' b ' , ' c ' ] ) tdf = pd.concat ( [ tdf [ 1000 : ] , l...
memory leak in creating a buffer with pandas ?
Python
I am using PHP 's bcmath library to perform operations on fixed-point numbers . I was expecting to get the same behaviour of Python 's Decimal class but I was quite surprised to find the following behaviour instead : while using Decimals in Python I get : Why is that ? As I am using this to perform very sensitive opera...
// PHP : $ a = bcdiv ( '15.80 ' , '483.49870000 ' , 26 ) ; $ b = bcmul ( $ a , '483.49870000 ' , 26 ) ; echo $ b ; // prints 15.79999999999999999999991853 # Python : from decimal import Decimala = Decimal ( '15.80 ' ) / Decimal ( '483.49870000 ' ) b = a * Decimal ( '483.49870000 ' ) print ( b ) # prints 15.800000000000...
PHP bcmath versus Python Decimal
Python
I need to mark negative contexts in a sentence . The algorithm goes as follows : Detect a negator ( not/never/ain't/don't/ etc ) Detect a clause ending punctuation ( . ; : ! ? ) Add _NEG to all the words in between this.Now , I have defined a regex to pick out all such occurences : I can detect and replace the matched ...
def replacenegation ( text ) : match=re.search ( r '' ( ( \b ( never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint ) \b ) |\b\w+n't\b ) ( ( ? ! [ . : ; ! ? ] ) . ) * [ . : ; ! ? \b ] '' , text ) if match : s=match.group ( ) print s news= '' '' ...
How to modify text that matches a particular regular expression in Python ?
Python
I have python code . `` کم '' is a string , consisting of two alphabets ک and م .but they are combined in arabic . i am giving this word to PIL library function . But it is saving image separately both alphabets . How can i combine them . ? output : that is ک and م .
data2= `` کم '' draw.text ( ( ( W-w ) /2 , ( H-h ) /2 ) , data2 , ( 0,0,0 ) , font=font ) draw = ImageDraw.Draw ( img ) img.save ( `` abc '' + '' .png '' )
PIL draw.text ( ) is displaying string containing arabic ligature as two separate glyphs
Python
Short , but complete , summaryI want to allow users of my function ( a class factory ) to inject/overwrite global imports when using my function ( longer explanation of rationale below ) . But there are about 10 different variables that could be passed in and it adds a number of very repetitive lines to the code . ( gr...
class Dummy ( object ) : passpkg1 , pkg2 = Dummy ( ) , Dummy ( ) pkg1.average = lambda *args : sum ( args ) / len ( args ) pkg2.get_lengths = lambda *args : map ( len , args ) def get_average ( *args , **kwargs ) : average = kwargs.get ( `` average '' ) or pkg1.average get_lengths = kwargs.get ( `` get_lengths '' ) or ...
Injecting `` global imports '' into Python functions
Python
How to handle variable length sublist unpacking in Python2 ? In Python3 , if I have variable sublist length , I could use this idiom : In Python2 , it 's an invalid syntax : BTW , this question is a little different from Idiomatic way to unpack variable length list of maximum size n , where the solution requires the kn...
> > > x = [ ( 1 , 2,3,4,5 ) , ( 2 , 4,6 ) , ( 3 , 5,6,7,8,9 ) ] > > > for i , *item in x : ... print ( item ) ... [ 2 , 3 , 4 , 5 ] [ 4 , 6 ] [ 5 , 6 , 7 , 8 , 9 ] > > > x = [ ( 1 , 2,3,4,5 ) , ( 2 , 4,6 ) , ( 3 , 5,6,7,8,9 ) ] > > > for i , *item in x : File `` < stdin > '' , line 1 for i , *item in x : ^SyntaxError :...
How to handle variable length sublist unpacking in Python2 ?
Python
I have a small part in my code thats similar to this one ( ofcourse with real matrices instead of the zero filled ones ) : and it looks like its causing memory leaks . When running the following code : I get : Is this a bug or is there something else I should do ? I 've also tried making the variable named by putting t...
x = [ rinterface.FloatSexpVector ( [ 0 ] * ( 1000**2 ) ) for i in xrange ( 20 ) ] y = robjects.r ( 'list ' ) ( x ) for i in xrange ( 10 ) : x = [ rinterface.FloatSexpVector ( [ 0 ] * ( 1000**2 ) ) for i in xrange ( 20 ) ] y = robjects.r ( 'list ' ) ( x ) del x del y robjects.r ( 'gc ( verbose=TRUE ) ' ) Error : can not...
memory leak with rpy
Python
I have a class which fetches details and populates the class with information if it 's instantiated already with an id using a details method . If it 's not instantiated yet I want it to instead use an argument passed into details as the id and return a new instantiated object . Something like the following : but also ...
f = Foo ( ) f.id = '123 ' f.details ( ) f = Foo.details ( id='123 ' )
Python method available for both instantiated/uninstantiated class
Python
Given two sets , how do I perform a pairwise comparison of each element in one set with each element of the other set.I would like to get top 3 results for each element in the initial set.\Is there a faster way to solve the task . I am looking for a more pythonic way of doing the task .
set1 = set ( [ str ( item ) for item in range ( 100 ) ] ) # Pls . note originally set contains stringsset2 = set ( [ str ( item ) for item in range ( 50,150 ) ] ) # set ( [ str ( item ) for item in range ( 50,100 ) ] ) for item in set1 : max = [ -1 , -1 , -1 ] for stuff in set2 : val = magicComp ( item , stuff ) if val...
Do a pairwise comparison of each element in two sets and return a top 3 ranklist
Python
So , I am new to Django , and can not for the life of me figure out why I keep getting a TypeError on my view.Error is : I have the following in the viewI am probably missing something in my settings.py , but not sure what it could be . Also , how do I link to my scss file ? I added the following in my settings.pyI thi...
TypeError at /filename must be a string , not NoneRequest Method : GETRequest URL : http : //127.0.0.1:8000/Django Version : 1.8.5Exception Type : TypeErrorException enter code hereValue : filename must be a string , not None < ! DOCTYPE html > { % load sass_tags % } < html > < head lang= '' en '' > ... < link href= ''...
Django-sass-processor TypeError
Python
I am trying to implement a custom Keras layer that will keep only the top N values of the input and convert all of the rest to zeros . I have one version that mostly works , but leaves more than N values if there are ties . I would like to use a sort function to always only leaves N non-zero values.Here is the mostly w...
def top_n_filter_layer ( input_data , n=2 , tf_dtype=tf_dtype ) : # # # # Works , but returns more than 2 values if there are ties : values_to_keep = tf.cast ( tf.nn.top_k ( input_data , k=n , sorted=True ) .values , tf_dtype ) min_value_to_keep = tf.cast ( tf.math.reduce_min ( values_to_keep ) , tf_dtype ) mask = tf.m...
How to implement a custom keras layer that only keeps the top n values and zeros out all the rest ?
Python
How do I convert this : Into this : Note : C and F are missing in the output because the corresponding items in the input list are False .
[ True , True , False , True , True , False , True ] 'AB DE G '
convert a list of booleans to string
Python
I 'd like to efficiently create a pandas DataFrame from a Python collections.Counter dictionary .. but there 's an additional requirement.The Counter dictionary looks like this : Those dictionary keys are tuples where the first is to become the row , and the second the column of the dataframe.The resulting DataFrame sh...
( a , b ) : 5 ( c , d ) : 7 ( a , d ) : 2 b da 5 2c 0 7
Create MultiIndex pandas DataFrame from dictionary with tuple keys
Python
I have the following code to create a container which pretends to behave like the set of all prime numbers ( actually hides a memoised brute-force prime test ) That seems to be working so far : But it 's not playing nicely with argparse : The docs just say that Any object that supports the in operator can be passed as ...
import mathdef is_prime ( n ) : if n == 2 or n == 3 : return True if n == 1 or n % 2 == 0 : return False else : return all ( n % i for i in xrange ( 3 , int ( 1 + math.sqrt ( n ) ) , 2 ) ) class Primes ( object ) : def __init__ ( self ) : self.memo = { } def __contains__ ( self , n ) : if n not in self.memo : self.memo...
Python argparse choices from an infinite set
Python
My Input is : Expected Output is : Iterating over input and using eval/literal_eval on the tuple-strings is not possible : How can I convert an item such as ' ( var1 , ) ' to a tuple where the inner objects are treated as strings instead of variables ? Is there a simpler way than writing a parser or using regex ?
input = [ ' ( var1 , ) ' , ' ( var2 , var3 ) ' ] output = [ ( 'var1 ' , ) , ( 'var2 ' , 'var3 ' ) ] > > > eval ( ' ( var1 , ) ' ) > > > NameError : name 'var1 ' is not defined
Convert tuple-strings to tuple of strings
Python
I installed a new pyvenv environment with the following commands : However , when I call which pip , I get the following : /usr/bin/pip . Apparently , the system wide pip installation is still used . If I look at the pyvenv documentation , it states the following : Changed in version 3.4 : Installs pip by default , add...
python3.4 -m venv envsource env/bin/activate
Call correct pip in pyvenv environment python3.4
Python
I need to non-linearly expand on each pixel value from 1 dim pixel vector with taylor series expansion of specific non-linear function ( e^x or log ( x ) or log ( 1+e^x ) ) , but my current implementation is not right to me at least based on taylor series concepts . The basic intuition behind is taking pixel array as i...
def taylor_func ( x , approx_order=2 ) : x_ = x [ ... , None ] x_ = tf.tile ( x_ , multiples= [ 1 , 1 , approx_order+ 1 ] ) pows = tf.range ( 0 , approx_order + 1 , dtype=tf.float32 ) x_p = tf.pow ( x_ , pows ) x_p_ = x_p [ ... , None ] return x_p_x = Input ( shape= ( 4,4,3 ) ) x_new = Lambda ( lambda x : taylor_func (...
expand 1 dim vector by using taylor series of log ( 1+e^x ) in python
Python
I am building an event dispatcher framework that decodes messages and calls back into user code . My C++ background suggests that I write : Then the framework user would write something like : But I can also imagine putting onFoo ( ) and onBar ( ) as methods of Dispatcher and letting the user replace them with other me...
class Handler : def onFoo ( self ) : pass def onBar ( self ) : passclass Dispatcher : def __init__ ( self ) : self.handler = Handler ( ) def run ( ) : while True : msg = decode_message ( ) # magic if msg == 'foo ' : handler.onFoo ( ) if msg == 'bar ' : handler.onBar ( ) class MyHandler ( Handler ) : def onFoo ( self ) ...
Is it idiomatic Python to use an abstract class for event handler callbacks ?
Python
I 've added a couple of BrowserViews through paster , now I 'm trying to run them from plone.app.testing , because I like repeatable and consistent tests . Calling the view manually from the browser works without any problems.I 've tried both importing and initializing views manually , as well as calling the class from...
*** KeyError : 'global_cache_settings eggs/Products.CMFPlone-4.1.4-py2.6.egg/Products/CMFPlone/skins/plone_templates/main_template.pt28 : < metal : cache use-macro= '' context/global_cache_settings/macros/cacheheaders '' > 29 : Get the global cache headers located in global_cache_settings.eggs/plone.app.layout-2.1.13-p...
plone.app.testing ca n't call BrowserView
Python
How can I add Members folder for my functional tests in plone.app.testing so that it is findable as in real site ? Have have set member area creation flag in my product installation step which I 'm testing.I need to get this test working : I specifically need Member folder functionality . Just a folder owned by the tes...
membership.memberareaCreationFlag = 1 class TestMemberFolder ( unittest.TestCase ) : layer = MY_FUNCTIONAL_TESTING def setUp ( self ) : portal = self.portal = self.layer [ 'portal ' ] def test_members_folder ( self ) : membership = getToolByName ( self.portal , 'portal_membership ' ) membership.addMember ( `` basicuser...
How to add Members folder in plone.app.testing ?
Python
In the Scipy documents written that : The function zeros creates an array full of zeros , the function ones creates an array full of ones , and the function empty creates an array whose initial content is random and depends on the state of the memory . By default , the dtype of the created array is float64.So I was ran...
import numpy as npnp.empty ( ( 1,2 ) ) array ( [ [ 6.92892901e-310 , 8.42664136e-317 ] ] ) np.empty ( ( 1,2 ) ) array ( [ [ 0. , 0 . ] ] )
run np.empty for the second time
Python
In general , it 's better to do a single query vs. many queries for a given object . Let 's say I have a bunch of 'son ' objects each with a 'father ' . I get all the 'son ' objects : Then , I 'd like to get all the fathers for that group of sons . I do : Then I can do : Now , this assumes that son.father.key ( ) does ...
sons = Son.all ( ) father_keys = { } for son in sons : father_keys.setdefault ( son.father.key ( ) , None ) fathers = Father.get ( father_keys.keys ( ) )
Accessing related object key without fetching object in App Engine
Python
I 'm trying to understand why object destruction works differently in new style classes compared to old style ones.on exit , this will output : however , if i use Wrapper as a new style class , only the wrapper destructor is called , and the output is : Could someone explain the behavior shown above ?
class Wrapper ( ) : class Inner ( object ) : def __del__ ( self ) : print 'Inner destructor ' innerInstance = Inner ( ) def __del__ ( self ) : print 'Wrapper destructor'if __name__ == '__main__ ' : x = Wrapper ( ) Wrapper destructorInner destructor Wrapper destructor
Python destructors in new and old style classes
Python
Trying to get my head around threading . In my code , it 's only firing one thread , when I think it should go straight on to the second . I 've been reading about locks and allocating but do n't quite understand . What would I need to do here to let 2 threads run independently at the same time ?
import threaddef myproc ( item ) : print ( `` Thread fired for `` + item ) while True : passthings = [ 'thingone ' , 'thingtwo ' ] for thing in things : try : thread.start_new_thread ( myproc ( thing ) ) except : print ( `` Error '' )
Understanding threading
Python
I got the following code snippet from Peter Norvig 's website ; it 's a decorator to enable memoization on function calls ( caching prior calls to the function to change an exponential recursion into a simple dynamic program ) . The code works fine , but I 'm wondering why the second to last line is necessary . This is...
def memo ( f ) : table = { } def fmemo ( *args ) : if args not in table : table [ args ] = f ( *args ) return table [ args ] fmemo.memo = table return fmemo
Why is a line in this python function necessary ? ( memoized recursion )
Python
In python there is the *args convention I am wondering if CF9 supports something similar.Here is the python example
> > > def func ( *args ) : for a in args : print a , `` is a quality argument '' > > > func ( 1 , 2 , 3 ) 1 is a quality argument2 is a quality argument3 is a quality argument > > >
Does Coldfusion support dynamic arguments ?
Python
We want to fetch parent child in such a way that it gives me latest 10 parents with each having only one latest child record . For example : Using above specified model structure , I would like to fetch latest 10 categories along with latest child item for each category.With only one query to the server I would like to...
Category- id- name- created_dateItem- id- name- category- created_date Category1.name , Category1.id , LatestItemForCat1.name , LatestItem1ForCat1.created_dateCategory2.name , Category2.id , LatestItemForCat2.name , LatestItem1ForCat2.created_dateCategory3.name , Category3.id , LatestItemForCat3.name , LatestItem1ForCa...
Optimized way of fetching parents with only latest child using django ORM
Python
for example : and I want to merge them to a dictionary like this : I have a way to do this , but I think it takes too much time : Is there any better ideas ?
list1= [ 'k1 ' , 'k2 ' , 'k3 ' , [ 'k4 ' , 'k5 ' , [ 'k6 ' , 'k7 ' ] ] ] list2= [ 'v1 ' , 'v2 ' , 'v3 ' , [ 'v4 ' , 'v5 ' , [ 'v6 ' , 'v7 ' ] ] ] dict1= { 'k1 ' : 'v1 ' , 'k2 ' : 'v2 ' , 'k3 ' : 'v3 ' , 'k4 ' : 'v4 ' , 'k5 ' : 'v5 ' , 'k6 ' : 'v6 ' , 'k7 ' : 'v7 ' } def mergeToDict ( keyList , valueList ) : resultDict ...
What 's the most efficient way to zip two nested list to a single level dictionary
Python
For all intents and purposes , I am a Python user and use the Pandas library on a daily basis . The named capture groups in regex is extremely useful . So , for example , it is relatively trivial to extract occurrences of specific words or phrases and to produce concatenated strings of the results in new columns of a d...
import numpy as npimport pandas as pdimport remyDF = pd.DataFrame ( [ 'Here is some text ' , 'We all love TEXT ' , 'Where is the TXT or txt textfile ' , 'Words and words ' , 'Just a few works ' , 'See the text ' , 'both words and text ' ] , columns= [ 'origText ' ] ) print ( `` Original dataframe\n -- -- -- -- -- -- --...
Regex named groups in R
Python
In Perl , to lowercase a textfile , I could do the following lowercase.perl : And on the command line : perl lowercase.perl < infile.txt > lowered.txtIn Python , I could do with lowercase.py : And on the command line : python lowercase.py infile.txt lowered.txtIs the Perl lowercase.perl different from the Python lowerc...
# ! /usr/bin/env perluse warnings ; use strict ; binmode ( STDIN , `` : utf8 '' ) ; binmode ( STDOUT , `` : utf8 '' ) ; while ( < STDIN > ) { print lc ( $ _ ) ; } # ! /usr/bin/env pythonimport ioimport syswith io.open ( sys.argv [ 1 ] , ' r ' , 'utf8 ' ) as fin : with io.open ( sys.argv [ 2 ] , ' r ' , 'utf8 ' ) as fou...
Lowercasing script in Python vs Perl
Python
I know that Union allows you to specify the logical-or of multiple types . I 'm wondering if there is a way to do something analogous for the logical-and , something like : I know that one option is to just explicitly define a new type that inherits from both Bar and Baz , like this : In my context that option is not i...
def foo ( x : And [ Bar , Baz ] ) : class BarAndBaz ( Bar , Baz ) : ... def foo ( x : BarAndBaz ) :
Type hint as logical-and of multiple types
Python
NOTE : This is about importing modules and not classes , functions from those modules , so I do n't think it 's a duplicate of the mane `` ImportError : can not import name '' results in SO , at least I have n't found one that matches this.I do understand that importing classes or functions from modules by name might c...
$ mkdir pkg $ touch pkg/__init__.py from __future__ import print_functionfrom __future__ import absolute_importfrom . import bdef A ( x ) : print ( ' I am A , x= { } . '.format ( x ) ) b.B ( x + 1 ) def Z ( x ) : print ( ' I am Z , x= { } . I\ 'm done now ! '.format ( x ) ) from __future__ import print_functionfrom __f...
Understanding behavior of Python imports and circular dependencies
Python
Declarative usage of Python 's enum.Enum requires values to be provided , when in the most basic use case for an enum we do n't actually care about names and values . We only care about the sentinels themselves . After reading a related Q & A recently , I realised it is possible to use the __prepare__ method of the enu...
class Color ( Enum ) : red blue green from collections import defaultdictclass EnumMeta ( type ) : @ classmethod def __prepare__ ( meta , name , bases ) : return defaultdict ( object ) def __new__ ( cls , name , bases , classdict ) : classdict.default_factory = None return type.__new__ ( cls , name , bases , classdict ...
Using __prepare__ for an Enum ... what 's the catch ?
Python
I 'm plotting a PGM image : Here 's the data I 'm using.The problem is some of the shown pixels are wrong . For example : the three grey boxes near the top of the image are of value 11 ( so they should be red , not red ) the two yellow pixels in the top row -- they are of value 8 , so they should be yellow-green , not ...
from pylab import *import numpy LABELS = range ( 13 ) NUM_MODES = len ( LABELS ) def read_ascii_pgm ( fname ) : `` '' '' Very fragile PGM reader . It 's OK since this is only for reading files output by my own app. `` '' '' lines = open ( fname ) .read ( ) .strip ( ) .split ( '\n ' ) assert lines [ 0 ] == 'P2 ' width ,...
Off by one error in imshow ?
Python
I noticed the following holds : Will this always be true or could it possibly depend on the system locale ? ( It seems strings are unicode in python 3 : e.g . this question , but bytes in 2.x )
> > > u'abc ' == 'abc'True > > > 'abc ' == u'abc'True
Will a UNICODE string just containing ASCII characters always be equal to the ASCII string ?
Python
I am creating a local response cache for which I am creating a Pipeline because I need to store information of an item depending on its ID , collected from a site.Now I also need to create a Downloader Middleware because depending on the ID that I previously stored , I do n't want to hit the site with a new Request , s...
DOWNLOADER_MIDDLEWARES = { 'myproject.urlcache.CachePipelineMiddleware ' : 1 , } ITEM_PIPELINES = { 'myproject.urlcache.CachePipelineMiddleware ' : 800 , }
scrapy : Middleware/Pipeline single instance
Python
I have the following t=5 DNA strings : I 'm trying to find the best motifs of length k=8 from the collection of strings using a laplace transform to randomly sample chunks of length k from each of the t strings.My helper functions are as follows : The output I should be getting for this is : I get different outputs eve...
DNA = `` 'CGCCCCTCTCGGGGGTGTTCAGTAAACGGCCAGGGCGAGGTATGTGTAAGTGCCAAGGTGCCAGTAGTACCGAGACCGAAAGAAGTATACAGGCGTTAGATCAAGTTTCAGGTGCACGTCGGTGAACCAATCCACCAGCTCCACGTGCAATGTTGGCCTA '' ' k = 8t = 5 def window ( s , k ) : for i in range ( 1 + len ( s ) - k ) : yield s [ i : i+k ] def HammingDistance ( seq1 , seq2 ) : if len ( seq1...
Unexpected output in randomized motif search in DNA strings
Python
This question is a slight spin on a previous question : Accessing the underlying struct of a PyObjectExcept in my version I want to know how to expose the fields of the Point struct as members of my new type.I have looked everywhere I could think , read numerous example Python extensions and read many tutorials , docs ...
# include < Python.h > # include < structmember.h > // This is actually defined elsewhere in someone else 's code.struct Point { int x ; int y ; } ; struct PointObject { PyObject_HEAD struct Point* my_point ; int z ; } ; static PyMemberDef point_members [ ] = { { `` z '' , T_INT , offsetof ( struct PointObject , z ) , ...
Expose an underlying struct as a member of a custom type within a Python extension
Python
The following code produces the given output.Output : Why does __sizeof__ ( ) print a smaller result when a second element is considered ? Should n't the output be larger ? I realize from this answer that I should be using sys.getsizeof ( ) , but the behavior seems odd nonetheless . I 'm using Python 3.5.2.Also , as @ ...
import sysprint ( 'ex1 : ' ) ex1 = 'Hello'print ( '\t ' , ex1.__sizeof__ ( ) ) print ( '\nex2 : ' ) ex2 = ( 'Hello ' , 53 ) print ( '\t ' , ex2.__sizeof__ ( ) ) ex1 : 54 ex2 : 40
__sizeof__ str is larger than __sizeof__ a tuple containing that string
Python
What I need to accomplish : Given a binary file , decode it in a couple different ways providing a TextIOBase API . Ideally these subsequent files can get passed on without my needing to keep track of their lifespan explicitly . Unfortunately , wrapping a BufferedReader will result in that reader being closed when the ...
In [ 1 ] : import ioIn [ 2 ] : def mangle ( x ) : ... : io.TextIOWrapper ( x ) # Will get GCed causing __del__ to call close ... : In [ 3 ] : f = io.open ( 'example ' , mode='rb ' ) In [ 4 ] : f.closedOut [ 4 ] : FalseIn [ 5 ] : mangle ( f ) In [ 6 ] : f.closedOut [ 6 ] : True In [ 1 ] : import ioIn [ 2 ] : class MyTex...
Prevent TextIOWrapper from closing on GC in a Py2/Py3 compatible way
Python
I am trying to lookup information regarding someone on Dbpedia but their name contains parenthesis in this case ending with _ ( musician ) which leads to an error .
SELECT ? birthPlaceWHERE { dbpedia : Tom_Johnston_ ( musician ) dbpprop : birthPlace ? birthPlace }
How to reference a page that contains parenthesis in SPARQL
Python
As far as I understand it , tuples and strings are immutable to allow optimizations such as re-using memory that wo n't change . However , one obvious optimisation , making slices of tuples refer to the same memory as the original tuple , is not included in python.I know that this optimization is n't included because w...
def test ( n ) : tup = tuple ( range ( n ) ) for i in xrange ( n ) : tup [ 0 : i ]
Since Tuples are immutable , why does slicing them make a copy instead of a view ?
Python
Here 's a very simple example of what I 'm trying to get around : The problem is that I can not refer to Test while it 's still being definedNormally , I 'd just do this : But I never create an instance of this class . It 's really just a container to hold a group of related functions and data ( I have several of these...
class Test ( object ) : some_dict = { Test : True } class Test ( object ) : some_dict = { } def __init__ ( self ) : if self.__class__.some_dict == { } : self.__class__.some_dict = { Test : True } class Test ( object ) : @ classmethod def class_init ( cls ) : cls.some_dict = { Test : True } Test.class_init ( )
class __init__ ( not instance __init__ )
Python
I 've come across some code that reads : I think that the following would do the same job : The reference says that it evaluates the suite if the test expression is found to be trueThe reference says of Boolean expressions : In the context of Boolean operations , and also when expressions are used by control flow state...
if bool ( x ) : doSomething if x : doSomething
Is there any difference between ` if bool ( x ) ` and ` if x ` in Python ?
Python
I need to assign a module & class to a dictionary key . Then pickle that dictionary to file . Then later , load the pkl file , then import & instantiate the class , based on that dictionary key value.I 've tried this : Yet it wo n't store a reference to module_exmaple.py in the pkl file.I 've tried a workaround of usin...
import module_examplefrom module_example import ClassExampledictionary = { 'module ' : module_example , 'class ' : ClassExample )
How do I pickle a dictionary containing a module & class ?
Python
Let 's say , I have a bunch of functions a , b , c , d and e and I want to find out if they directly use a loop : I want to write a function uses_loop so I can expect these assertions to pass : ( I expect uses_loop ( c ) to return False because c uses a list comprehension instead of a loop . ) I ca n't modify a , b , c...
def a ( ) : for i in range ( 3 ) : print ( i**2 ) def b ( ) : i = 0 while i < 3 : print ( i**2 ) i += 1def c ( ) : print ( `` \n '' .join ( [ str ( i**2 ) for i in range ( 3 ) ] ) ) def d ( ) : print ( `` \n '' .join ( [ `` 0 '' , `` 1 '' , `` 4 '' ] ) ) def e ( ) : `` for '' assert uses_loop ( a ) == Trueassert uses_l...
How to find out if ( the source code of ) a function contains a loop ?
Python
I 'm trying to do cython debugging on NixOS . I can easily install cython in a nix-shell ( chosen for simplicity of example ) , like this : Then we do a normal nix-shell of just python and see what version of python we get.All is well -- we get a non-debug python in both cases . And if we gdb it , we get ( no debugging...
$ nix-shell -p 'python27.withPackages ( p : [ p.cython ] ) ' $ cat /nix/store/s0w3phb2saixi0a9bzk8pjbczjaz8d7r-python-2.7.14-env/bin/python # ! /nix/store/jgw8hxx7wzkyhb2dr9hwsd9h2caaasdc-bash-4.4-p12/bin/bash -eexport PYTHONHOME= '' /nix/store/s0w3phb2saixi0a9bzk8pjbczjaz8d7r-python-2.7.14-env '' export PYTHONNOUSERSI...
Nixos : How do I get get a python with debug info included with packages ?
Python
File input.txt consists of two lines : first has integer number N space then integer number K ( 1 ≤ N , K ≤ 250000 ) . Second has N space-delimeted integers , where each integer is less than or equal to K. It is guaranteed that each integer from 1 to K is in the array . The task is to find subarray of minimum length , ...
Input Output5 3 2 41 2 1 3 26 4 2 62 4 2 3 3 1 with open ( 'input.txt ' ) as file : N , K = [ int ( x ) for x in file.readline ( ) .split ( ) ] alley = [ int ( x ) for x in file.readline ( ) .split ( ) ] trees = { } min_idx = ( 1 , N ) min_length = Nfor i in range ( N ) : trees [ alley [ i ] ] = i if len ( trees ) == K...
find minimum-length subarray that has all numbers
Python
Or is everything a method ? Since everything is an object , a is just a method of that file.py , right ?
def whatever :
Are there functions in Python , or is everything a method ?
Python
I am trying to calculate the optimal team for a Fantasy Cycling game . I have a csv-file containing 176 cyclist , their teams , the amount of points they have scored and the price to put them in my team . I am trying to find the highest scoring team of 16 cyclists.The rules that apply to the composition of any team are...
THOMAS Geraint , Team INEOS,142,13SAGAN Peter , BORA - hansgrohe,522,11.5GROENEWEGEN Dylan , Team Jumbo-Visma,205,11FUGLSANG Jakob , Astana Pro Team,46,10BERNAL Egan , Team INEOS,110,10BARDET Romain , AG2R La Mondiale,21,9.5QUINTANA Nairo , Movistar Team,58,9.5YATES Adam , Mitchelton-Scott,40,9.5VIVIANI Elia , Deceunin...
Finding all combinations based on multiple conditions for a large list
Python
I 'm trying to find a way to filter the admin queryset for page objects based up on the user provided , what I 've considered ( pseudo code ) : This wo n't work because feincms checks for a completely loaded django instance . A verbose solution would probably be not to load the page module at all , and either override ...
from feincms ... Pageclass MyPageAdmin ( PageAdmin ) : def __init__ ( self , *args , **kwargs ) : 'monkey business ' super ( MyPageAdmin , self ) .__init__ ( *args , **kwargs ) admin.site.unregister ( Page ) admin.site.register ( Page , MyPageAdmin ) from feincms ... PageAdminclass MyPage ( Page ) : objects = CustomMan...
Customizing the feincms page admin based on user
Python
I have a 120 GB file saved ( in binary via pickle ) that contains about 50,000 ( 600x600 ) 2d numpy arrays . I need to stack all of these arrays using a median . The easiest way to do this would be to simply read in the whole file as a list of arrays and use np.median ( arrays , axis=0 ) . However , I do n't have much ...
import pickleimport timeimport numpy as npfilename = 'images.dat ' # contains my 50,000 2D numpy arraysdef stack_by_pixel ( i , j ) : pixels_at_position = [ ] with open ( filename , 'rb ' ) as f : while True : try : # Gather pixels at a given position array = pickle.load ( f ) pixels_at_position.append ( array [ i ] [ ...
Optimizing my large data code with little RAM
Python
My ImageGenerators reading 2261 training and 567 testing images from folder . I am trying to train my model with 2000 samples_per_epoch and 20 batch_size . Batch_size is divisible for samples_per_epoch but somehow it is adding extra value and shows that warning : ( UserWarning : Epoch comprised more than samples_per_ep...
train_datagen = ImageDataGenerator ( rescale=1./255 , shear_range=0.1 , zoom_range=0.1 , rotation_range=5. , width_shift_range=0.1 , height_shift_range=0.1 ) val_datagen = ImageDataGenerator ( rescale=1./255 ) train_generator = train_datagen.flow_from_directory ( train_data_dir , target_size = ( img_width , img_height ...
Keras ' fit_generator extra training value
Python
I 'm trying to have my popular_query subquery remove dupe Place.id , but it does n't remove it . This is the code below . I tried using distinct but it does not respect the order_by rule.I did a test printout with How can I fix this ? Thanks !
SimilarPost = aliased ( Post ) SimilarPostOption = aliased ( PostOption ) popular_query = ( db.session.query ( Post , func.count ( SimilarPost.id ) ) . join ( Place , Place.id == Post.place_id ) . join ( PostOption , PostOption.post_id == Post.id ) . outerjoin ( SimilarPostOption , PostOption.val == SimilarPostOption.v...
How can I query rows with unique values on a joined column ?
Python
How can I extract a python enum subset without redefining it ? I would like to get an equivalent to MyDesiredSubset without having to define it again.So far I tried something like this , but MyTrySubset is broken and the code is ugly.Any suggestions how to get MyDesiredSubset without redefining it ?
from enum import unique , Enum @ uniqueclass MyEnum ( Enum ) : ONE = 1 TWO = 2 THREE = 3 FOUR = 4 @ uniqueclass MyDesiredSubset ( Enum ) : THREE = 3 FOUR = 4 @ uniqueclass MyTrySubset ( Enum ) : passfor item in MyEnum : setattr ( MyTrySubset , item.name , item.value )
How can I extract a python enum subset without redefining it ?
Python
I 'm using the Python docx library to generate an document , that I would like to be able to open and find spelling errors in . But when I open the document none of the spelling errors flag ( little red underlines ) or are identified if I run a spell check . If I edit a line or copy , cut and paste the content back int...
from docx import Documentdocument = Document ( ) paragraph = document.add_paragraph ( 'This has a spellling errror ' ) document.save ( r'SpellingTester.docx ' )
When using Python docx how to enable spelling in output document ?
Python
I have a rather performance related question about django queries . Say I have a table of employees with 10,000 records . Now If I 'm looking to select 5 random employees that are of age greater than or equal to 20 , let 's say some 5,500 employees are 20 or older . The django query would be : and the raw counterpart o...
Employee.objects.filter ( age__gte=20 ) .order_by ( ' ? ' ) [ :5 ] SELECT * FROM ` database ` . ` employee ` WHERE ` employee ` . ` age ` > = 20ORDER BY RAND ( ) LIMIT 5 ;
Django Query Performance
Python
After hearing the latest Stack Overflow podcast , Peter Norvig 's compact Python spell-checker intrigued me , so I decided to implement it in Scala if I could express it well in the functional Scala idiom , and also to see how many lines of code it would take.Here 's the whole problem . ( Let 's not compare lines of co...
import scala.io.Sourceval alphabet = `` abcdefghijklmnopqrstuvwxyz '' def train ( text : String ) = { `` [ a-z ] + '' .r.findAllIn ( text ) .foldLeft ( Map [ String , Int ] ( ) withDefaultValue 1 ) { ( a , b ) = > a ( b ) = a ( b ) + 1 } } val NWORDS = train ( Source.fromFile ( `` big.txt '' ) .getLines.mkString.toLowe...
How can I approximate Python 's or operator for set comparison in Scala ?
Python
According to the Official Unicode Consortium code chart , all of these are numeric : However , when I ask Python to tell me which ones are numeric , they all are ( even ⅟ ) except for four : Those are : Ↄ Roman Numeral Reversed One Hundredↄ Latin Small Letter Reversed C↊ Turned Digit Two↋ Turned Digit ThreeWhy does Pyt...
⅐ ⅑ ⅒ ⅓ ⅔ ⅕ ⅖ ⅗ ⅘ ⅙ ⅚ ⅛ ⅜ ⅝ ⅞ ⅟Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ Ⅶ Ⅷ Ⅸ Ⅹ Ⅺ Ⅻ Ⅼ Ⅽ Ⅾ Ⅿⅰ ⅱ ⅲ ⅳ ⅴ ⅵ ⅶ ⅷ ⅸ ⅹ ⅺ ⅻ ⅼ ⅽ ⅾ ⅿↀ ↁ ↂ Ↄ ↄ ↅ ↆ ↇ ↈ ↉ ↊ ↋ In [ 252 ] : print ( [ k for k in `` ⅐⅑⅒⅓⅔⅕⅖⅗⅘⅙⅚⅛⅜⅝⅞⅟ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅺⅻⅼⅽⅾⅿↀↁↂↃↄↅↆↇↈ↉↊↋ '' if not k.isnumeric ( ) ] ) [ ' Ↄ ' , ' ↄ ' , '↊ ' , '↋ ' ]
Why is ` '↊'.isnumeric ( ) ` false ?
Python
I 'm trying to document a Python project with ReadTheDocs . Initially , the build process would die when it got to : I 've read the rtd faq and used mock for the osgeo module that was giving me trouble . Now the build process makes it past that import but chokes on : With this rather unhelpful error : I 'm completely n...
from osgeo import gdal , osr from osgeo.gdalconst import * RuntimeError : sys.path must be a list of directory names
Mock with submodules for ReadTheDocs
Python
I 've got lots of address style strings and I want to sort them in a rational way.I 'm looking to pad all the numbers in a string so that : `` Flat 12A High Rise '' becomes `` Flat 00012A High Rise '' , there may be multiple numbers in the string.So far I 've got : Can that be improved - looks pugly to me !
def pad_numbers_in_string ( string , padding=5 ) : numbers = re.findall ( `` \d+ '' , string ) padded_string = `` for number in numbers : parts = string.partition ( number ) string = parts [ 2 ] padded_string += `` % s % s '' % ( parts [ 0 ] , parts [ 1 ] .zfill ( padding ) ) padded_string += stringreturn padded_string
How to pad all the numbers in a string
Python
I 've plotted a 3-d mesh in Matlab by below little m-file : I am going to acquire the same result by utilization of Python and its corresponding modules , by below code snippet : But the output of the Python is is considerably different with the Matlab one , and as a matter of fact is unacceptable.I am afraid of wrong ...
[ x , n ] = meshgrid ( 0:0.1:20 , 1:1:100 ) ; mu = 0 ; sigma = sqrt ( 2 ) ./n ; f = normcdf ( x , mu , sigma ) ; mesh ( x , n , f ) ; import numpy as npfrom scipy.integrate import quadimport matplotlib.pyplot as pltsigma = 1def integrand ( x , n ) : return ( n/ ( 2*sigma*np.sqrt ( np.pi ) ) ) *np.exp ( - ( n**2*x**2 ) ...
Algorithm equalivence from Matlab to Python
Python
I have been assigned the following : `` ... Plot your final MSD as a function of δt . Include errorbars σ = std ( MSD ) /√N , where std ( MSD ) is the standard deviation among the different runs and N is the number of runs . N.B . : This is the formula for the error of the mean for statistically independent , normally ...
# % % Brownian Motionimport mathimport matplotlib.pyplot as pltimport numpy as npimport randomP_dis = [ ] N = 10 # N = the number of iterations ( i.e . the number of iterations of the loop below ) for j in range ( N ) : T = 10000 # T = time steps i.e . the number of jumps the particle makes x_pos = [ 0 ] y_pos = [ 0 ] ...
Mean Square Displacement as a Function of Time in Python
Python
I have a decorator declared as a class : ... and when I use it to wrap a method in a class , calling that method does not seem to set the instance of the object as the first argument . While this behavior is not exactly unexpected , how would I go about getting self to be frozen when the method becomes an instance meth...
class predicated ( object ) : def __init__ ( self , fn ) : self.fn = fn self.fpred = lambda *args , **kwargs : True def predicate ( self , predicate ) : self.fpred = predicate return self def validate ( self , *args , **kwargs ) : return self.fpred ( *args , **kwargs ) def __call__ ( self , *args , **kwargs ) : if not ...
Methods decorated with a decorator class do not have the `` self '' argument frozen
Python
I 'm trying to use coverage.py to find the coverage of functional tests executed against a server process , deployed using .pyc files . And it seems coverage does not support this.Trying to overcome the problem , I created a simple .py module that calls other pyc files for which I provided the sources into a separate f...
coverage run -- source=../src main.py Coverage.py warning : No data was collected .
coverage.py against .pyc files
Python
I found a problem with exec ( It happened in a system that has to be extensible with user written scripts ) . I could reduce the problem itself to this code : I expected that memory should be freed by the garbage collector after the call of function fn . However , the Python process still consumes the additional 200MB ...
def fn ( ) : context = { } exec `` 'class test : def __init__ ( self ) : self.buf = ' 1'*1024*1024*200x = test ( ) ' '' in contextfn ( ) def fn ( ) : context = { } exec `` 'class test : def __init__ ( self ) : self.buf = ' 1'*1024*1024*200def f1 ( ) : x = test ( ) f1 ( ) `` ' in contextfn ( ) $ pythonPython 2.7 ( r27:8...
Python : exec statement and unexpected garbage collector behavior
Python
I have a pandas dataframe which contains data as shown below : So an ID can be under any class in a particular month and next month his class might change.Now what I want to do is for each ID get the number of months it has been under a particular class and also the latest class under which it falls . Something like be...
ID year_month_id Class1 201612 A2 201612 D3 201612 B4 201612 Other5 201612 Other6 201612 Other7 201612 A8 201612 Other9 201612 A1 201701 B ID Class_A Class_B Class_D Other Latest_Class1 2 3 4 0 B2 12 0 0 0 D
Get counts by group using pandas
Python
Why django uses tuple of tuples to store for example choices instead of standard dict ? Example : And should I do it to when I know the dict wo n't change in time ? I reckon the tuples are faster but does it matter if when I try to get value I 'm still need to convert it to dict to find it ? UPDATE : Clarification if I...
ORGINAL_MARKET = 1SECONDARY_MARKET = 2MARKET_CHOICES = ( ( ORGINAL_MARKET , _ ( 'Orginal Market ' ) ) , ( SECONDARY_MARKET , _ ( 'Secondary Market ' ) ) , ) dict ( self.MARKET_CHOICES ) [ self.ORGINAL_MARKET ]
Why django uses tuple of tuples to store static dictionaries and should i do the same ?
Python
Why does yield SyntaxError : invalid syntax ? What do the extra brackets add ?
1.__add__ ( 1 ) ( 1 ) .__add__ ( 1 )
Why does 1.__add__ ( 1 ) yield a syntax error ?
Python
This is my code in python but the answer it gives is not correct according to projecteuler.net.It gives an output 1189 . Am I making some mistake ?
a = 2**1000total = 0while a > = 1 : temp = a % 10 total = total + temp a = int ( a/10 ) print ( total )
python - Sum of digits in 2^1000 ?
Python
What is the difference between doingto doing
class a : def __init__ ( self ) : self.val=1 class a : val=1 def __init__ ( self ) : pass
Difference between defining a member in __init__ to defining it in the class body in python ?
Python
In Flask I 'm using a set of decorators for each route , but the code is `` ugly '' : I would prefer to have a declaration that groups all of them with a single decorator : I tried to follow the answer at Can I combine two decorators into a single one in Python ? but I can not make it working : because of this error th...
@ app.route ( `` /first '' ) @ auth.login_required @ crossdomain ( origin='* ' ) @ nocachedef first_page : ... . @ app.route ( `` /second '' ) @ auth.login_required @ crossdomain ( origin='* ' ) @ nocachedef second_page : ... . @ nice_decorator ( `` /first '' ) def first_page : ... . @ nice_decorator ( `` /second '' ) ...
How to group decorators in Python
Python
I 'm new to Python and have what is probably a very basic question about the 'best ' way to store data in my code . Any advice much appreciated ! I have a long .csv file in the following format : My scenario values run from 1 to 100 , year goes from 1961 to 1990 and month goes from 1 to 12 . My file therefore has 100*2...
Scenario , Year , Month , Value1,1961,1,0.51,1961,2,0.71,1961,3,0.2etc . str ( Scenario ) +str ( Year ) +str ( Month )
Most appropriate data structure ( Python )
Python
How do I get the variable part of type as a string ? ie : In each case here , I want what is inside single quotes : str , int , type as a string.I tried using a regex against repr ( type ( 1 ) ) and that works , but that does not seem robust or Pythonic . Is there a better way ?
> > > type ( 'abc ' ) < type 'str ' > > > > type ( 1 ) < type 'int ' > > > > type ( _ ) < type 'type ' >
Get the return of 'type ' as human readable string
Python
When two dataframes are concatenated ( using concat ) by default concat creates a new dataframe with the union of the columns of both , setting the values of any missing columns in the result with nan . For example ... But if the missing column in one of the dataframes contains timestamps this breaks ... Throws `` Attr...
import pandas as pda = pd.DataFrame ( { ' A ' : range ( 5 ) , ' B ' : range ( 5 ) } ) b = pd.DataFrame ( { ' A ' : range ( 5 ) } ) pd.concat ( [ a , b ] , sort=False ) A B0 0 0.01 1 1.0 ... 3 3 NaN4 4 NaN a = pd.DataFrame ( { ' A ' : range ( 5 ) , ' B ' : [ pd.Timestamp.utcnow ( ) for _ in range ( 5 ) ] } ) b = pd.Data...
Pandas concat does not handle Timestamp columns correctly ?