lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
I am working with some data and end up with a situation where I want to cut a series like this : To count the number of values in each level , I find two different answers when I do the following : Should n't both methods give the same results ?
df = pd.DataFrame ( { ' A ' : 10000* [ 1 ] , ' B ' : np.random.randint ( 0 , 1001 , 10000 ) } ) df [ 'level ' ] = pd.cut ( df.B , bins = [ 0 , 200 , 400 , 600 , 800 , 1000 ] , labels = [ ' i ' , 'ii ' , 'iii ' , 'iv ' , ' v ' ] ) df.level.value_counts ( sort = False ) i 1934ii 1994iii 2055iv 2056v 1952Name : level , dt...
Pivot table with count as aggfunc gives different result than value_counts
Python
I am currently designing a software which needs to manage a certain hardware setup.The hardware setup is as following : System - The system contains two identical devices , and has certain functionality relative to the entire system.Device - Each device contains two identical sub devices , and has certain functionality...
system_instance = system_manager_class ( some_params ) system_instance.some_func ( 0 ) # configure device_manager [ 0 ] .sub_device_manager [ 0 ] .entity [ 0 ] system_instance.some_func ( 5 ) # configure device_manager [ 0 ] .sub_device_manager [ 1 ] .entity [ 1 ] system_instance.some_func ( 8 ) # configure device_mana...
Manager / Container class , how to ?
Python
I am parsing JSON requests using the JSON library which parses into python dictionary . As the requests are user-generated , I need to fix default values for parameters that have not been supplied . Other languages have stuff like ternary operators which make sense for repetitive applications . But the code below needs...
if `` search_term '' in request.keys ( ) : search_term=request [ 'search_term ' ] else : search_term= '' '' if `` start '' in request.keys ( ) : start=request [ 'start ' ] else : start=0if `` rows '' in request.keys ( ) : rows=request [ 'rows ' ] else : rows=1000000
How to fix default values from a dictionary Pythonically ?
Python
So I 'm using locals ( ) to grab some arguments in the function . Works nicely : Standard stuff . But now let 's introduce a list comprehension : Ehh ? Why has it inserted a self-reference ?
def my_function ( a , b ) : print locals ( ) .values ( ) > > > my_function ( 1,2 ) [ 1 , 2 ] def my_function ( a , b ) : print [ x for x in locals ( ) .values ( ) ] > > > my_function ( 1,2 ) [ [ ... ] , 1 , 2 ]
Why does locals ( ) return a strange self referential list ?
Python
If I have a directory structure like this : And I want to be able to callHow do I make the contents of functions , classes , accessible as : in stead of : The subdivision in files is only there for convenience ( allowing easier collaboration ) , but I 'd prefer to have all the contents in the same namespace .
package/ __init__.py functions.py # contains do ( ) classes.py # contains class A ( ) import package as p p.do ( ) p.A ( ) p.functions.do ( ) p.classes.A ( )
Pulling python module up into package namespace
Python
I am looking for a good way to compare two dictionaries which contain the information of a matrix . So the structure of my dictionaries are the following , both dictionaries have identical keys : If I have to matrices , i.e . lists of list , I can use numpy.allclose . Is there something similar for dictionaries or is t...
dict_1 = { ( `` a '' , '' a '' ) :0.01 , ( `` a '' , '' b '' ) : 0.02 , ( `` a '' , '' c '' ) : 0.00015 , ... dict_2 = { ( `` a '' , '' a '' ) :0.01 , ( `` a '' , '' b '' ) : 0.018 , ( `` a '' , '' c '' ) : 0.00014 , ...
Compare Dictionaries for close enough match
Python
I 'm currently writing a parser to parse simple arithmetic formula : which only need ( and restrict ) to support +-*/ on number and variables . For example : It 's basicly used to calculate price on products.This is written in python and i would like to just use python 's own parser for simplicity . The idea is firstly...
100.50*num*discount
Convert ast.Num to decimal.Decimal for precision in python
Python
I 'm building a Django ( 1.6 ) site ( with twitter bootstrap ) which has some forms where the user has to fill in some dates.I enabled l10n and i18n.The datetime fields are controlled by a JQuery widget . The widget accept a parameter to define the input format of the date and time.How can I get the current django date...
> > > from django.utils import formats > > > formats.get_format ( `` SHORT_DATE_FORMAT '' , lang= '' nl '' ) Out [ 27 ] : u ' j-n-Y ' > > > formats.get_format ( `` SHORT_DATE_FORMAT '' , lang= '' fr '' ) Out [ 28 ] : u ' j N Y ' > > > formats.get_format ( `` SHORT_DATE_FORMAT '' , lang= '' de '' ) Out [ 29 ] : u'd.m.Y ...
django country from request
Python
Say I have a string : That I would like as : Basically , splitting only on increasing digits where the difference is .1 ( i.e . 1.2 to 1.3 ) . Is there a way to split this with regex but only capturing increasing sequential numbers ? I wrote code in python to sequentially iterate through using a custom re.compile ( ) f...
teststring = `` 1.3 Hello how are you 1.4 I am fine , thanks 1.2 Hi There 1.5 Great ! '' testlist = [ `` 1.3 Hello how are you '' , `` 1.4 I am fine , thanks 1.2 Hi There '' , `` 1.5 Great ! '' ] parts1_temp = [ ' 1.3 ' , ' 1.4 ' , ' 1.2 ' , ' 1.5 ' ] parts_num = range ( int ( parts1_temp.split ( ' . ' ) [ 1 ] ) , int ...
Regex using increasing sequence of numbers Python
Python
Is it possible to `` pipeline '' consumption of a generator across multiple consumers ? For example , it 's common to have code with this pattern : In this case , multiple functions completely consume the same iterator , making it necessary to cache the iterator in a list . Since each consumer exhausts the iterator , i...
def consumer1 ( iterator ) : for item in iterator : foo ( item ) def consumer2 ( iterator ) : for item in iterator : bar ( item ) myiter = list ( big_generator ( ) ) v1 = consumer1 ( myiter ) v2 = consumer2 ( myiter ) c1_retval , c2_retval = iforkjoin ( big_generator ( ) , ( consumer1 , consumer2 ) )
pipeline an iterator to multiple consumers ?
Python
To explain in a clearer way my question I will start by explaining the real-life case I am facing.I am building a physical panel with many words on it that can be selectively lit , in order to compose sentences . This is my situation : I know all the sentences that I want to displayI want to find out [ one of ] the sho...
SENTENCES : `` A dog is on the table '' `` A cat is on the table '' SOLUTIONS : `` A dog cat is on the table '' `` A cat dog is on the table ''
How to perform a sorting according to rules but with repetition of items to solve circular references ?
Python
I ’ ve noticed that assigning to a pandas DataFrame column ( using the .loc indexer ) behaves differently depending on what other columns are present in the DataFrame and on the exact form of the assignment . Using three example DataFrames : I ’ ve found the following : df1 : df1.col1 = xResult : df1.loc [ : , 'col1 ' ...
df1 = pandas.DataFrame ( { 'col1 ' : [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] } ) # col1 # 0 [ 1 , 2 , 3 ] # 1 [ 4 , 5 , 6 ] # 2 [ 7 , 8 , 9 ] df2 = pandas.DataFrame ( { 'col1 ' : [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] , 'col2 ' : [ [ 10 , 20 , 30 ] , [ 40 , 50 , 60 ] , [ 70 , 80 , 90 ] ] } ) # col1...
Assigning rank 2 numpy array to pandas DataFrame column behaves inconsistently
Python
I have a class that contains several functions ( most of it contains code that parses smth. , get all necessary info and print it ) . I 'm trying to print a class but i get smth . like < _main_.TestClass instance at 0x0000000003650888 > . Code sample : When i print functions out of class - all is ok. What i 'm doing wr...
from lxml import htmlimport urllib2url = 'someurl.com'class TestClass : def testFun ( self ) : f = urllib2.urlopen ( url ) .read ( ) # some code print 'Value for ' +url+ ' : ' , SomeVariable def testFun2 ( self ) : f2 = urllib2.urlopen ( url ) .read ( ) # some code print 'Value2 for ' +url+ ' : ' , SomeVariable2test = ...
How can I print a Python class ?
Python
I 'm trying to type-check the latest revision of my code and get inconsistent results using the ALE plugin in vim and mypy on the command line . Update : After the comments from @ aaron below , I checked out the code on a different machine , and it works as expected : I get more errors there , than on my main developme...
$ ./env/bin/mypy puresnmppuresnmp/aio/api/raw.py:505 : error : Type signature has too few argumentspuresnmp/api/pythonic.py:239 : error : Type signature has too few argumentspuresnmp/api/raw.py:490 : error : Type signature has too few argumentspuresnmp/test/asyncmock.py:18 : error : 'yield ' in async functionFound 4 er...
Scanning a package with mypy yields different result on different machines
Python
I have noticed this in Python 's threading module source : Am I correct in assuming this is an attempt in mimicking a `` sealed '' class ( c # ) or a `` final '' class ( java ) in other languages ? Is this a common pattern in Python ? Are there any other approaches to this problem in Python ?
def Event ( *args , **kwargs ) : return _Event ( *args , **kwargs ) class _Event ( _Verbose ) : ...
Python convention : function constructor for a private class
Python
I have recently stated trying to use the newer style of classes in Python ( those derived from object ) . As an excersise to familiarise myself with them I am trying to define a class which has a number of class instances as attributes , with each of these class instances describing a different type of data , e.g . 1d ...
some_class.data_type.some_variable class profiles_1d ( object ) : def __init__ ( self , x , y1=None , y2=None , y3=None ) : self.x = x self.y1 = y1 self.y2 = y2 self.y3 = y3class collection ( object ) : def __init__ ( self ) : self._profiles_1d = None def get_profiles ( self ) : return self._profiles_1d def set_profile...
Using a class instance as a class attribute , descriptors , and properties
Python
I am trying to remove all strings from a list of tuplesI have started to try and find a solution : But I ca n't seem to get my head around how I would get an output like : The format is always ( int , str ) .
ListTuples = [ ( 100 , 'AAA ' ) , ( 80 , 'BBB ' ) , ( 20 , 'CCC ' ) , ( 40 , 'DDD ' ) , ( 40 , 'EEE ' ) ] output = [ i for i in ListTuples if i [ 0 ] == str ] print ( output ) [ ( 100 ) , ( 80 ) , ( 20 ) , ( 40 ) , ( 40 ) ]
How to remove all strings from a list of tuples python
Python
I 'm using the Tensorflow Dataset API to prepare my data for input into my network . During this process , I have some custom Python functions which are mapped to the dataset using tf.py_function . I want to be able to debug the data going into these functions and what happens to that data inside these functions . When...
import tensorflow as tfdef add_ten ( example , label ) : example_plus_ten = example + 10 # Breakpoint here . return example_plus_ten , labelexamples = [ 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 ] labels = [ 0 , 0 , 1 , 1 , 1 , 1 , 0 , 0 ] examples_dataset = tf.data.Dataset.from_tensor_slices ( examples ) labels_dataset = ...
IDE breakpoint in TensorFlow Dataset API mapped py_function ?
Python
I 'm attempting to create a simple linear model with Python using no libraries ( other than numpy ) . Here 's what I haveFirst , it converges VERY quickly . After only 14 iterations . Second , it gives me a different result than a linear regression with sklearn . For reference , my sklearn code is : My custom model pre...
import numpy as npimport pandasnp.random.seed ( 1 ) alpha = 0.1def h ( x , w ) : return np.dot ( w.T , x ) def cost ( X , W , Y ) : totalCost = 0 for i in range ( 47 ) : diff = h ( X [ i ] , W ) - Y [ i ] squared = diff * diff totalCost += squared return totalCost / 2housing_data = np.loadtxt ( 'Housing.csv ' , delimit...
Why does n't my custom made linear regression model match sklearn ?
Python
I have written a Python function that computes pairwise electromagnetic interactions between a largish number ( N ~ 10^3 ) of particles and stores the results in an NxN complex128 ndarray . It runs , but it is the slowest part of a larger program , taking about 40 seconds when N=900 [ corrected ] . The original code lo...
import numpy as npdef interaction ( s , alpha , kprop ) : # s is an Nx3 real array # alpha is complex # kprop is float ndipoles = s.shape [ 0 ] Amat = np.zeros ( ( ndipoles,3 , ndipoles , 3 ) , dtype=np.complex128 ) I = np.array ( [ [ 1,0,0 ] , [ 0,1,0 ] , [ 0,0,1 ] ] ) im = complex ( 0,1 ) k2 = kprop*kprop for i in ra...
Cython speedup is n't as large as expected
Python
I have a Python project with the following structure : All of the modules are empty except testapp/api/__init__.py which has the following code : and testapp/api/utils.py which defines x : Now from the root I import testapp.api : The result of the import surprises me , because it shows that the second import statement ...
testapp/├── __init__.py├── api│ ├── __init__.py│ └── utils.py└── utils.py from testapp import utilsprint `` a '' , utilsfrom testapp.api.utils import xprint `` b '' , utils x = 1 $ export PYTHONPATH= $ PYTHONPATH : . $ python -c `` import testapp.api '' a < module 'testapp.utils ' from 'testapp/utils.pyc ' > b < module...
Why might Python 's ` from ` form of an import statement bind a module name ?
Python
I have a matrix , X , for which I am computing a weighted sum of intermediate matrix products . Here 's a minimal reproducible example : This works fine and produces the results I expect . However , as the size of n and y grow ( into the hundreds ) , this becomes extremely expensive , as repetitively computing matrix p...
import numpy as nprandom_state = np.random.RandomState ( 1 ) n = 5p = 10X = random_state.rand ( p , n ) # 10x5X_sum = np.zeros ( ( n , n ) ) # 5x5 # The length of weights are not related to X 's dims , # but will always be smallery = 3weights = random_state.rand ( y ) for k in range ( y ) : X_sum += np.dot ( X.T [ : , ...
Efficiently sum complex matrix products with Numpy
Python
I have switched from R to pandas . I routinely get SettingWithCopyWarnings , when I do something likeI think I understand the problem , though I 'll gladly learn what I got wrong . In the given example , it is undefined whether df_b is a view on df_a or not . Thus , the effect of assigning to df_b is unclear : does it ...
df_a = pd.DataFrame ( { 'col1 ' : [ 1,2,3,4 ] } ) # Filtering step , which may or may not return a viewdf_b = df_a [ df_a [ 'col1 ' ] > 1 ] # Add a new column to df_bdf_b [ 'new_col ' ] = 2 * df_b [ 'col1 ' ] # SettingWithCopyWarning ! ! df_a = pd.DataFrame ( { 'col1 ' : [ 1,2,3,4 ] } ) # Filtering step , definitely a ...
What is the point of views in pandas if it is undefined whether an indexing operation returns a view or a copy ?
Python
My problem is very simple . I would like to compute the following sum.However python gives RuntimeWarning : overflow encountered in multiply and nan as the output and it is also very very slow.Is there a clever way to do this ?
from __future__ import divisionfrom scipy.misc import combimport mathfor n in xrange ( 2,1000,10 ) : m = 2.2*n/math.log ( n ) print sum ( sum ( comb ( n , a ) * comb ( n-a , b ) * ( comb ( a+b , a ) *2** ( -a-b ) ) **m for b in xrange ( n+1 ) ) for a in xrange ( 1 , n+1 ) )
How to compute an expensive high precision sum in python ?
Python
I am creating a fast method of generating a list of primes in the range ( 0 , limit+1 ) . In the function I end up removing all integers in the list named removable from the list named primes . I am looking for a fast and pythonic way of removing the integers , knowing that both lists are always sorted.I might be wrong...
# removable and primes are both sorted lists of integersfor composite in removable : primes.remove ( composite ) i = 0j = 0while i < len ( primes ) and j < len ( removable ) : if primes [ i ] == removable [ j ] : primes = primes [ : i ] + primes [ i+1 : ] j += 1 else : i += 1 import math # returns a list of primes in r...
What 's a fast and pythonic/clean way of removing a sorted list from another sorted list in python ?
Python
When I list all the Fortran files in NumPy 's source tree , I get : So none other than f2py itself uses Fortran . I looked into the linear algebra modules . For LAPACK , there is a make_lite.py file which extracts only the necessary subroutines from a LAPACK source tree , and converts them into C using f2c . So when ex...
./doc/source/f2py/scalar.f./doc/source/f2py/string.f./doc/source/f2py/calculate.f./doc/source/f2py/moddata.f90./doc/source/f2py/array.f./doc/source/f2py/allocarr.f90./doc/source/f2py/extcallback.f./doc/source/f2py/common.f./doc/source/f2py/ftype.f./doc/source/f2py/fib3.f./doc/source/f2py/callback.f./doc/source/f2py/fib...
What is f2py used for while building numpy source ?
Python
For example , why does this work ? When innerfunc is called in func2 , how does it know the values of func1var ?
def func1 ( func1var ) : def innerfunc ( innerfuncvar ) : if func1var == 1 : print innerfuncvar else : print 5 func2 ( innerfunc ) def func2 ( function ) : function ( 9 )
In python , when you pass internally defined functions into other functions , how does it keep the variables ?
Python
See this example for a demonstration : Why ?
> > > class M : def __init__ ( self ) : self.x = 4 > > > sample = M ( ) > > > def test ( self ) : print ( self.x ) > > > sample.test = test > > > sample.test ( ) Traceback ( most recent call last ) : File `` < pyshell # 17 > '' , line 1 , in < module > sample.test ( ) TypeError : test ( ) missing 1 required positional ...
Why do n't monkey-patched methods get passed a reference to the instance ?
Python
Why is shallow-copying a list using a slice so much faster than using list builtin ? Usually when I see weird things like this , they 're fixed in python3 - but this discrepancy is still there :
In [ 1 ] : x = range ( 10 ) In [ 2 ] : timeit x_ = x [ : ] 10000000 loops , best of 3 : 83.2 ns per loopIn [ 3 ] : timeit x_ = list ( x ) 10000000 loops , best of 3 : 147 ns per loop In [ 1 ] : x = list ( range ( 10 ) ) In [ 2 ] : timeit x_ = x [ : ] 10000000 loops , best of 3 : 100 ns per loopIn [ 3 ] : timeit x_ = li...
Why is copying a list using a slice [ : ] faster than using the obvious way ?
Python
What is the rationale behind the advocated use of the for i in xrange ( ... ) -style looping constructs in Python ? For simple integer looping , the difference in overheads is substantial . I conducted a simple test using two pieces of code : File idiomatic.py : File cstyle.py : Profiling results were as follows : I ca...
# ! /usr/bin/env pythonM = 10000N = 10000if __name__ == `` __main__ '' : x , y = 0 , 0 for x in xrange ( N ) : for y in xrange ( M ) : pass # ! /usr/bin/env pythonM = 10000N = 10000if __name__ == `` __main__ '' : x , y = 0 , 0 while x < N : while y < M : y += 1 x += 1 bash-3.1 $ time python cstyle.pyreal 0m0.109suser 0...
Rationale behind Python 's preferred for syntax
Python
I have a string with Python code in it that I could evaluate as Python with literal_eval if it only had instances of OrderedDict replaced with { } .I am trying to use ast.parse and ast.NodeTransformer to do the replacement , but when I catch the node with nodetype == 'Name ' and node.id == 'OrderedDict ' , I ca n't fin...
from ast import NodeTransformer , parsepy_str = `` [ OrderedDict ( [ ( ' a ' , 1 ) ] ) ] '' class Transformer ( NodeTransformer ) : def generic_visit ( self , node ) : nodetype = type ( node ) .__name__ if nodetype == 'Name ' and node.id == 'OrderedDict ' : pass # ? ? ? return NodeTransformer.generic_visit ( self , nod...
How can I replace OrderedDict with dict in a Python AST before literal_eval ?
Python
From this question , I 'm now doing error handling one level down . That is , I call a function which calls another larger function , and I want where it failed in that larger function , not in the smaller function . Specific example . Code is : Output is : but line 8 is `` print workerFunc ( ) '' - I know that line fa...
import sys , osdef workerFunc ( ) : return 4/0def runTest ( ) : try : print workerFunc ( ) except : ty , val , tb = sys.exc_info ( ) print `` Error : % s , % s , % s '' % ( ty.__name__ , os.path.split ( tb.tb_frame.f_code.co_filename ) [ 1 ] , tb.tb_lineno ) runTest ( ) Error : ZeroDivisionError , tmp2.py,8 Error : Zer...
When I catch an exception , how do I get the type , file , and line number of the previous frame ?
Python
currently I am trying to understand the way machine learning algorithms work and one thing I do n't really get is the obvious difference between calculated accuracy of predicted labels and the visual confusion matrix . I will try to explain as clear as it is possible . Here is the snippet of the dataset ( here you can ...
f1 f2 f3 f4 f5 f6 label89.18 0.412 9.1 24.17 2.4 1 190.1 0.519 14.3 16.555 3.2 1 283.42 0.537 13.3 14.93 3.4 1 364.82 0.68 9.1 8.97 4.5 2 434.53 0.703 4.9 8.22 3.5 2 587.19 1.045 4.7 5.32 5.4 2 643.23 0.699 14.9 12.375 4.0 2 743.29 0.702 7.3 6.705 4.0 2 820.498 1.505 1.321 6.4785 3.8 2 9 model.fit ( X_train , y_train )...
Python - machine learning
Python
this line evaluates to True in pythonbecause False and 0 are equal after typecasting.Is there any way to avoid this typecasting ? Something like === operator for list ? ( I know that I can handle this case with a loop by explicitly checking for value types , but I am curious if there is some short and sweet trick to do...
False in [ 0,1,2 ]
False matching with 0 in a list python
Python
How can I use the textwrap module to split before a line reaches a certain amount of bytes ( without splitting a multi-bytes character ) ? I would like something like this :
> > > textwrap.wrap ( '☺ ☺☺ ☺☺ ☺ ☺ ☺☺ ☺☺ ' , bytewidth=10 ) ☺ ☺☺☺☺ ☺☺ ☺☺☺☺
Using textwrap.wrap with bytes count
Python
I need to manipulate some intervals of real numbers . Basically I 'll perform unions and intersections thereof . This way I always obtain sets of real numbers that are unions of a finite number of intervals.At the moment I 'm using sympy for python . My question is : given a sympy Set , is there a ( nice ) way to itera...
( -oo , 5 ] U [ 7 , 20 ]
sympy set : iterate over intervals
Python
Python is so flexible , that I can use functions as elements of lists or arguments of other functions . For example : or However , it is not clear to me how to do the same with random functions . For example I want to use Gaussian distributions : [ random.normalvariate ( 3.0 , 2.0 ) , random.normalvariate ( 1.0 , 4.0 )...
x = [ sin , cos ] y = s [ 0 ] ( 3.14 ) # It returns sin ( 3.14 ) def func ( f1 , f2 ) : return f1 ( 2.0 ) + f2 ( 3.0 )
How to pass a random function as an argument ?
Python
I wanted to implement a library I have written for python in C using the C-API of python . In python I can declare `` constants '' in my module by just stating : Those constants are then later returned by the functions offered by the module . I have some trouble doing the same thing in C. Here is what I got so far : I ...
RED = `` red '' # Not really a constant , I knowBLUE = `` blue '' # but suitable , neverthelessdef solve ( img_h ) : # Awesome computations return ( RED , BLUE ) [ some_flag ] PyMODINIT_FUNCPyInit_puzzler ( void ) { PyObject* module = PyModule_Create ( & Module ) ; ( void ) PyModule_AddStringConstant ( module , `` BLUE...
Python C-API access String constants
Python
I need to dynamically load several potentially unsafe modules for testing purpose.Regarding security , my script is executed by a low-access user.Although , I still need a way to elegantly make the import process timeout as I have no guarantee that the module script will terminate . By example , it could contain a call...
from threading import Threadimport importlib.utilclass ReturnThread ( Thread ) : def __init__ ( self , *args , **kwargs ) : super ( ) .__init__ ( *args , **kwargs ) self._return = None def run ( self ) : if self._target is not None : self._return = self._target ( *self._args , **self._kwargs ) def join ( self , *args ,...
How to dynamically import an unsafe Python module with a timeout ?
Python
I saw this for loop and I did n't quite understood why the last print is 2.Why it is n't 3 ? out :
a = [ 0 , 1 , 2 , 3 ] for a [ -1 ] in a : print ( a [ -1 ] ) 0122
Weird for loop statement
Python
Let 's say I have the following Pandas DataFrame : What I want is to calculate the number of non-overlapping runs of n consecutive non-zero values in each row , for various values of n. The desired output would be : where e.g . each value in the 2s column shows the number of non-overlapping runs of length 2 in that row...
id | a1 | a2 | a3 | a4 1 | 3 | 0 | 10 | 25 2 | 0 | 0 | 31 | 15 3 | 20 | 11 | 6 | 5 4 | 0 | 3 | 1 | 7 id | a1 | a2 | a3 | a4 | 2s | 3s | 4s1 | 3 | 0 | 10 | 25 | 1 | 0 | 02 | 0 | 0 | 31 | 15 | 1 | 0 | 03 | 20 | 11 | 6 | 5 | 2 | 1 | 14 | 0 | 3 | 1 | 7 | 1 | 1 | 0
Counting non-overlapping runs of non-zero values by row in a DataFrame
Python
I just wrote a bit of code where I wanted to do : where foo would return the first some_obj where some_obj.attr is zero or less . The alternative , I suppose , would bebut that feels very hacky.I ended up writing it out , but I do n't like how deeply nested it got.To clarify : container in this case is likely no more t...
def foo ( container ) return any ( ( some_obj.attr < = 0 for some_obj in container ) ) def foo ( container ) : return next ( ( some_obj for some_obj in container if some_obj.attr < = 0 ) , False ) def foo ( container ) : for some_obj in container : if some_obj.attr < = 0 : return some_obj return False
Alternative to ` any ` that returns the last evaluated object ?
Python
Im just beginning to mess around a bit with classes ; however , I am running across a problem.The previous script is returning < unbound method MyClass.f > instead of the intended value . How do I fix this ?
class MyClass ( object ) : def f ( self ) : return 'hello world'print MyClass.f
Python newbie having a problem using classes
Python
I 'm using Sphinx to generate documentation from code . Does anyone know if there is a way to control the formatting of floating point numbers generated from default arguments . For example if I have the following function : The generated documentation ends up looking like : Obviously this is a floating point precision...
def f ( x = 0.97 ) : return x+1 foo ( x = 0.96999999999997 )
Sphinx floating point formatting
Python
I am trying to implement a decorator class which would decorate methods in other classes . However , I need the class which holds the decorated method available in the decorator . I ca n't seem to find it anywhere.Here 's an example : That will print out this : In the decorator class the callable is of type function , ...
class my_decorator ( object ) : def __init__ ( self , arg1 , arg2 ) : print ( self.__class__.__name__ + `` .__init__ '' ) self.arg1 = arg1 self.arg2 = arg2 def __call__ ( self , my_callable ) : print ( self.__class__.__name__ + `` .__call__ '' ) print ( type ( my_callable ) ) self.my_callable = my_callable # self.my_ca...
How to find the containing class of a decorated method in Python
Python
My Conway 's game of life implementation in Python does n't seem to follow the rules correctly , and I ca n't figure out what could be wrong . When I put a final configuration into Golly , it continues past what mine did.I first identified the program by putting a configuration at which my program stopped into Golly , ...
# Function to find number of live neighborsdef neighbors ( row , column ) : adjacents = 0 # Horizontally adjacent if row > 0 : if board [ row-1 ] [ column ] : adjacents += 1 if column > 0 : if board [ row ] [ column-1 ] : adjacents += 1 if row < thesize-1 : if board [ row+1 ] [ column ] : adjacents += 1 if column < the...
Game of Life patterns carried out incorrectly
Python
I am using two architecture programs , with visual programming plugins ( Grasshopper for Rhino and Dynamo for Revit - for those that know / are interested ) Grasshopper contains a function called 'Jitter ' this will shuffle a list , however it has an input from 0.0 to 1.0 which controls the degree of shuffling - 0.0 re...
import mathimport randompercent = 30items = 42def remainder ( ) : remain = items % len ( list2 ) list3.append ( True ) remain -= 1 while remain > 0 : list3.append ( False ) remain -= 1 return list3 # find module of repeating True and False valueslist1 = ( [ True ] + [ False ] * int ( ( 100/percent ) -1 ) ) # multiply t...
varying degree of shuffling using random module python
Python
I have searched the web and stack overflow questions but been unable to find an answer to this question . The observation that I 've made is that in Python 2.7.3 , if you assign two variables the same single character string , e.g.Then the variables will share the same reference : This is also true for some longer stri...
> > > a = ' a ' > > > b = ' a ' > > > c = ' ' > > > d = ' ' > > > a is bTrue > > > c is dTrue > > > a = 'abc ' > > > b = 'abc ' > > > a is bTrue > > > ' ' is ' 'True > > > ' ' * 1 is ' ' * 1True > > > a = ' a c ' > > > b = ' a c ' > > > a is bFalse > > > c = ' ' > > > d = ' ' > > > c is dFalse > > > ' ' * 2 is ' ' * 2F...
Under which circumstances do equal strings share the same reference ?
Python
I 've used Wnck to check whether a window has been created like this : However , since dialogs do n't show up in the list of tasks , I ca n't find them that way . What is an appropriate way of checking whether they 're displayed ( and modal / not modal ) ?
screen = Wnck.Screen.get_default ( ) screen.force_update ( ) # recommended per Wnck documentation window_list = screen.get_windows ( ) for window in window_list : print ( window.get_name ( ) ) if window.has_name ( ) : if window.get_name ( ) == self.xld_main_window.get_title ( ) : window_found = True break assert window...
How to test if GTK+ dialog has been created ?
Python
I 'm trying to create my own anaconda package and after many attempts I 've finally managed to create a conda usable package out of my code . ( It depends on a package from haasad channel , so it should be installed like this : conda install -c monomonedula sten -c haasad ) .The problem appear when I 'm trying to insta...
Collecting package metadata ( current_repodata.json ) : doneSolving environment : failed with initial frozen solve . Retrying with flexible solve.Solving environment : failed with repodata from current_repodata.json , will retry with next repodata source.Collecting package metadata ( repodata.json ) : doneSolving envir...
UnsatisfiableError - Conda
Python
According to guido ( and to some other Python programmers ) , implicit string literal concatenation is considered harmful . Thus , I am trying to identifying logical lines containing such a concatenation.My first ( and only ) attempt was using shlex ; I thought of splitting a logical line with posix=False , so I 'll id...
shlex.split ( ' '' '' '' Some docstring `` '' '' ' , posix=False ) # Returns ' [ ' '' '' ' , ' '' Some docstring `` ' , ' '' '' ' ] ' , which is considered harmful , but it 's not
Identifying implicit string literal concatenation
Python
I have a dataset like this : I need to delete the first elements of each subview of the data as defined by the first column . So first I get all elements that have 0 in the first column , and delete the first row : [ 0,1 ] . Then I get the elements with 1 in the first column and delete the first row [ 1,5 ] , next step...
[ [ 0,1 ] , [ 0,2 ] , [ 0,3 ] , [ 0,4 ] , [ 1,5 ] , [ 1,6 ] , [ 1,7 ] , [ 2,8 ] , [ 2,9 ] ] [ [ 0,2 ] , [ 0,3 ] , [ 0,4 ] , [ 1,6 ] , [ 1,7 ] , [ 2,9 ] ]
delete the first element in subview of a matrix
Python
On Tiger , I used a custom python installation to evaluate newer versions and I did not have any problems with that* . Now Snow Leopard is a little more up-to-date and by default ships with What could be considered best practice ? Using the python shipped with Mac OS X or a custom compiled version in , say $ HOME . Are...
$ ls /System/Library/Frameworks/Python.framework/Versions/2.3 2.5 2.6 @ Current
On Mac OS X , do you use the shipped python or your own ?
Python
I have a SQL table which I can read in as a Pandas data frame , that has the following structure : It 's a representation of a matrix , for which all the values are 1 or 0 . The dense representation of this matrix would look like this : Normally , to do this conversion you can use pivot , but in my case with tens or hu...
user_id value1 1001 2002 1004 200 100 2001 1 12 1 04 0 1
How to efficiently create a SparseDataFrame from a long table ?
Python
I am working with https : //github.com/awslabs/chalice for using AWS Lambda , and I faced the following issue while installing using pip install chaliceThis is the error.Can anyone help me to resolve the issue ? Thanks in advance .
Exception : Traceback ( most recent call last ) : File “ /Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py ” , line 215 , in main status = self.run ( options , args ) File “ /Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py ” , line 342 , in run prefix=options.prefix_p...
Error while installing Chalice
Python
I 'm running Django 1.5.1 , Python 2.7.2 , and IPython 0.13.2 . If I do `` python ./manage.py shell '' from within my Django project directory , I get the following error : I know forms is defined as I can see it when it do `` dir ( forms ) '' . I 've noticed that this error only occurs when I 'm running iPython within...
from django import formsclass CommentForm ( forms.Form ) : name = forms.CharField ( ) NameError : name 'forms ' is not defined .
Getting NameError with Django 1.5 and IPython
Python
The details of the prerequisites of this code are quite long so I 'll try my best to summarize . WB/RG/BYColor is the base image , FIDO is an overlay of this base image which is applied to it . S_wb/rg/by are the final output images . WB/RG/BYColor are the same size as FIDO.For each unique element in FIDO , we want to ...
sX=200sY=200S_wb = np.zeros ( ( sX , sY ) ) S_rg = np.zeros ( ( sX , sY ) ) S_by = np.zeros ( ( sX , sY ) ) uniqueFIDOs , unique_counts = np.unique ( FIDO , return_counts=True ) numFIDOs = uniqueFIDOs.shape for i in np.arange ( 0 , numFIDOs [ 0 ] ) : Lookup = FIDO==uniqueFIDOs [ i ] # Get average of color signals for t...
Speeding-up `` for-loop '' in image analysis when iterations are up to 40,000
Python
How can we make a class represent itself as a slice when appropriate ? This did n't work : Expected output : Actual output : Inheriting from slice does n't work either .
class MyThing ( object ) : def __init__ ( self , start , stop , otherstuff ) : self.start = start self.stop = stop self.otherstuff = otherstuff def __index__ ( self ) : return slice ( self.start , self.stop ) > > > thing = MyThing ( 1 , 3 , 'potato ' ) > > > 'hello world ' [ thing ] 'el ' TypeError : __index__ returned...
Make an object that behaves like a slice
Python
I have a new relic agent configured like so : newrelic==2.56.0.42It 's logging the `` right '' things in staging , but it 's not sending . The agents send data from localhost and production.This is some configs from the newrelic.ini fileThis is my staging config in newrelic.iniOne log that I think is suspicious is this...
newrelic.agent.initialize ( newrelic_ini_file , newrelic_env ) logging.info ( 'NewRelic initialized with newrelic_env '+repr ( newrelic_env ) ) logging.info ( 'NewRelic config name is '+repr ( newrelic.agent.application ( ) .name ) ) NewRelic initialized with newrelic_env 'staging ' NewRelic config name is 'My Service ...
newrelic agent is not sending data to newrelic servers at staging only
Python
I know by using itertools , we can generate products , permutations and combinations . However , considering a case like : I am interested in generating the all different iterable set of ABC with len ( sequence ) =0 len ( sequence ) =1 OR len ( sequence ) =2 and len ( sequence ) =3 by having repetitions r. Its kinda of...
max_allowed_len ( sequence ) = 3 iterable= ABCrepeat= 3 ( or just ` range ( len ( 'ABC ' ) ` ) ' A '' B '' C ' 'AA '' BB '' CC '' AB '' AC ' , ... 'AAB '' ABA '' AAC '' ACA ' `
using python itertools to generate custom iteration
Python
I 'm learning Haskell after Python , and I thought that making a function that finds all the items in a sequence that are n't in another ( where both sequences have elements that can be compared ) would be an interesting exercise . I wrote some code for this in Python easily : ( where both seq and domain are sorted ) H...
def inverse ( seq , domain ) : ss = iter ( seq ) dd = iter ( domain ) while True : s = next ( ss ) while True : d = next ( dd ) if d ! = s : yield d if d > = s : break
Haskell equivalent of this Python code
Python
I seek a functionality in sympy that can provide descriptions to symbols when needed . This would be something along the lines of This would be useful because it would enable me to keep track of all my variables and know what physical quantities I am dealing with . Is something like this even remotely possible in sympy...
> > > x = symbols ( ' x ' ) > > > x.description.set ( 'Distance ( m ) ' ) > > > t = symbols ( 't ' ) > > > t.description.set ( 'Time ( s ) ' ) > > > x.description ( ) 'Distance ( m ) ' > > > t.description ( ) 'Time ( s ) ' > > > print ( rhow.__doc__ ) Assumptions : commutative = True You can override the default assump...
Possible to add descriptions to symbols in sympy ?
Python
To preface my question let me give a bit of context : I 'm currently working on a data pipeline that has a number of different steps . Each step can go wrong and many take some time ( not a huge amount , but on the order of minutes ) .For this reason the pipeline is currently heavily supervised by humans . An analyst g...
run a -- > ✅run b -- > ✅ ( b relies on some data produced by a ) run c -- > ❌ ( c relies on data produced by a and b ) // make some changes to crun c -- > ✅ ( c should run in an identical state to its original run )
Is there an easy way to have `` checkpoints '' in an extended python script ?
Python
I am trying to implement lazy partitioning of an iterator object that yields slices of the iterator when a function on an element of the iterator changes values . This would mimick the behavior of Clojure 's partition-by ( although the semantics of the output would be different , since Python would genuinely `` consume...
> > > unagi = [ -1 , 3 , 4 , 7 , -2 , 1 , -3 , -5 ] > > > parts = partitionby ( lambda x : x < 0 , unagi ) > > > print [ [ y for y in x ] for x in parts ] [ [ -1 ] , [ 3 , 4 , 7 ] , [ -2 ] , [ 1 ] , [ -3 , -5 ] ] from itertools import *def partitionby ( f , iterable ) : seq = iter ( iterable ) current = next ( seq ) ju...
Feeling stupid while trying to implement lazy partitioning in Python
Python
After reading this document about thread safety , I am left feeling that there is something missing in the documentation , or my reading of it , or my reasoning.Let 's give a simple example : I understood this code to construct a new instance of the HelloWorldNode class whenever the hello_world tag is used . Other exam...
class HelloWorldNode ( template.Node ) : def render ( self , context ) : return `` O HAI LOL '' @ register.tag ( name= '' hello_world '' ) def hello_world ( parser , tokens ) : `` '' '' Greets the world with wide-eyed awe. `` '' '' return HelloWorldNode ( ) class HelloWorldNode ( template.Node ) : def __init__ ( self ,...
Thread Safety with Template Tags
Python
I have a following simple code : As expected from my python knowledge , output is 3 - entire list will contain last value of i . But how this works internally ? AFAIK , python variables are simply reference to objects , so first closure must enclose object first i reference - and this object is definitely 1 , not 3 O_O...
def get ( ) : return [ lambda : i for i in [ 1 , 2 , 3 ] ] for f in get ( ) : print ( f ( ) )
Weird closure behavior in python
Python
I 'm developing a package called garlicsim . ( Website . ) The package is intended for Python 2.X , but I am also offerring Python 3 support on a different fork called garlicsim_py3 . ( 1 ) So both of these packages live side by side on PyPI , and Python 3 users install garlicsim_py3 , and Python 2 users install garlic...
try : import garlicsimexcept ImportError : import garlicsim_py3 as garlicsim
Having a Python package install itself under a different name
Python
Why is the following code true ? I understand what I wanted was len ( foo ) > 1 , but as a beginner this surprised me .
> > > foo = { } > > > foo > 1True > > > foo < 1False > > > foo == 0False > > > foo == -1False > > > foo == 1False
Why is an empty dictionary greater than 1 ?
Python
Simple use of Python 's str.format ( ) method : Hex , octal , and binary literals do not work : According to the replacement field grammar , though , they should : The integer grammar is as follows : Have I misunderstood the documentation , or does Python not behave as advertised ? ( I 'm using Python 2.7 . )
> > > ' { 0 } '.format ( 'zero ' ) 'zero ' > > > ' { 0x0 } '.format ( 'zero ' ) KeyError : '0x0 ' > > > ' { 0o0 } '.format ( 'zero ' ) KeyError : '0o0 ' > > > ' { 0b0 } '.format ( 'zero ' ) KeyError : '0b0 ' replacement_field : := `` { `` [ field_name ] [ `` ! '' conversion ] [ `` : '' format_spec ] `` } '' field_name ...
KeyError when using hex , octal , or binary integer as argument index with Python 's str.format ( ) method
Python
I have a dictionary in python with a pretty standard structure . I want to retrieve one value if present , and if not retrieve another value . If for some reason both values are missing I need to throw an error.Example of dicts : What is the best practice for this ? What could be an intuitive and easily readable way to...
# Data that has been modifieddata_a = { `` date_created '' : `` 2020-01-23T16:12:35+02:00 '' , `` date_modified '' : `` 2020-01-27T07:15:00+02:00 '' } # Data that has NOT been modifieddata_b = { `` date_created '' : `` 2020-01-23T16:12:35+02:00 '' , } mod_date_a = data_a.get ( 'date_modified ' , data_a.get ( 'date_crea...
Best practice for conditionally getting values from Python dictionary
Python
Non-positive number division is quite different in c++ and python programming langugages : So , as you can see , c++ is minimizing quotient.However , python behaves like that : I ca n't code my own division function behaving like c++ , because I 'll use it for checking c++ calculator programs , and python does not supp...
//c++:11 / 3 = 311 % 3 = 2 ( -11 ) / 3 = -3 ( -11 ) % 3 = -211 / ( -3 ) = -311 % ( -3 ) = 2 ( -11 ) / ( -3 ) = 3 ( -11 ) % ( -3 ) = -2 # python11 / 3 = 311 % 3 = 2 ( -11 ) / 3 = -4 ( -11 ) % 3 = 111 / ( -3 ) = -411 % ( -3 ) = -1 ( -11 ) / ( -3 ) = 3 ( -11 ) % ( -3 ) = -2
Changing python math module behaviour for non-positive numbers division
Python
I have a program using argparse . It takes 1 required positional argument , 1 optional positional argument , and 1 flag argument . Something like : So , I tried using this : Which works fine for test.py B C -a A and test.py -a A B C.But when I do test.py B -a A C , it throws an error : So , how can I get it to accept t...
usage : test.py [ -h ] [ -a A ] b [ c ] parser = argparse.ArgumentParser ( ) parser.add_argument ( '-a ' ) parser.add_argument ( ' b ' ) parser.add_argument ( ' c ' , nargs= ' ? ' , default=None ) print ( parser.parse_args ( ) ) $ python3 test.py B -a A Cusage : test.py [ -h ] [ -a A ] b [ c ] test.py : error : unrecog...
Allow positional command-line arguments with nargs to be seperated by a flag
Python
So I have this piece of code which is running on a discord bot which should repeat what the user says after a command . It does this but repeats it another 7 times after making 8 total runs through that script . Can anyone spot why this might be happening ? Note : The code that actually runs starts from the elif but I ...
@ Client.event async def on_message ( message ) : if message.content == `` s ! ping '' : userID = message.author.id Client.send_message ( message.channel , `` < @ % s > '' % ( userID ) ) elif message.content.startswith == `` s ! say '' : args = message.content.split ( `` `` ) Client.send_message ( message.channel , `` ...
Discord code is running multiple times for no reason
Python
I 've contributed stub file to ordered-set library . To include stub files I followed recommendations from MyPy and PEP-561 . But when I do python setup.py sdist I get distribution without ordered_set.pyi file : What I 'm doing wrong ? Also , where is the code , related to stub files inclusion , in the distutils librar...
$ tar -tvf dist/ordered-set-*.tar.gz -- wildcards '*pyi'tar : *pyi : Not found in archivetar : Exiting with failure status due to previous errors
Stub files are not included in the distribution despite py.typed marker included in the package
Python
I 've got the following tiny Python method that is by far the performance hotspot ( according to my profiler , > 95 % of execution time is spent here ) in a much larger program : The code is being run in the Jython implementation of Python , not CPython , if that matters . seq is a DNA sequence string , on the order of...
def topScore ( self , seq ) : ret = -1e9999 logProbs = self.logProbs # save indirection l = len ( logProbs ) for i in xrange ( len ( seq ) - l + 1 ) : score = 0.0 for j in xrange ( l ) : score += logProbs [ j ] [ seq [ j + i ] ] ret = max ( ret , score ) return ret
How to speed up this Python code ?
Python
I have a pandas dataframe as : I also have multiple number of lists with categories names , something as : - movies= [ 'spiderman ' , 'marvels ' , 'thriller ' ] 'sports= [ 'baseball ' , 'hockey ' , 'football ' ] , politics= [ 'election ' , 'china ' , 'usa ' ] and many others categories . All I want to match the keyword...
word_list [ 'nuclear ' , 'election ' , 'usa ' , 'baseball ' ] [ 'football ' , 'united ' , 'thriller ' ] [ 'marvels ' , 'hollywood ' , 'spiderman ' ] ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... word_list matched_list_names [ 'nuclear ' , 'election ' , 'usa ' , 'baseball ' ] politics ,...
Match keywords in pandas column with another list of elements
Python
Why does PHP return INF ( infinity ) for the following piece of code : The expected result was 4321 , but PHP returned INF , float type : I wrote the same code in Python and C # and got the expected output - 4321PythonC #
< ? php $ n = 1234 ; $ m = 0 ; while ( $ n > 0 ) { $ m = ( $ m * 10 ) + ( $ n % 10 ) ; $ n = $ n / 10 ; } var_dump ( $ m ) ; ? > float INF n = 1234m = 0while ( n > 0 ) : m = ( m * 10 ) + ( n % 10 ) n = n / 10print m static void Main ( string [ ] args ) { int n = 1234 ; int m = 0 ; while ( n > 0 ) { m = ( m * 10 ) + ( n...
Unexpected behavior in PHP - Same code gives correct results in C # and Python
Python
I wrote a solution for this competitive programming problem . It passed all the test cases , except it was off by one for the last case , and I ca n't figure out why . The problem can be stated like this : given how many pennies each person in a group has , how much money has to change hands so that everyone in the gro...
def transfer ( A ) : A.sort ( key = lambda x : -x ) extra = sum ( A ) % len ( A ) average = sum ( A ) // len ( A ) high = sum ( [ abs ( x - ( average+1 ) ) for x in A [ : extra ] ] ) low = sum ( [ abs ( x - average ) for x in A [ extra : ] ] ) return ( high+low ) /2 print ( transfer ( [ 613 , 944 , 7845 , 8908 , 12312 ...
Impossible-to-find bug in a program that equalizes wealth in a group ( UVA 10137 , `` The Trip '' )
Python
I do n't need the laziness of itertools.groupby . I just want to group my list into a dict of lists as such : Is there a standard function that already does this ?
dict ( [ ( a , list ( b ) ) for a , b in itertools.groupby ( mylist , mykeyfunc ) ] )
Does python have a non-lazy version of itertools.groupby ?
Python
In the course of implementing the `` Variable Elimination '' algorithm for a Bayes ' Nets program , I encountered an unexpected bug that was the result of an iterative map transformation of a sequence of objects.For simplicity 's sake , I 'll use an analogous piece of code here : This is definitely the wrong result . S...
> > > nums = [ 1 , 2 , 3 ] > > > for x in [ 4 , 5 , 6 ] : ... # Uses n if x is odd , uses ( n + 10 ) if x is even ... nums = map ( ... lambda n : n if x % 2 else n + 10 , ... nums ) ... > > > list ( nums ) [ 31 , 32 , 33 ] > > > nums = [ 1 , 2 , 3 ] > > > for x in [ 4 , 5 , 6 ] : ... # Uses n if x is odd , uses ( n + 1...
map vs list ; why different behaviour ?
Python
Problem : Imagine you start at the corner of an X by Y grid . You can only move in two directions : right and down . How many possible paths are there for you to go from ( 0 , 0 ) to ( X , Y ) I have two approaches for this , first is to use a recursive algorithm enhanced by memoization , and the second one is to use b...
def gridMovingCount ( x , y , cache ) : if x == 0 or y == 0 : return 1 elif str ( x ) + '' : '' +str ( y ) in cache : return cache [ str ( x ) + '' : '' +str ( y ) ] else : cache [ str ( x ) + '' : '' +str ( y ) ] = gridMovingCount ( x-1 , y , cache ) + gridMovingCount ( x , y-1 , cache ) return cache [ str ( x ) + '' ...
Python : Recursive call counting ways of walking grid yield incorrect answer when grid size is too large
Python
Could somebody please explain the following code to me.It prints 42 , I expected 0.I meant to create two instances of OuterTest , which would contain a distinct instance of InnerTest each . Instead I got two instances of OuterTest which reference the same instance of InnerTest . Also what would be a correct way to impl...
class InnerTest : def __init__ ( self , value = 0 ) : self.value = valueclass OuterTest : def __init__ ( self , inner_test = InnerTest ( ) ) : self.inner_test = inner_testa = OuterTest ( ) b = OuterTest ( ) a.inner_test.value = 42print b.inner_test.value
How to create distinct instances of a class in Python ?
Python
CaveatThis is NOT a duplicate of this . I 'm not interested in finding out my memory consumption or the matter , as I 'm already doing that below . The question is WHY the memory consumption is like this.Also , even if I did need a way to profile my memory do note that guppy ( the suggested Python memory profiler in th...
Partition of a set of 45968 objects . Total size = 5579934 bytes . Index Count % Size % Cumulative % Kind ( class / dict of class ) 0 13378 29 1225991 22 1225991 22 str 1 11483 25 843360 15 2069351 37 tuple 2 2974 6 429896 8 2499247 45 types.CodeType import osimport psutilimport timewith open ( 'errors.log ' ) as file_...
Why does reading a whole file take up more RAM than its size on DISK ?
Python
With that code I receiveAny thoughts ?
# ! /usr/bin/env pythonimport osimport statimport sysclass chkup : def set ( file ) : filepermission = os.stat ( file ) user_read ( ) user_write ( ) user_exec ( ) def user_read ( ) : `` '' '' Return True if 'file ' is readable by user `` '' '' # Extract the permissions bits from the file 's ( or # directory 's ) stat i...
Why does my Python class claim that I have 2 arguments instead of 1 ?
Python
I have code that depends on elapsed time ( for instance : If 10 minutes has passed ) What is the best way to simulate this in pytest ? Monkey patching methods in module time ? Example code ( the tested code - a bit schematic but conveys the message ) :
current_time = datetime.datetime.utcnow ( ) retry_time = current_time + datetime.timedelta ( minutes=10 ) # time_in_db represents time extracted from DBif time_in_db > retry_time : # perform the retry
advance time artificially in pytest
Python
What is the `` most pythonic '' way to build a dictionary where I have the values in a sequence and each key will be a function of its value ? I 'm currently using the following , but I feel like I 'm just missing a cleaner way . NOTE : values is a list that is not related to any dictionary .
for value in values : new_dict [ key_from_value ( value ) ] = value
Is there a more pythonic way to build this dictionary ?
Python
Say I want to use black as an API , and do something like : Formatting code by calling the black binary with Popen is an alternative , but that 's not what I 'm asking .
import blackblack.format ( `` some python code '' )
Is it possible to call Black as an API ?
Python
I 'm attempting to learn Racket , and in the process am attempting to rewrite a Python filter . I have the following pair of functions in my code : From what I can tell the implementation of the first function in Racket would be something along the following lines : Which appears to work correctly . Working on the impl...
def dlv ( text ) : `` '' '' Returns True if the given text corresponds to the output of DLV and False otherwise. `` '' '' return text.startswith ( `` DLV '' ) or \ text.startswith ( `` { `` ) or \ text.startswith ( `` Best model '' ) def answer_sets ( text ) : `` '' '' Returns a list comprised of all of the answer sets...
Migrating from Python to Racket ( regular expression libraries and the `` Racket Way '' )
Python
I understand how I can provide an informal representation of an instance of the object , but I am interested in providing an informal string representation of the Class name.So specifically , I want to override what is returned when I print the Class ( __main__.SomeClass ) .
> > > class SomeClass : ... def __str__ ( self ) : ... return ' I am a SomeClass instance. ' ... > > > SomeClass < class __main__.SomeClass at 0x2ba2f0fd3b30 > > > > print SomeClass__main__.SomeClass > > > > > > x = SomeClass ( ) > > > x < __main__.SomeClass instance at 0x2ba2f0ff3f38 > > > > print xI am a SomeClass in...
How do I provide an informal string representation of a python Class ( not instance )
Python
I have set up a very simple multi-layer perceptron with a single hidden layer using a sigmoid transfer function , and mock data with 2 inputs.I have tried to set up using the Simple Feedforward Neural Network using TensorFlow example on Github . I wo n't post the whole thing here but my cost function is set up like thi...
# Backward propagationloss = tensorflow.losses.mean_squared_error ( labels=y , predictions=yhat ) cost = tensorflow.reduce_mean ( loss , name='cost ' ) updates = tensorflow.train.GradientDescentOptimizer ( 0.01 ) .minimize ( cost ) with tensorflow.Session ( ) as sess : init = tensorflow.global_variables_initializer ( )...
Loss decreases but weights do n't appear to change during tensorflow gradient descent
Python
I am trying to put some numbers into numpy arraywhere did 1 go ?
> > > np.array ( [ 20000001 ] ) .astype ( 'float32 ' ) array ( [ 20000000 . ] , dtype=float32 )
Why numpy converts 20000001 int to float32 as 20000000. ?
Python
I have two arrays of N floats ( which act as ( x , y ) coordinates and might have duplicates ) and and associated z array of N floats ( which act as weights for the coordinates ) .For each ( x , y ) pair of floats I need to select the pair with the smallest associated z value . I 've defined a selectMinz ( ) function w...
import numpy as npimport timedef getData ( ) : N = 100000 x = np.arange ( 0.0005 , 0.03 , 0.001 ) y = np.arange ( 6. , 10. , .05 ) # Select N values for x , y , where values can be repeated x = np.random.choice ( x , N ) y = np.random.choice ( y , N ) z = np.random.uniform ( 10. , 15. , N ) return x , y , zdef selectMi...
Efficiently get minimum values for each pair of elements from two arrays in a third array
Python
s1 and s2 are sets ( Python set or C++ std : :set ) To add the elements of s2 to s1 ( set union ) , you can doTo remove the elements of s2 from s1 ( set difference ) , you can doWhat is the C++ equivalent of this ? The codedoes not work , for s1.erase ( ) requires iterators from s1.The codeworks , but seems overly comp...
Python : s1.update ( s2 ) C++ : s1.insert ( s2.begin ( ) , s2.end ( ) ) ; Python : s1.difference_update ( s2 ) s1.erase ( s2.begin ( ) , s2.end ( ) ) ; std : :set < T > s3 ; std : :set_difference ( s1.begin ( ) , s1.end ( ) , s2.begin ( ) , s2.end ( ) , std : :inserter ( s3 , s3.end ( ) ) ; s1.swap ( s3 ) ;
C++ equivalent of Python difference_update ?
Python
According to PEP 8 : Imports should be grouped in the following order : standard library importsrelated third party importslocal application/library specific importsYou should put a blank line between each group of imports.But it does not mention about __future__ imports . Should __future__ imports be grouped together ...
from __future__ import absolute_importimport sysimport os.pathfrom .submod import xyz from __future__ import absolute_importimport sysimport os.pathfrom .submod import xyz
PEP 8 : How should __future__ imports be grouped ?
Python
According to the docs you can ignore warnings like this : which gives : But there does n't seem to be any documentation on this mini-language ( is it even a minilanguage ? ) How is the match done ? I 'm asking this because the following test does n't ignore the DeprecationWarning raised by importing boto3 : Pytest outp...
@ pytest.mark.filterwarnings ( `` ignore : api v1 '' ) def test_foo ( ) : @ pytest.mark.filterwarnings ( `` ignore : DeprecationWarning '' ) def test_ignore_warnings ( ) : import boto3 ============================================================================================================================== warnings...
How does @ pytest.mark.filterwarnings work ?
Python
Suppose I have two series of timestamps which are pairs of start/end times for various 5 hour ranges . They are not necessarily sequential , nor are they quantized to the hour.Now suppose that we have some data that is timestamped by minute , over a range that encompasses all start/end pairs . We wish to obtain the val...
import pandas as pdstart = pd.Series ( pd.date_range ( '20190412 ' , freq= ' H ' , periods=25 ) ) # Drop a few indexes to make the series not sequentialstart.drop ( [ 4,5,10,14 ] ) .reset_index ( drop=True , inplace=True ) # Add some random minutes to the start as it 's not necessarily quantizedstart = start + pd.to_ti...
How to vectorize a loop through pandas series when values are used in slice of another series
Python
I need to map some data points onto a map . I downloaded the basemap module for python to do this . I get the following error message each time I attempt to even make a map . The code I use for this is below . How can I fix this ? The version of geos I am using is 3.4.2 , the version of basemap I am using is 1.0.7 . Th...
Assertion failed : ( 0 ) , function query , file AbstractSTRtree.cpp , line 285.aborted from mpl_toolkits.basemap import Basemapimport numpy as npimport matplotlib.pyplot as plotdef main ( ) : map = Basemap ( projection = 'cyl ' , llcrnrlon= -100 , llcrnrlat = -18 , urcrnrlon =-80 , urcrnrlat = 31 ) map.drawcoastlines ...
Basemap causes python to abort
Python
I 've got what I think is a somewhat interesting problem , even just from a programming exercise point of view.I have a long list of binary patterns that I want to reduce into a more compact form to present to users . The notation to be followed is that a '- ' can represent either a ' 1 ' or a ' 0 ' , so [ '1011 ' , '1...
[ '1100 ' , '1000 ' , '0100 ' , '0000 ' , '1111 ' , '1011 ' , '0111 ' , '0011 ' ] def reducePatterns ( patterns ) : `` 'Reduce patterns into compact dash notation '' ' newPatterns = [ ] # reduced patterns matched = [ ] # indexes with a string that was already matched for x , p1 in enumerate ( patterns ) : # pattern1 if...
Reducing binary patterns in Python
Python
I haveat the very top of my template file . I get the error : What 's the correct way to do this ?
< % ! from __future__ import division % > SyntaxError : from __future__ imports must occur at the beginning of the file
Using from __future__ import in Mako template
Python
I have a large ( 106x106 ) correlation matrix in pandas with the following structure : Truncated here for simplicity.If I calculate the linkage , and later plot the dendrogram using the following code : It yields a dendrogram like : My question is surrounding the y-axis . On all examples I have seen , the Y axis is bou...
+ -- -+ -- -- -- -- -- -- -- -- -- -+ -- -- -- -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -+ -- -- -- -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -- -+| | 0 | 1 | 2 | 3 | 4 |...
Dendrogram y-axis labeling confusion