text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : This following is a snippet of Python code I found that solves a mathematical problem . What exactly is it doing ? I was n't too sure what to Google for.Is this a special Python syntax ? <code> x , y = x + 3 * y , 4 * x + 1 * y
What is this piece of Python code doing ?
Python : I know in languages such as C , C++ , Java and C # , ( C # example ) the else if statement is syntactic sugar , in that it 's really just a one else statement followed by an if statement . is equal to However , in python , there is a special elif statement . I 've been wondering if this is just shorthand for d...
Is the python `` elif '' compiled differently from else : if ?
Python : Consider the next example : I 'm using cp1251 encoding within the idle , but it seems like the interpreter actually uses latin1 to create unicode string : Why so ? Is there spec for such behavior ? CPython , 2.7.EditThe code I was actually looking for isSeems like when encoding unicode with latin1 codec , all ...
Encoding used for u '' '' literals
Python : I have a strange behaviour with pybind11 when I want to use C++ polymorphism in Python . Here is a simple example of my problem : The output of this script is [ MyBase , MyDerived ] MyBase MyBasebut the expected output is [ MyBase , MyDerived ] MyBase MyDerivedbecause mylist return a std : :vector which contai...
Polymorphism and pybind11
Python : I 'm having issues with reverting a Django ( 1.8.7 ) migration that contains the renaming of a table . Even though it seems to be able to rename it in Postgres , it then tries to add a constraint using the old table name.Here 's the traceback : If you take a look at the SQL it generates , You can see that ther...
Error when reverting an auto-generated migration for renaming a table in Django
Python : Converting a loop into a comprehension is simple enough : toBut I 'm not sure how to proceed when the loop involves assigning a value to a reference.And the comprehension ends up looking like this : This calculates word.split ( ' l ' ) multiple times whereas the loop only calculates it once and saves a referen...
Converting a loop with an assignment into a comprehension
Python : I 'm trying to calculate the weighted topological overlap for an adjacency matrix but I can not figure out how to do it correctly using numpy . The R function that does the correct implementation is from WGCNA ( https : //www.rdocumentation.org/packages/WGCNA/versions/1.67/topics/TOMsimilarity ) . The formula ...
How to compute the Topological Overlap Measure [ TOM ] for a weighted adjacency matrix in Python ?
Python : PIP always downloads and installs a package when a specific SVN revision is specified ( slowing the syncing process considerably ) . Is there a way around this ? Normally pip detects that the package is already installed in the environment and prompts to use -- upgrade.My pip_requirements file has the followin...
PIP always reinstalls package when using specific SVN revision
Python : While I was messing around with Python , Although I understand that 'conjugate ' , 'imag ' , and 'real ' are there for the sake of compatibility with complex type , I ca n't understand why 'numerator ' and 'denominator ' exists for int only , and does n't for a float . Any explanation for that ? <code> > > > [...
Why float objects in Python does n't have denominator attribute , while int does ?
Python : I have a c++ vector with std : :pair < unsigned long , unsigned long > objects . I am trying to generate permutations of the objects of the vector using std : :next_permutation ( ) . However , I want the permutations to be of a given size , you know , similar to the permutations function in python where the si...
How to create a permutation in c++ using STL for number of places lower than the total length
Python : I 've got an iterator with some objects in it and I wanted to create a collection of uniqueUsers in which I only list every user once . So playing around a bit I tried it with both a list and a dict : So I tested it by converting the dict to a list when doing the if statement , and that works as I would expect...
` object in list ` behaves different from ` object in dict ` ?
Python : I have been playing around with SQLAlchemy and found out that I can not track reliably what is being changed within database.I have created an example that explains what my concern is : In short - there are two objects : ParentChild - linked to ParentEach time I add new instance of Child and link it with insta...
Make parent object not appearing within session.dirty of before_flush event listener
Python : I wrote a line of code using lambda to close a list of file objects in python2.6 : It works , but does n't in python3.1 . Why ? Here is my test code : <code> map ( lambda f : f.close ( ) , files ) import sysfiles = [ sys.stdin , sys.stderr ] for f in files : print ( f.closed ) # False in 2.6 & 3.1map ( lambda ...
Could n't close file in functional way in python3.1 ?
Python : Python2.7 output format not getting as expected if body of email read from a file . user_info.txt is a file generated by another job which contains all the details of users . The output format of user_info.txt is nice . Where as sending that file as an email , output format changes completely . does am I doing...
stdout format changing when sending a file using smtplib - python2.7
Python : how should I define a function , where , which can tell where it was executed , with no arguments passed in ? all files in ~/app/a.py : b.py : c.py : <code> def where ( ) : return 'the file name where the function was executed ' from a import whereif __name__ == '__main__ ' : print where ( ) # I want where ( )...
Determine where a function was executed ?
Python : I have a dataset with an id column , date column and value . I would like to count the consecutive appearances/duplicate values of id for a continuous date range.My question is very much like Count consecutive duplicate values by group but in Python.Moreover , the question is different from How to find duplica...
Counting Consecutive Duplicates For By Group
Python : Just soliciting opinion on whether the following is reasonable or if there is a better approach . Basically I want a decorator that will apply to a function or a class that implements __call__.You could just have a regular decorator and decorate the __call__ explicitly but then the decorator is tucked inside t...
python decorator for class OR function
Python : Following is the __init__ method of the Local class from the werkzeug library : I do n't understand two things about this code : Why did they writeinstead of simplyWhy did they even use __setattr__ if the could simply write <code> def __init__ ( self ) : object.__setattr__ ( self , '__storage__ ' , { } ) objec...
` object.__setattr__ ( self , ... , ... ) ` instead of ` setattr ( self , ... , ... ) ` ?
Python : I though this question would solve my problem , and I followed the Simple HTTP Server example but I 'm getting different issues that I ca n't find a solution for.I want to generate an Excel file in my server and return it to the user with an Http response . I 'm using xlsxwriter to build the file and a pyramid...
Decoding problems when returning xlsxwriter response with pyramid
Python : I 'm wondering how to match the labels produced by a SVN classifier with the ones on my dataset . ANd then I realized that the problem starts at the begining : when I load the dataset I got a dataset which in my case has the following properties : But I , m wondering if the order og the target_names is differe...
Labels of datasets imported with sklearn.datasets.load_files
Python : Trying to convert super ( B , self ) .method ( ) into a simple nice bubble ( ) call.Did it , see below ! Is it possible to get reference to class B in this example ? Basically , C is child of B , B is child of A . Then we create c of type C. Then the call to c.test ( ) actually calls B.test ( ) ( via inheritan...
super ( ) in Python 2.x without args
Python : Original problem descriptionThe problem arises when I implement some machine learning algorithm with numpy . I want some new class ludmo which works the same as numpy.ndarray , but with a few more properties . For example , with a new property ludmo.foo . I 've tried several methods below , but none is satisfa...
Python : How to extend a huge class with minimum lines of code ?
Python : I 'm thinking to do some bytecode manipulation ( think genetic programming ) in Python.I came across a test case in crashers test section of Python source tree that states : Broken bytecode objects can easily crash the interpreter . This is not going to be fixed.Thus the question , how to validate given tweake...
How to validate Python bytecode ?
Python : I have an image array that has an X times Y shape of 2048x2088 . The x-axis has two 20 pixel regions , one at the start and one at the end , which are used to calibrate the main image area . To access these regions I can slice the array like so : My question is how to define these areas in a configuration file...
Using a string to define Numpy array slice
Python : I am currently working on a jupyter notebook in kaggle . After performing the desired transformations on my numpy array , I pickled it so that it can be stored on disk . The reason I did that is so that I can free up the memory being consumed by the large array . The memory consumed after pickling the array wa...
Jupyter Notebook Memory Management
Python : I ran into a very surprising relative import behavior today ( unfortantely after nearly 4 hours of pulling my hair out ) .I have always been under the impression that if you have `` Class A '' inside of a module name `` module_a.py '' within a package named `` package '' that you could equivalently use either ...
Unexpected relative import behavior in Python
Python : I have a list my_list ( the list contains utf8 strings ) : For some reason , a sorted list ( my_sorted_list = sorted ( my_list ) ) uses more memory : Why is sorted returning a list that takes more space in memory than the initial unsorted list ? <code> > > > len ( my_list ) 8777 > > > getsizeof ( my_list ) # <...
Why is a sorted list bigger than an unsorted list
Python : I 'm currently developing some things in Python and I have a question about variables scope.This is the code : If I remove the first line ( a = None ) the code still works as before . However in this case I 'd be declaring the variable inside an `` if '' block , and regarding other languages like Java , that v...
Correctness about variable scope
Python : If I have list1 as shown above , the index of the last value is 3 , but is there a way that if I say list1 [ 4 ] , it would become list1 [ 0 ] ? <code> list1 = [ 1,2,3,4 ]
Is there a way to cycle through indexes
Python : I 'm making a wxpython app that I will compile with the various freezing utility out there to create an executable for multiple platforms.the program will be a map editer for a tile-based game enginein this app I want to provide a scripting system so that advanced users can modify the behavior of the program s...
Python - Creating a `` scripting '' system
Python : I 'm fairly new to programming in general . I need to develop a program that can copy multiple directories at once and also take into account multiple file type exceptions . I came across the shutil module which offers the copytree and ignore_patterns functions . Here is a snippet of my code which also uses th...
Is there a way to interrupt shutil copytree operation in Python ?
Python : Let 's say I have an async generator like this : I consume it like this : It works just fine , however when the connection is disconnected and there is no new event published the async for will just wait forever , so ideally I would like to close the generator forcefully like this : But I get the following err...
How to forcefully close an async generator ?
Python : I ’ m new at making COM servers and working with COM from Python so I want to clarify a few things I could not find explicit answers for : Creating GUID ’ s Properly for COM serversDo I generate : The GUID for my intended COM server manually , copy it and use that # for the server from then on in ? Therefore ,...
When do I generate new GUID 's for COM Servers ? ( Examples in Python )
Python : In NumPy , why does hstack ( ) copy the data from the arrays being stacked : gives for C : whereas hsplit ( ) creates a view on the data : gives for b : I mean - what is the reasoning behind the implementation of this behaviour ( which I find inconsistent and hard to remember ) : I accept that this happens bec...
Why does hstack ( ) copy data but hsplit ( ) create a view on it ?
Python : I have installed and tried both wxpython-3.0 and wxpython-2.8 for python2.7 from the standard cygwin repos ( 64-bit , Win 7 ) . However when I start the Cygwin X server and try to run the most simple `` Hello World '' script from wxPython tutorials : I get a Gtk-WARNING ** : Screen for GtkWindow not set which ...
Running wxpython app in cygwin/X
Python : I have the following code : But if I make a subclass of int , and reimplement __cmp__ : Why are these two different ? Is the python runtime catching the TypeError thrown by int.__cmp__ ( ) , and interpreting that as a False value ? Can someone point me to the bit in the 2.x cpython source that shows how this i...
Does python coerce types when doing operator overloading ?
Python : Python documentation says : and it gives an example > > > Point = namedtuple ( 'Point ' , ... In all the examples I could find , the return from namedtuple and argument typename are spelled the same . Experimenting , it seems the argument does not matter : What is the distinction ? How does the typename argume...
What is the difference between namedtuple return and its typename argument ?
Python : I 'm fairly new in 'recursive functions ' . So , I 'm trying to wrap my head around why we use recursive functions and how recursive functions work and I think I 've a fairly good understanding about it.Two days ago , I was trying to solve the shortest path problem . I 've a following graph ( it 's in python )...
How recursive functions work inside a 'for loop '
Python : I am using matplotlib ( version 1.4 ) to create images that I need saved in .tiff format . I am plotting in the IPython notebook ( version 3.2 ) with the % matplotlib inline backend . Normally I use the Anaconda distribution and am able to save matplotlib figures to .tiff with no problem . However , I am tryin...
What other libraries does matplotlib need installed to write tiff files ?
Python : I have a simple DataFrame : I can then split the tuples column into two very simply , e.g.This approach also works : However if my DataFrame is slightly more complex , e.g.then the first approach throws `` Columns must be same length as key '' ( of course ) because some rows have two values and some have none ...
Can I split this column containing a mix of tuples/None more efficiently ?
Python : Will the results of numpy.lib.stride_tricks.as_strided depend on the dtype of the NumPy array ? This question arises from the definition of .strides , which is Tuple of bytes to step in each dimension when traversing an array.Take the following function that I 've used in other questions here . It takes a 1d o...
Will results of numpy.as_strided depend on input dtype ?
Python : I would like to be able to index elements of a power set without expanding the full set into memory ( a la itertools ) Furthermore I want the index to be cardinality ordered . So index 0 should be the empty set , index 2**n - 1 should be all elementsMost literature I have found so far involves generating a pow...
Index into size ordered power set
Python : Python 2.7 : Python 3.5 : How can I get a valid answer ? For me `` .txt '' would fit.Even the filetype lib ca n't handle this : - ( See https : //github.com/h2non/filetype.py/issues/30 <code> > > > from mimetypes import guess_extension > > > guess_extension ( 'text/plain ' ) '.ksh ' > > > from mimetypes import...
content-type text/plain has file extension .ksh ?
Python : I have a lot of data that I 'd like to structure in a Pandas dataframe . However , I need a multi-index format for this . The Pandas MultiIndex feature has always confused me and also this time I ca n't get my head around it.I built the structure as I want it as a dict , but because my actual data is much larg...
Convert dict constructor to Pandas MultiIndex dataframe
Python : This is my python code which prints the sql query.When printing the Mysql query my Django project shows following error in the terminal : Mysql doumentation does not say much about it.What does this mean and how to can i rectify it . <code> def generate_insert_statement ( column_names , values_format , table_n...
Mysql 'VALUES function ' is deprecated
Python : I have three DB models ( from Django ) that can be used as the input for building a recommendation system : Users List - with userId , username , email etcMovies List - with movieId , movieTitle , Topics etcSaves List - with userId , movieId and timestamp ( the current recommendation system will be a little bi...
Recommendation system with matrix factorization for huge data gives MemoryError
Python : The documentation on the uuid module says : UUID.variant ¶ The UUID variant , which determines the internal layout of the UUID . This will be one of the integer constants RESERVED_NCS , RFC_4122 , RESERVED_MICROSOFT , or RESERVED_FUTURE.And later : uuid.RESERVED_NCS ¶ Reserved for NCS compatibility . uuid.RFC_...
When would a UUID variant be an integer ?
Python : I 'm working with Keras and I 'm trying to rewrite categorical_crossentropy by using the Keras abstract backend , but I 'm stuck . This is my custom function , I want just the weighted sum of crossentropy : In my program I generate a label_pred with to model.predict ( ) .Finally I do : I get the following erro...
Keras crossentropy
Python : I have a field in the model , and the data entered is , the django model 's max_length is set to 2000 while the entered data is only of length 3 , Does the max_length reserves space for 2000 characters in the database table per object ? after the model object is saved , does the space is freed up ? Do setting ...
do setting the max_length to a very large value consume extra space ?
Python : This returns only result [ 89 ] and I need to return the whole 89 % . Any ideas how to do it please ? <code> re.findall ( `` ( 100| [ 0-9 ] [ 0-9 ] | [ 0-9 ] ) % '' , `` 89 % '' )
Python - re.findall returns unwanted result
Python : I 'm having a bit of trouble understanding why some variables are local and some are global . E.g . when I try this : I get this error : Now , it totally makes sense to me why it 's throwing me an error on score . I did n't set it globally ( I commented that part out intentionally to show this ) . And I am spe...
Why some Python variables stay global , while some require definition as global
Python : This code returns a list [ 0,0,0 ] to [ 9,9,9 ] , which produces no repeats and each element is in order from smallest to largest.Looking for a shorter and better way to write this code without using multiple variables ( position1 , position2 , position3 ) , instead only using one variable i.Here is my attempt...
Number list with no repeats and ordered
Python : I 'm trying to handle a file , and I need to remove extraneous information in the file ; notably , I 'm trying to remove brackets [ ] including text inside and between bracket [ ] [ ] blocks , Saying that everything between these blocks including them itself but print everything outside it . Below is my text F...
Python remove Square brackets and extraneous information between them
Python : First I 'll lay out what I 'm trying to achieve in case there 's a different way to go about it ! I want to be able to edit both sides of an M2M relationship ( preferably on the admin page although if needs be it could be on a normal page ) using any of the multi select interfaces.The problem obviously comes w...
Editing both sides of M2M in Admin Page
Python : I have a square 2D numpy array , A , and an array of zeros , B , with the same shape.For every index ( i , j ) in A , other than the first and last rows and columns , I want to assign to B [ i , j ] the value of np.sum ( A [ i - 1 : i + 2 , j - 1 : j + 2 ] .Example : Is there an efficient way to do this ? Or s...
2d numpy array , making each value the sum of the 3x3 square it is centered at
Python : I 'm trying to create a dictionary in OCaml that maps a string to a list of strings . I 've referenced this tutorial for a basic string to string map , but I need some help making a list.Here is what I want to do in Python : Thanks in advance <code> > > > food = { } > > > food [ `` fruit '' ] = ( `` blueberry ...
OCaml map a string to a list of strings
Python : I am aware of the nature of floating point math but I still find the following surprising : From the documentation I could not find anything that would explain that . It does state : ... In addition , any string that represents a finite value and is accepted by the float constructor is also accepted by the Fra...
fractions.Fraction ( ) returns different nom. , denom . pair when parsing a float or its string representation
Python : I 'm trying to create in Altair a Vega-Lite specification of a plot of a time series whose time range spans a few days . Since in my case , it will be clear which day is which , I want to reduce noise in my axis labels by letting labels be of the form ' % H : % M ' , even if this causes labels to be non-distin...
Hours and minutes as labels in Altair plot spanning more than one day
Python : how can a delete a specific entry from a bibtex file based on a cite key using python ? I basically want a function that takes two arguments ( path to bibtex file and cite key ) and deletes the entry that corresponds to the key from the file . I played around with regular expressions but was n't successful . I...
deleting a specific entry from a bibtex file based on cite key using Python
Python : I 'm querying the Windows Desktop Search JET ( ESE ) database using Python + ADO . It works but after ~7600 records I get an exception when advancing to the next record using MoveNext . I know it is not at EOF because I can run the same query in VBScript and get way more records with the same query.Exception t...
How to use win32com to handle overflow when querying Desktop Search ?
Python : tl ; dr : How do I predict the shape returned by numpy broadcasting across several arrays without having to actually add the arrays ? I have a lot of scripts that make use of numpy ( Python ) broadcasting rules so that essentially 1D inputs result in a multiple-dimension output . For a basic example , the idea...
Numpy function to get shape of added arrays
Python : I have a template in which I placed , let 's say 5 forms , but all disabled to be posted except for the first one . The next form can only be filled if I click a button that enables it first.I 'm looking for a way to implement a Django-like forloop.last templatetag variable in a for loop inside an acceptance t...
Is there a pythonic way of knowing when the first and last loop in a for is being passed through ?
Python : We trained this model for classify 5 image classes . We used 500 images for each class for train the model and 200 images for each class to validate the model . We used keras in tensorflow backend.It uses data that can be downloaded at : https : //www.kaggle.com/alxmamaev/flowers-recognitionIn our setup , we :...
Image Classification with TensorFlow and Keras
Python : I have two dataframes I would like to merge.DF1 has this formDF2 is another set of data , which shares a condensed version of the indexI would like to populate DF1 with the data from DF2What is the most efficient way to do this ? <code> index c1 c2a1 1 2a1 2 1a1 3 1b1 5 2b1 4 7 index c3 c4a1 9 10b1 7 8 index c...
Expand and merge Pandas dataframes
Python : I am a bit puzzled by the python ( 2.7 ) list.remove function . In the documentation of remove it says : `` Remove the first item from the list whose value is x . It is an error if there is no such item . `` So , I guess here value means that comparison is based on equality ( i.e . == ) and not identity ( i.e ...
Removal of an item from a python list , how are items compared ( e.g . numpy arrays ) ?
Python : I transformed the following functionto a batched versionThis function handles quaternion1 and quaternion0 with shape ( ? ,4 ) . Now I want that the function can handle an arbitrary number of dimensions , such as ( ? , ? ,4 ) . How to do this ? <code> def quaternion_multiply ( quaternion0 , quaternion1 ) : `` '...
Numpy : make batched version of quaternion multiplication
Python : Playing around with id ( ) . Began with looking at the addresses of identical attributes in non-identical objects . But that does n't matter now , I guess . Down to the code : First test ( in interactive console ) : No surprise here , actually . n.__class__ is different than t.__class__ so it seems obvious the...
Python memory management insights -- id ( )
Python : This behavior is a little bit strange to me , I always thought x/=5 . was equivalent to x=x/5 . . But clearly the g ( x ) function does not create a new reference with /= operation . Could anyone offer an explanation for this ? <code> def f ( x ) : x=x/5 . return xdef g ( x ) : x/=5 . return xx_var = np.arange...
Unexpected behavior for numpy self division
Python : I have a large file ( 2GB ) of categorical data ( mostly `` Nan '' -- but populated here and there with actual values ) that is too large to read into a single data frame . I had a rather difficult time coming up with a object to store all the unique values for each column ( Which is my goal -- eventually I ne...
The Pythonic way to grow a list of lists
Python : What is the best data structure to have a both-ways mapping of object , with flag values for each couple , in Python ? For instance , let 's imagine I have two pools of men and women I want to match together . I want a datastructure to store de matches so I can access the corresponding man of each woman , the ...
Efficient both ways mapping in Python with flag values
Python : I am using python 3.6.5 and plotly 3.9.0 to create an interactive line graph that the user can change the range using a ranger slide . I would like to add a hover tool to the range slider so that when the user moves the slider , a hover icon says the new date range before the user releases the mouse . I think ...
Hover tool for plotly slider widget ( python )
Python : Is there a way to import numpy without installing it ? I have a general application built into an .exe with PyInstaller . The application has a plugin system which allows it to be extended through Python scripts . The plugin import system works fine for basic modules ( lone .py files , classes , functions , an...
Import numpy without installing
Python : I have a data frame like thisI want to filter all the 'None ' from col1 and add the corresponding col2 value into a new column col3 . My output look like this Can anyone help me to achieve this . <code> ID col1 col2 1 Abc street 2017-07-27 1 None 2017-08-17 1 Def street 2018-07-15 1 None 2018-08-13 2 fbg stree...
Filter a data-frame and add a new column according to the given condition
Python : When adding an integer value to a float value , I realized that __add__ method is working fine if called on float , such as this : but not if called on an integer : At first I thought that __add__ was just being implemented differently for int and float types ( like float types accepting to be added to int typ...
Python : __add__ and + , different behavior with float and integer
Python : Is it common in Python to keep testing for type values when working in a OOP fashion ? Or I can use a more loose approach , like : <code> class Foo ( ) : def __init__ ( self , barObject ) : self.bar = setBarObject ( barObject ) def setBarObject ( barObject ) ; if ( isInstance ( barObject , Bar ) : self.bar = b...
Is it common/good practice to test for type values in Python ?
Python : I am trying to divide a rectangle with specific coordinates into 8 smaller rectangles ( two columns and four rows ) is this possible ? Input for example would be : and result would be : This is what I 've tried so far : This is what I need ( kind of : / ) : <code> rec = [ ( 0 , 0 ) , ( 0 , 330 ) , ( 200 , 330 ...
How to divide a rectangle in specific number of rows and columns ?
Python : For example , here is a simple c function that use pointer to return value : I want to call add ( ) function for every elements in two arrays , and collect the result by numba @ jit function.Compile the c code first : And load it by ctypes : then the numba function : But numba has no addressof operator or func...
How to call ctypes functions that use pointer to return value in Numba @ jit
Python : Let us have the following example : This code works fine and I have the following output : Now lets pass the value as bytes : This also works fine and have the following output : But things change when I try to have the key as bytes : This results in TypeError saying : Is there any way we can pass bytes as key...
How can we pass bytes as the key of keyword arguments to functions ?
Python : I 'm trying to merge two dataframes in pandas on a common column name ( orderid ) . The resulting dataframe ( the merged dataframe ) is dropping the orderid from the 2nd data frame . Per the documentation , the 'on ' column should be kept unless you explicitly tell it not to . Which outputs this : What I am tr...
Pandas merge not keeping 'on ' column
Python : I 'm going to write my own Python-Java interface . It is compiled as a DLL andwrapped using ctypes.Yet , it is possible to find Java-classes and allocate Java-objects.But what would be an interface to another language without using those objectsmethods ? My aim is to make this as natural as possible . Unfortun...
My Python-Java Interface , good design ? And how to wrap JNI Functions ?
Python : There are two files : And : When executed with Python 2.7 : When executed with Python 3.5 : What is that weird thing < frozen importlib._bootstrap > all about ? What happened with import and/or inspect that changed this behaviour ? How can we get that Python 2 filename introspection working again on Python 3 ?...
inspect who imported me
Python : When two bar charts ( one horizontal , one vertical ) are shown side-by-side using alt.hconcat , the titles are misaligned even though the heights of the charts are equal . Is there a way to align the titles ? The chart titles are misaligned . ( ca n't post the image since I apparently need 10 reputation point...
Is there a way to align chart titles when ` hconcat ` is used ?
Python : tl ; dr -- In a PySide application , an object whose method throws an exception will remain alive even when all other references have been deleted . Why ? And what , if anything , should one do about this ? In the course of building a simple CRUDish app using a Model-View-Presenter architecture with a PySide G...
Why is PySide 's exception handling extending this object 's lifetime ?
Python : I am trying to read a website 's content using below code.In the result , I am unable to see the the table which I could see when I do `` Inspect '' element manually in the browser.Using selenium could be one solution . But I am looking for some other alternate solutions , if possible.Any idea on how to read t...
Unable to read table from website using Beautifulsoup
Python : I have the following code : Since MyObject inherits from object , why does n't MyCallableSubclass work in every place that MyCallable does ? I 've read a bit about the Liskov substitution principle , and also consulted the Mypy docs about covariance and contravariance . However , even in the docs themselves , ...
How to make Mypy deal with subclasses in functions as expected
Python : I am trying to set up a subclass of pd.DataFrame that has two required arguments when initializing ( group and timestamp_col ) . I want to run validation on those arguments group and timestamp_col , so I have a setter method for each of the properties . This all works until I try to set_index ( ) and get TypeE...
Property Setter for Subclass of Pandas DataFrame
Python : How can I get the second minimum value from each column ? I have this array : I wish to have output like : <code> A = [ [ 72 76 44 62 81 31 ] [ 54 36 82 71 40 45 ] [ 63 59 84 36 34 51 ] [ 58 53 59 22 77 64 ] [ 35 77 60 76 57 44 ] ] A = [ 54 53 59 36 40 44 ]
Get second minimum values per column in 2D array
Python : Python 3.7.2 , though I doubt that piece of information would be very useful.Pygame 1.7.2 . I 'm using this mainly to draw the triangulation . All calculations are done with plain formulas.The pseudocode for the Bowyer-Watson algorithm is as shown , according to Wikipedia : However , when I run my code , while...
A Bowyer-Watson Delaunay Triangulation I implemented does n't remove the triangles that contain points of the super-triangle
Python : I 'm currently in the process of writing a client server app as an exercise and I 've gotten pretty much everything to work so far , but there is a mental hurdle that I have n't been able to successfully google myself over . In the server application am I correct in my thinking that threading the packet handle...
Python Threading Concept Question
Python : I 'm trying to fetch data returned from url . Curl to the url results in following : [ { `` name '' : `` Hello World ! `` } ] Following is the code in my App.jsMy contact.js contains the following : The data does not get rendered or logged . Is there an issue in the way I 'm fetching it ? EDIT : The issue is r...
React not reading json returned from flask GET endpoint
Python : I created the requirements.txt with pip freeze > requirements.txt . Some modules show the @ file ... .. instead of the version # . What does it mean and why it show ? Conda : 4.8.3Here is the result of requirements.txt . e.g . astroid , flask-admin , matplotlib shows `` @ file '' belowHere is the conda listFin...
Why does the pip requirements file contain `` @ file '' instead of version number ?
Python : I 'm using ConfigObj in python with Template-style interpolation . Unwrapping my config dictionary via ** does n't seem to do interpolation . Is this a feature or a bug ? Any nice workarounds ? I 'd expect the second line to be /test/directory . Why does n't interpolation work with **kwargs ? <code> $ cat my.c...
Why does n't **kwargs interpolate with python ConfigObj ?
Python : In Python one can iterate over multiple variables simultaneously like this : Is there a C # analog closer than this ? Edit - Just to clarify , the exact code in question was having to assign a name to each index in the C # example . <code> my_list = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] for a , b , c in my_list : ...
C # analog of multi-variable iteration in Python ?
Python : I am using scrapy 1.1 to scrape a website . The site requires periodic relogin . I can tell when this is needed because when login is required a 302 redirection occurs . Based on # http : //sangaline.com/post/advanced-web-scraping-tutorial/ , I have subclassed the RedirectMiddleware , making the location http ...
Scrapy : Sending information to prior function
Python : I am just getting into Python coding and I 'm wondering which is considered more pythonic ? Example A : An obvious main method.or Example B : No main method.Any help/pointers would be appreciated ? <code> # ! /usr/bin/env python -ttimport randomdef dice_roll ( num=1 ) : for _ in range ( num ) : print ( `` Roll...
Main functions , pythonic ?
Python : I have a class that connects three other services , specifically designed to make implementing the other services more modular , but the bulk of my unit test logic is in mock verification . Is there a way to redesign to avoid this ? Python example : I then have to mock input , output and finder . Even if I do ...
Is having a unit test that is mostly mock verification a smell ?
Python : So I have this code for an object . That object being a move you can make in a game of rock papers scissor.Now , the object needs to be both an integer ( for matching a protocol ) and a string for convenience of writing and viewing.Now I 'm kinda new to python , coming from a C and Java background.A big thing ...
How can I make this code Pythonic
Python : I have a pandas DataFrame with a two-level multiindex . The second level is numeric and supposed to be sorted and sequential for each unique value of the first-level index , but has gaps . How do I insert the `` missing '' rows ? Sample input : Expected output : I suspect I could have used resample , but I am ...
Inserting `` missing '' multiindex rows into a Pandas Dataframe
Python : I 've struck a problem with a regular expression in Python ( 2.7.9 ) I 'm trying to strip out HTML < span > tags using a regex like so : re.sub ( r ' < span [ ^ > ] * > ( .* ? ) < /span > ' , r'\1 ' , input_text , re.S ) ( the regex reads thusly : < span , anything that 's not a > , then a > , then non-greedy-...
python re.sub non-greed substitute fails with a newline in the string
Python : Simple Problem Statement : Is is possible to have a array of a custom size data type ( 3/5/6/7 byte ) in C or Cython ? Background : I have run across a major memory inefficiency while attempting to code a complex algorithm . The algorithm calls for the storage of a mind-blowing amount of data . All the data is...
Custom size array