text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : I have a Django app which I want to be able to use in multiple instances . One model ( Listing ) can have a variable number of fields ( for the different instances ) but will then always have exactly those extra fields for the instance . I want these extra fields added through admin so I 've created models lik...
Display an unknown number of fields in Django template with field content of another record as the label
Python : How to get full row of data for groupby relsult ? How the get the full row ? I tried filtering but df [ df.e == df.groupby ( ' a ' ) [ ' b ' ] .max ( ) ] but size is different : ( Original data : Groupby ( [ 1,7 ] ) [ 14 ] .max ( ) gives me the result but in grouped series as 1 and 7 as index I wanted the corr...
Groupby returning full row for max occurs
Python : I 'm trying to add a few interactive things the to Django admin page via a simple RESTful api and Javascript . Should be simple , but I 'm facing a weird issue where every single one of my requests from javascript is returning a 403 authorization error . Note that this only applies to js . I can hit the url fr...
Django Rest framework replacing my currently authenticated user with AnonymousUser whenever I call it via ajax ?
Python : I am trying to filter data from a dataframe which are less than a certain value . If there is no NaN then its working fine . But when there is a nan then it is ignoring the NaN value . I want to include all the time its does n't matter its less than or bigger than the comparing value . In the above result 5,6,...
Value filter in pandas dataframe keeping NaN
Python : Suppose we have a string a = `` 01000111000011 '' with n=5 `` 1 '' s. The ith `` 1 '' , I would like to replace with the ith character in `` ORANGE '' .My result should look like : What could be the finest way to solve this problem in Python ? Is it possible to bind an index to each substitution ? Many thanks ...
Python : Replace ith occurence of x with ith element in list
Python : I 'm trying to wrap a little handy piece of C++ code that is intended to generate video+audio on windows using VFW , the C++ library lives here and the descriptions says : Uses Video for Windows ( so it 's not portable ) . Handy if you want to quickly record a video somewhere and do n't feel like wading throug...
Bug writing audio using custom video writer library
Python : I have a django 1.5 running on Google App Engine using the djangoappengine module for the stitching.Everything works fine , except that about a half of the calls to /_ah/queue/deferred raise the following import error : As you can see , the djangoappengine module sits inside the third_party directory , and thi...
/_ah/queue/deferred strange import error
Python : I expected the terminate ( ) method to kill the two processes : Running the code gives : I was expecting : <code> import multiprocessingimport timedef foo ( ) : while True : time.sleep ( 1 ) def bar ( ) : while True : time.sleep ( 1 ) if __name__ == '__main__ ' : while True : p_foo = multiprocessing.Process ( ...
Why are the children failing to die ?
Python : I am trying to accept tuple and list as object types in an __add__ method in Python . Please see the following code : The error I get when running it in the Python interpreter is : I simply can not figure our why this is n't working . This is homework for a college course and I have very little experience with...
Implementing Tuples and Lists in the isinstance Function in Python 2.7
Python : this is my code : mypy throw error : Argument 1 of `` __eq__ '' incompatible with supertype `` object '' . But if I remove __eq__ method , mypy wo n't complain it though compare is same as __eq__ , what should I do ? <code> class Person : def __init__ ( self , id ) : self.id = id def __eq__ ( self , other : 'P...
mypy : `` __eq__ '' incompatible with supertype `` object ''
Python : I 'm writing a Python parser to learn Flex and Bison , and I 'm trying to find out why only the first of these programs is valid Python.a.py : produces no error.b.py : produces this error : and c.py : produces this error : I 'm using Python 2.6.5 ( r265:79063 , Apr 16 2010 , 13:09:56 ) [ GCC 4.4.3 ] on linux2 ...
Why do indented explicit line continuations not allow comments in Python ?
Python : Using this small reproducible example , I 've so far been unable to generate a new integer array from 3 arrays that contains unique groupings across all three input arrays . The arrays are related to topographic properties : The idea is that the geographic contours are broken into 3 different properties using ...
Intersect multiple 2D np arrays for determining zones
Python : Situation ( Note : The following situation is just exemplary . This question applys to anything that can evaluate to bool ) A default list should be used if the user does not provide a custom list : You can shorten this to : Now , as per https : //docs.python.org/2.7/reference/expressions.html # or ... The exp...
Is 'or ' used on the right-hand-side of an assignment pythonic ?
Python : I have dataframe like this : i 'm trying to aggregate it like this : and it works but i also need to add grouped logins to row , to make row like this : I tried something like lambda x : x.ait [ 0 , 1 ] but it doesnt work <code> x = pd.DataFrame ( { 'audio ' : [ 'audio1 ' , 'audio1 ' , 'audio2 ' , 'audio2 ' , ...
Pandas group by result to columns
Python : I have to take a string containing placeholders for later substitution , like : And turn that into : I came up with : That works , but it feels super clunky , and not at all `` idiomatic '' python . How would a well , idiomatic python solution look like ? Updates for clarification : the resulting strings are n...
How to turn % s into { 0 } , { 1 } ... less clunky ?
Python : I undertook an interview last week in which I learnt a few things about python I did n't know about ( or rather realise how they could be used ) , first up and the content of this question is the use of or for the purposes of branch control . So , for example , if we run : Then if f ( ) evaluates to some true ...
Use of OR as branch control in FP
Python : I have one dataframe df , with two columns : Script ( with text ) and SpeakerAnd I have the following list : L = [ ' a ' , ' b ' , ' c ' ] With the following code , I obtain this dataframe df2 : Which line can I add in my code to obtain , for each line of my dataframe df2 , a percentage value of all lines spok...
Calculate percentage of similar values in pandas dataframe
Python : I 've updated django from 1.6 to 1.8.3 . I create test models in test setUp method in unit tests , something like thatAnd I have code in the application , which relies on the primary key == 1 . I 've noted , that sequences are n't actually reseted . In each next test the pk is greater , that in previous . This...
Django reset_sequences does n't work in LiveServerTestCase
Python : I have a boolean matrix with 1.5E6 rows and 20E3 columns , similar to this example : Also , I have another matrix N ( 1.5E6 rows , 1 column ) : What I need to do , is to go through each column pair from matrix M ( 1 & 1 , 1 & 2 , 1 & 3 , 1 & N , 2 & 1 , 2 & 2 etc ) combined by the AND operator , and count how ...
Fastest way for boolean matrix computations
Python : How could I split a string by comma which contains commas itself in Python ? Let 's say the string is : How do I make sure I only get four elements after splitting ? <code> object = `` '' '' { `` alert '' , `` Sorry , you are not allowed to do that now , try later '' , `` success '' , `` Welcome , user '' } ''...
Regex for splitting a string which contains commas
Python : a simple example : run with error when do current_process in __del__ : if I change a variable name : it get the right result : and I tried many variable name , some ok , some error.Why different instance name , will cause multiprocessing module be None in __del__ ? <code> # ! /usr/bin/env python # -*- coding :...
Python strange multiprocessing with variable name
Python : I would like to know if there is a way of writing the below module code without having to add another indentation level the whole module code.I am looking for something like this : Note , I do not want to throw an Exception , the import should pass normally . <code> # module codeif not condition : # rest of th...
Is it possible to end a python module import with something like a return ?
Python : Many iterator `` functions '' in the __builtin__ module are actually implemented as types , even although the documentation talks about them as being `` functions '' . Take for instance enumerate . The documentation says that it is equivalent to : Which is exactly as I would have implemented it , of course . H...
Why are some python builtin `` functions '' actually types ?
Python : I have written a python code for a newton method in 1D and want to use it to calculate the newton fractal for the function The basic python code I am using is this : My newton ( ) -function returns the number of iterations it needed to find an approximation xk such that |f ( xk ) | < 1e-10.I tested this code w...
newton fractal : mathoverflow error
Python : Disclaimer : completely new to Python from a PHP backgroundOk I 'm using Python on Google App Engine with Google 's webapp framework.I have a function which I import as it contains things which need to be processed on each page.This works fine when I call it , but how can I make sure the app is killed off afte...
How can I kill off a Python web app on GAE early following a redirect ?
Python : I was playing around with metaclasses in CPython 3.2.2 , and I noticed it is possible to end up with a class that is its own type : For our metaclass A , there does n't really seem to be much of a distinction between class and instance attributes : All this works the same ( apart from changing to __metaclass__...
Python - an object can be its own type ?
Python : Is there a good way to find stretches of Trues in a numpy boolean array ? If I have an array like : Can I get an array of indices like : or any other appropriate way to store this information . I know this can be done with some complicated while loops , but I 'm looking for a better way . <code> x = numpy.arra...
find stretches of Trues in numpy array
Python : I 've made this list ; each item is a string that contains commas ( in some cases ) and colon ( always ) : I would like to create a new list from the one above as follows : But I 'd like to know if/ how it 's possible to do so in a line or two of efficient code employing primarily Python 's higher order functi...
Using Python Higher Order Functions to Manipulate Lists
Python : I am trying to syllabify devanagari wordsधर्मक्षेत्रे - > धर् मक् षेत् रेdharmakeshetre - > dhar mak shet reI get the result as : Which is partially correctI try another word कुरुक्षेत्र - > कु रुक् षेत् रेkurukshetre - > ku ruk she treThe result is obviously wrong.How do I extract the syllables effectively ? ...
Syllabification of Devanagari
Python : Not sure how to title this question . I 've run into a few situations where I have a list of data , maybe annotated with some property , and I want to collect them into groups . For example , maybe I have a file like this : and I want to group each set of readings , splitting them on a condition ( in this case...
How to collect data from a list into groups based on condition ?
Python : Minimal exampleI tried referencing the class namespace as well but that is n't working eitherAnd of course , this works as expectedI want to understand why this scope issue is happening then , if I am trying to do something insane understand the best way to do it otherwise . My feeling was that the first code ...
Python scoping issue with dictionary comprehension inside class level code
Python : In python , I one had to swap values of 2 variables , all you need to do wasOne can look at it as if the two statements- ( x=y ) and ( y=x ) are executed in parallel and not one after another.Is there any way to achieve the same effect in c++ ? NOTE/EDIT : I am looking to extend this 'parallel effect ' ( if it...
Running statements in 'parallel '
Python : I have the following f-string I want to print out on the condition the variable is available : Which results in : So normally I 'd use a type specifier for float precision like this : Which would result in : But that messes with the if-statement in this case . Either it fails because : The if statement becomes...
How to apply float precision ( type specifier ) in a conditional f-string ?
Python : I have an expression like thiswhich is entered into Sympy like this ( for the sake of a reproducible example in this question ) Eyeballing this expression , the first order Taylor approximation for any of the variables , e.g . k1 , around some nonzero value should be nonzero , but this codejust returns 0 . Thi...
Why does my Sympy code calculate the first order Taylor series approximation incorrectly ?
Python : I 'm working with a mapping from values of a python dictionary into a numpy array like this : This offers the values referenced through the dict to reflect any changes made in the full array . I need the size of the groups within the dict to be flexible . However when a group is only a single element , such as...
Numpy - retaining the pointer when referencing a single element
Python : I am trying to learn python and I landed on the with..asconstruct , that used like this : So as a learning strategy I tried to do the following : and I got this output : My question is then : why did print ( derived ) return a None object and not a Derived object ? <code> with open ( `` somefile.txt '' , 'rt '...
Trying to figure out how the 'with..as ' construct works in python
Python : I have a ID terminatorand a .txt sample file to parseI generated Java and Python2 target and test each against sample file respectively . Java target can parse this file . But Python2 target ca n't . It throws token recognition error at : ' 均 ' . And I tested Python2 target against other valid inputs , all wor...
antlr4 python target can not recognize unicode
Python : i am trying to implement my own version of a DailyLogFile but it looks like i miss a fundamental of Python subclassing process ... as i get this error : so i need to explicitly add and define others methods like Write and rotate method like this : while i thought it would be correctly inherit from the base mot...
Python : why a method from super class not seen ?
Python : I have a list of dicts and would like to design a function to output a new dict which contains the sum for each unique key across all the dicts in the list.For the list : So far so good , this can be done with a counter : Which correctly returns : The trouble comes when the dicts in my list start to contain ne...
Python sum list of dicts by key with nested dicts
Python : Assume we have the following simplified data : I want to enumerate columns with the same prefix . In this case the prefixes are Data , Text . So expected output would be : Note the enumerated columns.Attempted solution # 1 : Attempted solution # 2 : Question : Is there an easier solution to do this , I also lo...
Enumerate columns with same prefix
Python : I am working on old text files with 2-digit years where the default century logic in dateutil.parser does n't seem to work well . For example , the attack on Pearl Harbor was not on dparser.parse ( `` 12/7/41 '' ) ( which returns 2041-12-7 ) . The buit-in century `` threshold '' to roll back into the 1900 's s...
customize dateutil.parser century inference logic
Python : I was messing around while trying to figure out shallow and deep copying in Python , and noticed that while the identities of a copied set , list , or seemingly any mutable type are n't the same : For immutable types this is n't the case - it looks like a copy points to the same address in memory . This sort o...
I think immutable types like frozenset and tuple not actually copied . What is this called ? Does it have any implications ?
Python : In python3 , when I try to execute the following lines : Why does python throw that in my opinion highly misleading TypeError : format ( ) argument after * must be a sequence , not map for this builtin function ? It makes it even more confusing to see that an explicit raise for other Exceptions is caught an pa...
Sometimes , map is a sequence , sometimes not ?
Python : I am trying to reproduce the algorithm explained here in Python but I am facing some problems with a strange growth of some parameters.The following is my attempt . Observe that get_ang ( ) and get_acc ( ) return angular velocity and acceleration along [ x , y , z ] -axis in degrees/s ( but I convert this data...
Error state Kalman Filter from MATLAB to Python
Python : A reoccurring pattern in my Python programming on GAE is getting some entity from the data store , then possibly changing that entity based on various conditions . In the end I need to .put ( ) the entity back to the data store to ensure that any changes that might have been made to it get saved . However ofte...
Elegant way to avoid .put ( ) on unchanged entities
Python : I 'm OCRing some text from two different sources . They can each make mistakes in different places , where they wo n't recognize a letter/group of letters . If they do n't recognize something , it 's replaced with a ? . For example , if the word is Roflcopter , one source might return Ro ? copter , while anoth...
elegant way to match two wildcarded strings
Python : Here is the code I am usingWhich is giving me the following error : I am hoping to 1 ) understand why this is happening , and 2 ) find a solution that allows me to pickle the object ( without removing the memoization ) . Ideally the solution would not change the call to pickle . Running python 3.6 with funcy==...
Cant Pickle memoized class instance
Python : I am going through the examples mentioned here , and am looking at this example . I ran a sample example below on ipython , and the result is consistent , i.e. , `` % d '' is slower than `` % s '' : Both the code blocks are similar , and even the output of disassembler is same , so why is `` % s '' faster than...
Why is % s faster than % d for integer substitution in python ?
Python : I see no difference in sub classing the models.manager object and overriding the get_query_set method or simply creating a new method in the sub class and using the method . For the reason being I have taken example from the django book ; With this I could use ; Person.women.all ( ) or Person.men.all ( ) to fe...
subclassing models.Manager
Python : Is there an existing Emacs function that adds the symbol currently under the point to __all__ when editing Python code ? E.g. , say the cursor was on the first o in foo : If you did M-x python-add-to-all ( or whatever ) it would add 'foo ' to __all__.I did n't see one when I googled around , but , as always , ...
Emacs function to add symbol to __all__ in Python mode ?
Python : I tried my attempt at finding the smallest number that is divisible by numbers from 1 to n , and now I 'm looking for advice on ways to further compact/make my solution more efficient . It would be pretty cool if there was an O ( 1 ) solution too . <code> def get_smallest_number ( n ) : `` '' '' returns the sm...
Fastest and most compact way to get the smallest number that is divisible by numbers from 1 to n
Python : Given a path , e.g . I wish to remove the e.This is what I did : Any more elegant way to do it ? <code> file_path = ' a.b.c.d.e ' class_path = ( '. ' ) .join ( file_path.split ( ' . ' ) [ 0 : -1 ] )
Remove a part of a path separated with dots
Python : Here is my model : Essentially , what I want is is for other_model to be unique in this table . That means that if there is a record where other_model_one id is 123 , I should not allow another record to be created with other_model_two id as 123 . I can override clean I guess but I was wondering if django has ...
Is there a way to create a unique id over 2 fields ?
Python : I 'm trying to achieve the behavior above . Read further if you care why or if the example is n't sufficient enough . Sorry for the sharp tongue , but most of my Stack Exchange questions get hostile questions back instead of answers.This question arises from requiring an admin to run my script , but the nature...
Can my Python script distinguish between if it was run as root or if it was run through sudo ?
Python : The Python documentation about the is operator says : The operators is and is not test for object identity : x is y is true if and only if x and y are the same object . x is not y yields the inverse truth value.Let 's try that : The Python documentation also says : Due to automatic garbage-collection , free li...
Why is a method not identical to itself ?
Python : I have a dataset that looks something like this : That is then being computed into this to create a kmeans cluster.What I want to do is to make those clusters relate to both time periods and keys.With the time periods -7 am to 10 am , and 4 pm to 6 pm , and 12 pm to 2 pm , with 6 pm to 12 am , 12 am to 7 am , ...
How to group a dataframe by 4 time periods and key
Python : As I am sure you are well aware , python , as do most programming languages , comes with built-in exceptions . I have gone through the list , and can not deduce which would be appropriate . Of course I can make my own exception , but this is a fairly standard error that would be excepted.This is an error based...
Python which built in exception to use
Python : If a = 15 and 152 is represented as a2 while 215 is represented as 2a then a number x has to be found such that8x = 8*x8I tried this naive Python codebut it is taking a huge amount of time to produce a correct result.How to optimize the code ? <code> > > > i = 0 > > > while ( i < =100000000000000000 ) : ... if...
Efficiently solving a letter/number problem in Python
Python : I 've looked at several other SO questions ( and google 'd tons ) that are 'similar'-ish to this , but none of them seem to fit my question right.I am trying to make a non fixed length , unique text string , only containing characters in a string I specify . E.g . made up of capital and lower case a-zA-Z chara...
python unique string creation
Python : I 'd like to know if its possible to use the * operator in a oneline if to achieve the following functionality : I thought I could just saybut it turns out this is the same as saying which does n't make any sense for *None . I tired enclosing the first option in parenthesis but this just throws SyntaxError : c...
Proper use of the * operator in a oneline if statement python
Python : I am using jupyter-cadquery to visualize some 3D models made with CadQuery.When visualizing the models on a Jupyter notebook , everything works as expected.But when trying to embed the widget in an HTML document , it seems the camera , on load , is pointing to ( 0 , 0 , 0 ) , not as expected . Once you interac...
Embed widgets with jupyter-cadquery ( threejs ) : wrong position on load
Python : I only have OOP programming experience in Java and have just started working on a project in Python and I 'm starting to realize Python makes me skeptical about a few things that are intuitive to me . So I have a few questions about OOP in Python.Scenario : I 'm writing a program that will send emails . For an...
Python OOP from a Java programmer 's perspective
Python : I would like to have python logging output to be in form of tree corresponding to logger tree . Just look at example.Lets say we have a code : The output should be something like : I could write formatters for each of the log by hand , but it does n't solve the problem of inserting something like o < -- '' a.b...
Format log messages as a tree
Python : Here 's a simple class created declaratively : And here 's a similar class , but it was defined by invoking the metaclass manually : I 'm interested to know whether they are indistinguishable . Is it possible to detect such a difference from the class object itself ? <code> class Person : def say_hello ( self ...
Detect if class was defined declarative or functional - possible ?
Python : Given the example below , which is more pythonic ? Using function composition , lambdas , or ( now for ) something completely different ? I have to say that the lambdas seem to be more readable , but Guido himself seems to want to remove lambdas altogether - http : //www.artima.com/weblogs/viewpost.jsp ? threa...
What is more pythonic - function composition , lambdas , or something else ?
Python : In KDE 5 ( Kubuntu 15.04 / Plasma 5.2 ) disabled Qt-Buttons ( Qt4 ) are indistinguishable from non-disabled buttons . This problem does not exist in KDE 4.14 as the following screen-shot shows : The program source for this dialog is written in Python with PyQt4 : How can I make disabled Buttons in KDE 5 recogn...
Disabled Qt-Buttons are not shown as disabled in Plasma 5.2 ( KDE 5 )
Python : I 'm trying to optimise an exponential objective function with GEKKO , but I do n't know if the selected solver is the best one for these kind of problems . Is the selected one a valid choice ? ? <code> import numpy as np'GEKKO MODELING'from gekko import GEKKOm = GEKKO ( ) m.options.SOLVER=1 # APOPT is an MINL...
What solver should I use if my objective function is an nonlinear ( also exponential explanation ) function ? Python GEKKO
Python : I want to compare all CSV files kept on my local machine to files kept on a server . The folder structure is the same for both of them . I only want to do a data comparison and not metadata ( like time of creation , etc ) . I am using filecmp but it seems to perform metadata comparison . Is there a way to do w...
Compare CSV files content with filecmp and ignore metadata
Python : I 've been subclassing tuple or using namedtuple blissfully for a few years , but now I have a use case where I need a class that can be used as a weak referent . And today I learned tuples do n't support weak references . Is there another way to create an immutable object in Python with a fixed set of attribu...
immutable objects in Python that can have weak references
Python : I was solving problem 26 on Project Euler where I need to calculate the length of the recurring part of 1/n where n is all integers between 1 and 1000 , and see which number makes the longest recurring part . That meant that I needed my division done a lot more precisely . So I was playing around with my decim...
Why does increasing precision make this program faster ?
Python : I stumbled upon this line of code in SciPy 's source , in the stats module : Is this return something other than 1.0 ? In other words , is there any value of x such that x == x holds False ? <code> return 1.0* ( x==x )
Is x==x ever False in Python ?
Python : I 'm getting the following error on the second refresh of a page : DetachedInstanceError : Instance is not bound to a Session ; attribute refresh operation can not proceedThe issue seems to be some sharing of cached data between requests . The thing is that it 's only supposed to be cached locally ( i.e . re-q...
Python ( Pyramid framework ) is persisting data between requests and I ca n't figure out why
Python : I have a list of characters and list of indexesand I 'd like to get this in one operationI could do this but is there is a way to do it faster ? <code> myList = [ ' a ' , ' b ' , ' c ' , 'd ' ] toRemove = [ 0,2 ] myList = [ ' b ' , 'd ' ] toRemove.reverse ( ) for i in toRemove : myList.pop ( i )
Concise way to remove elements from list by index in Python
Python : Problem statementI 'm looking for an efficient way to generate full binary cartesian products ( tables with all combinations of True and False with a certain number of columns ) , filtered by certain exclusive conditions . For example , for three columns/bits n=3 wewould get the full tableThis is supposed to b...
Generate filtered binary cartesian products
Python : Hi I am working on implementing a multi-classification model ( 5 classes ) with the new SpaCy Model en_pytt_bertbaseuncased_lg . The code for the new pipe is here : The code for the training is as follows and is based on the example from here ( https : //pypi.org/project/spacy-pytorch-transformers/ ) : So the ...
Model ( ) got multiple values for argument 'nr_class ' - SpaCy multi-classification model ( BERT integration )
Python : I have the following code copied from github gtfs_SQL_importer : I tried to run this on windows and replaced the call to the UNIX-command cat by the windows equivalent type which should work similar as of is-there-replacement-for-cat-on-windows.However when I execute that code I get some error : the syntax for...
how to pipe multiple sql- and py-scripts
Python : I have been using a wrapper for a c++-class for exporting functions to python for a while on linux . Now I wanted to make this available to my coworkers using windows . However , I fail to create a usable boost_python dll for this in cygwin . The problem arises when trying to link a dependent module in another...
Linking c++-class for boost_python in cygwin
Python : I have a pointAnd a pandas dataframeI would like to calculate the distance of every row in the pandas dataframe , to that specific pointI triedMy solution is really slow though ( taking into account that I want to calculate the distance from other points as well.Is there a way to do my calculations more effici...
How to calculate distance for every row in a pandas dataframe from a single point efficiently ?
Python : Produces instances smaller than those of a `` normal '' class . Why is this ? Source : David Beazley 's recent tweet . <code> class Spam ( object ) : __slots__ = ( '__dict__ ' , )
Why does __slots__ = ( '__dict__ ' , ) produce smaller instances ?
Python : In octave , all the numerical output subsequent to the command format bit will show the native bit representation of numbers as stored in the memory . For example , Is there an equivalent command in python to show all the numbers in their native-bit representation ( so the output is as shown below ) ? ( This i...
Is there a python equivalent of the octave command ` format bit ` ?
Python : Do Python 's stylistic best practices apply to scientific coding ? I am finding it difficult to keep scientific Python code readable.For example , it is suggested to use meaningful names for variables and to keep the namespace ordered by avoiding import * . Thus , e.g . : But these suggestions can lead to some...
Readability of Scientific Python Code ( Line Continuations , Variable Names , Imports )
Python : I thought int in python is represented by 4 bytes , why is it reporting 12 bytes Please someone explain why is it reporting 12 bytes when int uses just 4 bytes <code> > > > sys.getsizeof ( int ) 436 # ? does this mean int occupies 436 bytes . > > > sys.getsizeof ( 1 ) 12 # 12 bytes for int object , is this the...
How can i determine the exact size of a type used by python
Python : I have an Excel ( .xlsx ) file that has two columns of phrases . For example : I want to import it in Python and to get a list of tuples like : What could I do ? <code> John I have a dog Mike I need a catNick I go to school [ ( 'John ' , ' I have a dog ' ) , ( 'Mike ' , ' I need a cat ' ) , ( 'Nick ' , ' I go ...
From Excel to list of tuples
Python : I have a csv file that has 25000 rows . I want to put the average of every 30 rows in another csv file.I 've given an example with 9 rows as below and the new csv file has 3 rows ( 3 , 1 , 2 ) : What I did : This works well but can this code be better ? <code> | H | ========| 1 | -- -\| 3 | | -- - > | 3 || 5 |...
Calculate average of every n rows from a csv file
Python : Here is the code I tried : I have tried modifying the neural network and double-cheking the data.Is there anything I can do to improve the outcome ? Is the model not deep enough ? Is there any alternative models suited for my data ? Does this mean these features have no predictive value ? I 'm kind of confused...
keras accuracy does n't improve more than 59 percent
Python : How can I `` steal '' or copy a method from one class onto another class ? Example code : Expected output : Instead : TypeError : unbound method foo ( ) must be called with A instance as first argument ( got nothing instead ) <code> class A ( object ) : def foo ( self ) : print `` blah '' class B ( object ) : ...
python method stealer
Python : Is there a comprehensive reference list of the generic setup import step names ? The names of generic setup import steps do n't always match the names of their corresponding xml files for example 'types.xml ' has an import step called 'typeinfo'.In the absence of a list , I would be satisfied with a simple app...
Is there a good reference list for the names of the genericsetup import steps
Python : Warning , this is a bit recursive ; ) I answered this question : Python : How can i get all the elements in a list before the longest element ? And after I submitted there where another answer that should be faster ( the author thought , and so did I ) . I tried to time the different solutions but the solution...
Timing functions
Python : I 've got a performance bottleneck . I 'm computing the column-wise mean of large arrays ( 250 rows & 1.3 million columns ) , and I do so more than a million times in my application . My test case in Python : Numpy takes around 400 milliseconds on my machine , running on a single core . I 've tried several oth...
High performance array mean
Python : I 've used Python for many years but only gradually studied the more obscure features of the language , as most of my code is for data processing . Generators based on yield are part of my routine toolkit , and recently I read about coroutines . I found an example similar to this : which prints the average of ...
Converting from generator-based to native coroutines
Python : My UploadForm class : HTML Templatehosts.py to run the check for validationUsing VS 's debugging tools , I find that form.validate_on_submit ( ) does n't work and always fails validation and I get this error on my html page . { 'roomImage ' : [ 'File was empty ! ' ] } There is another MultipleFileField control...
FileRequiredValidator ( ) does n't work when using MultipleFileField ( ) in my form
Python : I 'm trying to split a list of strings into a list of tuples of uneven length containing these strings , with each tuple containing strings initially separated with blank strings . Basically I 'd need the parameterized split that I could apply to lists . If my initial list looks like : The last element of this...
Splitting a list into uneven tuples
Python : So I looked at a bunch of posts on Pyspark , Jupyter and setting memory/cores/executors ( and the associated memory ) .But I appear to be stuck -Question 1 : I dont see my machine utilizing either the cores or the memory . Why ? Can I do some adjustments to the excutors/cores/memory to optimize speed of readin...
PySpark : Setting Executors/Cores and Memory Local Machine
Python : I wanted to check if a given x lies in the interval [ 0 , a-1 ] .As a lazy coder I wrote and ( because that piece of code was in 4.5 nested loops ) quickly run into performance issues . I tested it and indeed , it turns out runtime of n in range ( n ) lies in O ( n ) , give or take . I actually thought my code...
` in range ` construction in python 2 -- - working too slow
Python : I am using pytest with pycharm , but when I run the test , I get the test and results garbled within the pycharm console , here is an example output : This is rather not pretty , and the result are printed after the test functions report . This is how it should look like when I run pytest from the terminal : I...
pytest output results are garbled within pycharm
Python : Loading an OpenFOAM case in ParaView using python is straight forward with : However , by default only the internalMesh mesh region is selected in the reader object.Using the trace method of ParaView is not of any help , since the MeshRegion property of the OpenFOAMReader object is simply set to the values of ...
How to select all mesh regions in ParaView OpenFOAM case using python scripting ?
Python : problem is very simple : I have two 2d np.array and I want to get a third array that only contains the rows that are not in common with the latter twos.for example : I tried np.delete ( X , Y , axis=0 ) but it does n't work ... <code> X = np.array ( [ [ 0,1 ] , [ 1,2 ] , [ 4,5 ] , [ 5,6 ] , [ 8,9 ] , [ 9,10 ] ...
Numpy : how delete rows common to 2 matrices
Python : While answering this question I had a doubt regarding how to reduce multiple spaces in a string to one in Python without using regex . Say the string is as follows : The first solution that came to my mind was But this will not conserve leading and trailing spaces if the string was something likeIn order to co...
Without regex reduce multiple spaces in a string to one in Python
Python : I am trying to perform some simple mathematical operations on the files.The columns in below file_1.csv are dynamic in nature the number of columns will increased from time to time . So we can not have fixed last_column master_ids.csv : Before any pre-processingmaster_count.csv : Before any processingmaster_Id...
Pandas Column mathematical operations No error no answer
Python : So , I was trying to make a basic Tic-Tac-Toe game with python , And I created one which works perfectly fine , but my code is not so good , as it has a lot of code for checking the list indexes ( Winner Of The Game ) , which kinda bothers me . So , How I avoid using the left index for checking the winner of t...
How to avoid multiple ` elif ` statements ?