text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : I 'm trying to do type conversions using a generator , but I want to move to the next element in the iterator once I successfully yield a value . My current attempt will yield multiple values in cases where the expressions are successful : How is this accomplished ? <code> def type_convert ( data ) : for item ...
Yield Only Once Per Iteration
Python : Suppose you are working with some bodgy piece of code which you ca n't trust , is there a way to run it safely without losing control of your script ? An example might be a function which only works some of the time and might fail randomly/spectacularly , how could you retry until it works ? I tried some hacki...
How to safely run unreliable piece of code ?
Python : BackgroundI am stuck on this problem : Each new term in the Fibonacci sequence is generated by adding the previous two terms . By starting with 1 and 2 , the first 10 terms will be:1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , ... By considering the terms in the Fibonacci sequence whose values do not exceed fou...
Project Euler # 2 in Python
Python : The function glib.spawn_async allows you to hook three callbacks which are called on event on stdout , stderr , and on process completion.How can I mimic the same functionality with subprocess with either threads or asyncio ? I am more interested in the functionality rather than threading/asynio but an answer ...
Mimicing glib.spawn_async with Popen…
Python : Consider following problem in Python : this statement yield False andyields True . So far as I know , [ ] equals False , but what is an empty tuple ? If we typeWe get a True , as return value . But why ? Thanks <code> > > > ( ) < [ ] > > > ( ) > [ ] > > > 1233 < ( 1,2 )
Why is tuple larger than a list in python ?
Python : With Python one can filter specific warnings using the following command line syntax : But how can one determine the correct value for module for a particular warning ? Consider the following example : Using ( pipenv -- python 3.6.5 install lxml==4.2.4 ) If one wanted to ignore only that specific import warnin...
How to determine the module name to filter a specific Python warning ?
Python : In this link , it says that truncated MD5 is uniformly distributed . I wanted to check it using PySpark and I created 1,000,000 UUIDs in Python first as shown below . Then truncated the first three characters from MD5 . But the plot I get is not similar to the cumulative distribution function of a uniform dist...
ECDF plot from a truncated MD5
Python : I 'm subclassing the threading.Thread class and it currently looks like this : Is the __init__ required in this instance ? If I leave it out , is it called automatically ? <code> class MyThread ( threading.Thread ) : def __init__ ( self : super ( MyThread , self ) .__init__ ( ) def run ( self ) : # Do some stu...
Is __init__ necessary if it only calls super.__init__ ?
Python : I 'm working on a python project where I have a pygame window , but I 'd also like to have a PyGTK window next to it at the same time with information about objects inside the pygame window . However , when I start the PyGTK window the pygame window freezes until the PyGTK one is closed , even if I do all the ...
Pygame and PyGTK side by side
Python : I would like to do a 'daxpy ' ( add to a vector the scalar multiple of a second vector and assign the result to the first ) with numpy using numba . Doing the following test , I noticed that writing the loop myself was much faster than doing a += c * b.I was not expecting this . What is the reason for this beh...
Numba : Manual looping faster than a += c * b with numpy arrays ?
Python : I 'm a newcomer to the python/Django universe and just started a huge project I 'm pretty excited about . I need to have my users login through Facebook and my app has a really specific user flow . I 've set up django-allauth and everything works as I needed . I 've overriden LOGIN_REDIRECT_URL so that my user...
Changing django-allauth render_authentication_error behavior
Python : I have dictionary of list as follows ( it can be more than 1M elements , also assume dictionary is sorted by key ) I want to know what is the most efficient way ( fastest way for large dictionary ) to convert it into list of row and column index like : Here are some solutions that I have so far : Using iterati...
Efficient way to convert dictionary of list to pair list of key and value
Python : I was recently playing with problem 14 of the Euler project : which number in the range 1..1_000_000 produces the longest Collatz sequence ? I 'm aware of the issue of having to memoize to get reasonable times , and the following piece of Python code returns an answer relatively quickly using that technique ( ...
why is this memoized Euler14 implementation so much slower in Raku than Python ?
Python : Ultimately , my goal is to extend Django 's ModelAdmin to provide field-level permissions—that is , given properties of the request object and values of the fields of the object being edited , I would like to control whether or not the fields/inlines are visible to the user . I ultimately accomplished this by ...
ModelAdmin thread-safety/caching issues
Python : If I have a list of tuples , where each tuple represents variables , a , b and c , how can I eliminate redundant tuples ? Redundant tuples are those where a and b are simply interchanged , but c is the same . So for this example : my final list should only contain only half of the entries . One possible output...
eliminating redundant tuples
Python : I have received an output , it likes this.I know it is not a standard JSON format , but is it still possible to parse into Python Dictionary type ? Is it a must that orange , apple , lemon must be quoted ? Thanks you <code> { orange : ' 2 ' , apple : ' 1 ' , lemon : ' 3 ' }
Python : How can I parse { apple : `` 1 '' , orange : `` 2 '' } into Dictionary ?
Python : I have a class named Factor in the module Factor.py ( https : //github.com/pgmpy/pgmpy/blob/dev/pgmpy/factors/Factor.py ) and also have function named factor_product in Factor.py as : Now if I even pass instances of Factor to the function , it still throws TypeError . A few lines from the debugger with breakpo...
Strange behaviour of isinstance function
Python : The HuggingFace BERT TensorFlow implementation allows us to feed in a precomputed embedding in place of the embedding lookup that is native to BERT . This is done using the model 's call method 's optional parameter inputs_embeds ( in place of input_ids ) . To test this out , I wanted to make sure that if I di...
HuggingFace BERT ` inputs_embeds ` giving unexpected result
Python : I am converting code from python2 to python3 for newstyle classes using future . My project is in Django 1.11I have a class in forms.py as : in Python 2which is converted to : in Python 3I have a selenium test that fails when this Form is invoked after it is converted to Python3 with the following error : Howe...
Import object from builtins affecting just one class
Python : Given a dictionary of string key and integer values , what 's the fastest way to split each key into a string-type key tuple then append a special substring < /w > to the last item in the tupleGiven : The goal is to achieve : One way to do it is to iterate through the counter and converting all but the last ch...
What 's the fastest way to split dictionary keys into a string-type tuples and append another string to last items in the tuples ?
Python : I have a bug in the program I am writing where I first call : Then I call : I want the program to update the display and then wait for a set period of time before continuing . However for some reason the display only updates after the waiting time , not before.I have attached some example code to demonstrate w...
Pygame : Display not updating until after delay
Python : I have a program for a simulation and inside the program I have a function . I have realized that the function consumes most time of simulation . So , I am trying to optimize the funcion first . The function is as followsJulia version 1.1 : I also rewrite the above function in python+numba for comparison as fo...
Optimizing suggestions for a piece of Julia and Python code
Python : I 'm having a problem where I 'm getting different random numbers across different computers despitescipy.__version__ == ' 1.2.1 ' on all computersnumpy.__version__ == ' 1.15.4 ' on all computersrandom_state seed is fixed to the same number ( 42 ) in every function call that generates random numbers for reprod...
Does scipy.stats produce different random numbers for different computer hardware ?
Python : What is the most natural way to complete the following code ? <code> import functools @ functools.total_orderingclass X : def __init__ ( self , a ) : self._a = a def __eq__ ( self , other ) : if not isinstance ( other , X ) : return False return self._a == other._a def __lt__ ( self , other ) : if not isinstan...
How to handle mixed types when implementing comparison operators ?
Python : I have a function with the following signature : Important part here are NamespacedAPIObject parameters . This function takes an obj_type as type spec , then creates an object ( instance ) of that type ( class ) . Then some other objects of that type are added to a list , which is then filtered with obj_condit...
Python 3.6 type hinting for a function accepting generic class type and instance type of the same generic type
Python : I wrote an extremely naive implementation of the Sieve of Atkin , based on Wikipedia 's inefficient but clear pseudocode . I initially wrote the algorithm in MATLAB , and it omits 5 as a prime number . I also wrote the algorithm in Python with the same result . Technically , I know why 5 is being excluded ; in...
Why does my naive implementation of the Sieve of Atkins exclude 5 ?
Python : Suppose I have a function like this : Then I can call : Both return the same as expected.However , I would like to do something like this : The idea behind this is that I would like to pre-configure a function and then put it in a pipe like this : Then , bar ( 1,2,3 ) ( data ) would be called as a part of the ...
Currying in inversed order in python
Python : Reading of a file downloaded from Google Cloud Storage fails in a python + flask + gunicorn + nginx + Compute Engine app . Link to the code : https : //github.com/samuq/CE-test . The line number 64 of the file 'ETL_SHP_READ_SQL_WRITE ' returns nothing , although the file is valid and has data in it : <code> pr...
Reading of a file from Google Cloud Storage fails in a python + flask + gunicorn + nginx + Compute Engine app
Python : A design question about python @ property , I 've encountered this two options : Option-1 : Option-2 : Question : I would like to know if there is any difference by using those 2 options ? If so how does it influencing my code ? <code> class ThisIsMyClass ( object ) : @ property def ClassAttr ( self ) : ... @ ...
Python @ property design
Python : I 'm recording data at 2000 Hz , which means every 0.5 milliseconds I have another data point . But my recording software only records with 1 millisecond precision , so that means I have duplicate values in my dataframe index which uses type float.So in order to fix the duplicates I want to add 0.005 to every ...
How do you add a value to a float index of a dataframe for every other row ?
Python : I have written a simple one-liner in julia to solve a little maths problem : find a two digit number , A and a three digit number B such that their product , A x B is a five digit numbers and every digit from 0 to 9 appears exactly once among the numbers A , B and A x B . For example , Here is my julia code wh...
Optimising a julia one-liner to make it as fast as python
Python : I have a list of tuples each with three items : I want to find number of tuples in the list with same first and third items , like with first item 1 and third item 2015 , there are 4 tuples ; with first item 2 and third item 2015 , there are 4 tuples . I tried : It does n't give desired result . How to do it ?...
Finding count of tuples with same first and third item in list of tuples
Python : The problemI 'm trying to create a spider that crawls and scrapes every product from a store and outputs the results to a JSON file , that includes going into each category in the main page and scraping every product ( just name and price ) , each product class page includes infinite scrolling . My problem is ...
How to crawl in desired order or Synchronously in Scrapy ?
Python : I 'm performing a decently complex operation on some 3- and 4-dimensional tensor using numpy einsum.My actual code isThis does what I want it to do.Using einsum_path , the result is : This indicates a theoretical speedup of about 200x.How can I use this result to speed up my code ? How do I `` implement '' wha...
How to use numpy einsum_path result ?
Python : How to get the most frequent row in a DataFrame ? For example , if I have the following table : Expected result : EDIT : I need the most frequent row ( as one unit ) and not the most frequent column value that can be calculated with the mode ( ) method . <code> col_1 col_2 col_30 1 1 A1 1 0 A2 0 1 A3 1 1 A4 1 ...
How to get the most frequent row in table
Python : In answering this question , I found that after using melt on a pandas dataframe , a column that was previously an ordered Categorical dtype becomes an object . Is this intended behaviour ? Note : not looking for a solution , just wondering if there is any reason for this behaviour or if it 's not intended beh...
Categorical dtype changes after using melt
Python : In Pycharm , the following code produces a warning : Why ? Should I not be concatenating two lists of mixed , hinted types ? <code> from typing import Listlist1 : List [ int ] = [ 1 , 2 , 3 ] list2 : List [ str ] = [ `` 1 '' , `` 2 '' , `` 3 '' ] list3 : List [ object ] = list1 + list2 # ↳ Expected type List [...
Why do I get a warning when concatenating lists of mixed types in Pycharm ?
Python : Problem : I 'm working with a dataset that contains many images that look something like this : Now I need all these images to be oriented horizontally or vertically , such that the color palette is either at the bottom or the right side of the image . This can be done by simply rotating the image , but the tr...
Detecting a horizontal line in an image
Python : I am trying to get the alphabet from python string module depending on a given locale with no success ( that is with the diacritics , i.e . éèêà ... for French ) . Here is a minimal example : In the python documentation , it is said that string.letters is locale dependent , but it seems that it does not work f...
Python string.letters does not include locale diacritics
Python : As part of a larger project , I 'm trying to `` embed '' a Python interactive interpreter in a Ruby process . I 'd like to be able to do something like the following : Unfortunately , the gets seems to hang rather than return any kind of output from the Python process . I 've tried variations of this procedure...
Embed Python CLI in a Ruby process ?
Python : I am trying to make a basic calculator but the problem I am having is how do I output the text ? How do I make it so when I click plus it allows me to add or if I click divide it allows me to divide and shows the output on the yellow part on my screenThis is what I have right now . You could run it ; there is ...
Pygame Basic calculator
Python : Here is a sample of the input pandas dataframe : Here is the expected DF ( output ) : As you can see , the missing days in the data will simply duplicate previous day 's rows so that I 'm simply filling the missing days with ( all ) previous day data . The thing is that the number of rows per day might differ ...
Duplicating previous day rows for all missing dates dataframe
Python : I 'm looking to re-create a R script and I am stuck on how to recreate this pipe in Python . I am analyzing the cumulative production of different factories and need to normalize their cumulative production time in order to compare.The pipe looks like this : It takes this : And Turns it into this : This in tur...
Python equivalent for tidyr : :complete in R that allows specifying additional values
Python : While profiling the memory consumption of my algorithm , I was surprised that sometimes for smaller inputs more memory was needed.It all boils down to the following usage of pandas.unique ( ) : with N=6*10^7 it needs 3.7GB peak memory , but with N=8*10^7 `` only '' 3GB . Scanning different input-size yields th...
Curious memory consumption of pandas.unique ( )
Python : I have a very simple setup : market data ( ticks ) in a pandas dataframe df like so : Now I use pandas.groupy to aggregate periodsIt is easy to get minimum and maximum prices by period , e.g.This is reasonably fast , too . Now , I also want first and last price per period . This is where the trouble begins . O...
Speed up custom aggregation functions
Python : My code is : The output I want is : The error I get is : ValueError : shape mismatch : value array of shape ( 3 , ) could not be broadcast to indexing result of shape ( 4 , ) When I do : The out is : Why it does n't work when I try to insert an array ? P.S . I I can not use loops <code> x=np.linspace ( 1,5,5 )...
NumPy - Insert an array of zeros after specified indices
Python : I found something interesting , here is a snippet of code : If I run this code , I will get : But if I change class B ( object ) to class B ( ) , I will get : I found a note in the __del__ doc : It is not guaranteed that del ( ) methods are called for objects that still exist when the interpreter exits.Then , ...
Why do new style class and old style class have different behavior in this case ?
Python : In this question on S/O : Can existing virtualenv be upgraded gracefully ? The accepted answer says that you can : use the Python 2.6 virtualenv to `` revirtual '' the existing directoryI can not seem to find any details on how to `` revirtual '' an existing virtualenv . I know how to manually install python ,...
What is `` revirtual '' in this answer ?
Python : I 'm reading some tab-delimited data into a pandas Dataframe using read_csv , but I have tabs occurring within the column data which means I ca n't just use `` \t '' as a separator . Specifically , the last entries in each line are a set of tab delimited optional tags which match [ A-Za-z ] [ A-Za-z0-9 ] : [ A...
Restrict separator to only some tabs when using pandas read_csv
Python : I have a problem where I need to ( pretty sure at least ) go through the entire list to solve . The question is to figure out the largest number of consecutive numbers in a list that add up to another ( greater ) element in that list . If there are n't any then we just take the largest value in the list as the...
Speeding up Python code that has to go through entire list
Python : I have a digraph consisting of a strongly connected component ( blue ) and a set of nodes ( orange ) that are the inputs to it . The challenge is to break as many cycles as possible with a minimum of removed edges . In addition , there must be a path from each orange node to each blue node.I solve the problem ...
Breaking cycles in a digraph with the condition of preserving connectivity for certain nodes
Python : Facing this issue with Python : As you can see the right-justification stopped working once the coloring tags get added to the text . The second `` text '' should be indented as the first one , but it was not . <code> a = `` text '' print ( ' { 0 : > 10 } '.format ( a ) ) # output : textb = `` \x1b [ 33mtext\x...
String alignment does not work with ansi colors
Python : I would like to sort a list in Python based on a pre-sorted listIs there a way to sort the list to reflect the presorted list despite the fact that not all the elements are present in the unsorted list ? I want the result to look something like this : Thanks ! <code> presorted_list = [ '2C ' , '3C ' , '4C ' , ...
Sort a list in python based on another sorted list
Python : I am trying to generate random text using letter frequencies that I have obtained . First , I succeeded with the following code : This until the letter z and spacebar . This give me > 50 lines of code and I want to get the same result using an array.So far I have : But it is n't working properly , as the range...
Using array to generate random text
Python : What is the explanation for this behavior in Python ? a and b evaluates to 20 , while b and a evaluates to 10 . Are positive ints equivalent to True ? Why does it evaluate to the second value ? Because it is second ? <code> a = 10b = 20a and b # 20b and a # 10
Python `` and '' operator with ints
Python : Let 's say I have two objects of a same class : objA and objB . Their relationship is the following : If I use both objects as keys in a Python dict , then they will be considered as the same key , and overwrite each other . Is there a way to override the dict comparator to use the is comparison instead of == ...
Can I change the way keys are compared in a Python dict ? I want to use the operator 'is ' instead of ==
Python : Take a look at this : Evidently , the compiler has pre-evaluated ( 2+3 ) *4 , which makes sense . Now , if I simply change the order of the operands of * : The expression is no longer fully pre-evaluated ! What is the reason for this ? I am using CPython 2.7.3 . <code> > > > def f ( ) : ... return ( 2+3 ) *4 ....
Why are these two functions different ?
Python : I stumbled upon this apparently horrific piece of code : What is supposed if xx in `` '' : to mean ? Does n't it always evaluates to False ? <code> def determine_db_name ( ) : if wallet_name in `` '' : return `` wallet.dat '' else : return wallet_name
python : in `` '' ?
Python : I 've installed Django-CMS onto an existing site and while it is n't throwing errors , it is n't working . In particular , the header on a given page appears when I use `` / ? edit '' but none of the pull down menus work , and very little ( possibly none ) of the JavaScript works . Other facets : I 've done th...
Django-cms installs , but pull-downs and other JS does n't work - ideas for fixing ?
Python : I have a data set which has driver trip information as mentioned below . My objective is to come up with a new mileage or an adjusted mileage which takes into account the load a driver is carrying and the vehicle he/she is driving . Because we found that there is a negative correlation between mileage and load...
Machine Learning : normalize target var based on the impact of independent var
Python : I am looking for a way to speed up my code . I managed to speed up most parts of my code , reducing runtime to about 10 hours , but it 's still not fast enough and since I 'm running out of time I 'm looking for a quick way to optimize my code . An example : In the code above I read in about 6 million rows of ...
Looking for a quick way to speed up my code
Python : I am a bit confused on why you need a lambda function for nesting defaultdictWhy ca n't you do it like this ? instead of <code> test = defaultdict ( defaultdict ( list ) ) test = defaultdict ( lambda : defaultdict ( float ) )
Why do you need lambda to nest defaultdict ?
Python : I can not add the integer number 1 to an existing set . In an interactive shell , this is what I am doing : This question was posted two months ago , but I believe it was misunderstood.I am using Python 3.2.3 . <code> > > > st = { ' a ' , True , 'Vanilla ' } > > > st { ' a ' , True , 'Vanilla ' } > > > st.add ...
Adding the number 1 to a set has no effect
Python : I have this code : The file graph.txt contains this : The first two number are telling me , that GRAPH has 5 nodes and 10 edges . The Following number pairs demonstrate the edges between nodes . For example `` 1 4 '' means an edge between node 1 and 4.Problem is , the output should be this : But instead of tha...
Why cycle behaves differently in just one iteration ?
Python : When investigating for another question , I found the following : This was expected : But this I did not expect : And especially not this : Python seems to create new objects for each method access . Why am I seeing this behavior ? I.e . what is the reason why it ca n't reuse one object per class and one per i...
Python method accessor creates new objects on each access ?
Python : Python saysWhat operation does < < performs in Python ? <code> 1 < < 16 = 65536
What does < < represent in python ?
Python : I wrote a function that gets as an input a list of unique ints in order , ( from small to big ) . Im supposed to find in the list an index that matches the value in the index . for example if L [ 2 ] ==2 the output is true.so after i did that in complexity O ( logn ) i now want to find how many indexes behave ...
dificulty solving a code in O ( logn )
Python : I want to generate a mask from the results of numpy.searchsorted ( ) : pt is an array . Then I want to create a boolean mask of size ( 200 , 1000000 ) with True values when its indices are idx [ 0 : pt [ i ] ] , and I come up with a for-loop like this : Anyone has an idea to speed up the for-loop ? <code> impo...
How to speed up the performance of array masking from the results of numpy.searchsorted in python ?
Python : I have data frame `` A '' that looks like this : It has 22,000,000 rows × 5 columns and there is data frame `` B '' which looks like this : It has 2,000,000 rows × 3 columns.I want to replace type 's value of data frame `` A '' with `` B '' Where : I want to check a location from B belongs to which one of the ...
Fast ( vectorized ) way to find points in one DF belonging to equally sized rectangles ( given by two points ) from the second DF
Python : I am a Python newbie . I have this small problem . I want to print a list of objects but all it prints is some weird internal representation of object . I have even defined __str__ method but still I am getting this weird output . What am I missing here ? Please note that I know I can use either a for loop or ...
Printing a list of objects
Python : Say I have defined the following expression : The expr variable now displays like this : While this is fine for this minimal example , it gets quite messy in larger expressions . This really hinders my ability to see what happens later on when I compute sums over all r ( i , j ) , derivatives etc . My question...
Sympy - Rename part of an expression
Python : The zipfile.ZipFile documentation says that ZIP_DEFLATED can be used as compression method only if zlib is available , but neither zipfile module specification nor zlib module specification says anything about when zlib might not be available , or how to check for its availability.I work on Windows and when I ...
How to detect whether zlib is available and whether ZIP_DEFLATED is available ?
Python : In python you can make instances callable by implementing the __call__ method . For example But I can also implement a method of my own , say 'run ' : When should I implement __call__ ? <code> class Blah : def __call__ ( self ) : print `` hello '' obj = Blah ( ) obj ( ) class Blah : def run ( self ) : print ``...
When should I implement __call__
Python : Is there a way to align python basemaps like this figure below ? Here 's some sample basemap code to produce a map : <code> from mpl_toolkits.basemap import Basemapimport matplotlib.pyplot as pltfig = plt.figure ( figsize= ( 8 , 4.5 ) ) plt.subplots_adjust ( left=0.02 , right=0.98 , top=0.98 , bottom=0.00 ) m ...
Aligning maps made using basemap
Python : I would like to POST a mp4 file to AWS MediaStore using Python and the Signature v4 . I am trying to use the PutObject action from MediaStore.For this job , I can not use the SDK or the CLI.I can make GET requests to MediaStore with Python without the SDK or the CLI , but regarding POST requests , I did n't un...
POST file to AWS Mediastore with Python 3 without SDK , without CLI
Python : Okay , sorry if my problem seems a bit rough . I 'll try to explain it in a figurative way , I hope this is satisfactory . 10 children . 5 boxes . Each child chooses three boxes . Each box is opened : - If it contains something , all children selected this box gets 1 point - Otherwise , nobody gets a point.My ...
What is the most effective way to incremente a large number of values in Python ?
Python : I was reading Mendeley docs from here . I am trying to get data in my console for which I am using the following code from the tutorial Now I do n't understand where is auth_response will come from in the last line of code ? Does anybody have any idea ? Thanks <code> from mendeley import Mendeley # These value...
Authentication issue in mendeley Python SDK
Python : I am in the process of improving a program that parses XML and categorises and indexes its subtrees . The actual program is too large to show here , so I have brought it down to a minimal test case showing the issue I encounter.The idea is : Process XML files in a directory , one by oneProcess all alpino_ds no...
Multiprocessing large XML file with shared memory complex objects
Python : All my django-models have unicode functions , at the moment these tend to be written like this : However , Code Like a Pythonista , at http : //python.net/~goodger/projects/pycon/2007/idiomatic/handout.html # string-formatting points out that self.__dict__ is a dictionary , and as such the above can be simplif...
Django : More pythonic __unicode__
Python : I am relatively new to the world of Python and trying to use it as a back-up platform to do data analysis . I generally use data.table for my data analysis needs.The issue is that when I run group-aggregate operation on big CSV file ( randomized , zipped , uploaded at http : //www.filedropper.com/ddataredact_1...
Group several columns then aggregate a set of columns in Pandas ( It crashes badly compared to R 's data.table )
Python : The code above yields : What 's wrong ? I 've tried this with many other objects ( eg : and then in the body of my code ) and it works fine for everything I 've tried EXCEPT Moon.EDIT ( probably useless information ) : In https : //github.com/brandon-rhodes/pyephem/tree/master/libastro-3.7.5 : The routines for...
Perl 's Inline : :Python fails on pyephem
Python : The pandas.DataFrame.to_numpy method has a copy argument with the following documentation : copy : bool , default False Whether to ensure that the returned value is a not a view on another array . Note that copy=False does not ensure that to_numpy ( ) is no-copy . Rather , copy=True ensure that a copy is made ...
How to find out ` DataFrame.to_numpy ` did not create a copy
Python : What is a good pattern to avoid code duplication when dealing with different exception types in Python , eg . I want to treat URLError and HTTPError simlar but not quite : In this example , I would like to avoid the duplication of the first logger.error call . Given URLError is the parent of HTTPError one coul...
Python : how to avoid code duplication in exception catching ?
Python : I have a 2-D numpy array with 100,000+ rows . I need to return a subset of those rows ( and I need to perform that operations many 1,000s of times , so efficiency is important ) .A mock-up example is like this : So ... I want to return the array from a with rows identified in the first column by b : The differ...
Most efficient way to pull specified rows from a 2-d array ?
Python : The function numpy.savez ( ) allows to store numpy objects in a file . Storing the same same object in two files results in two different files : The two files differ : Why are n't the files identical ? Is there some random behavior , filename or time stamp included ? Can this be workaround or fixed ? ( Is it ...
Why does numpy.savez ( ) output non reproducible files ?
Python : until this point I was thinking there will be only one copy of immutable object and that will be shared ( pointed ) by all the variables.But when I tried , the below steps I understood that I was wrong.can anyone please explain me the internals ? <code> > > > a=1 > > > b=1 > > > id ( a ) 140472563599848 > > > ...
Internals for python tuples
Python : I was wondering if its possible to make a one-liner with pyp that has the same functionality as this.This takes in a comma separated list of numbers with 8 numbers per line and outputs it in the same format except the last two numbers in each line are reduced modulo 12 . It also outputs the first line ( the he...
Python one-liner ( converting perl to pyp )
Python : I have the following snippet that extracts indices of all unique values ( hashable ) in a sequence-like data with canonical indices and store them in a dictionary as lists : This looks like to me a quite common use case . And it happens that 90 % of the execution time of my code is spent in these few lines . T...
Python : faster operation for indexing
Python : I am using Airnef to download pictures from my Canon DSLR camera through python.I can download one picture without problems so the whole setup seems to work . However , as soon as I want to download another image the software hangs . The code to me looks quite complex.Two months ago I did post a thread on Test...
Python program Airnef stuck while downloading images
Python : For example , I 'm curious about what method/function on x is returning 1 . I 'm asking because I 'm seeing differences between calling print x and simply x. Similary , is there a way to specify what is called ? Does this configuration exist in IPython ? <code> python > > x = 1 > > x1
When I am in the Python or IPython console , what is called when I am returned an output ?
Python : My model is trained on digit images ( MNIST dataset ) . I am trying to print the output of the second layer of my network - an array of 128 numbers.After reading a lot of examples - for instance this , and this , or this.I did not manage to do this on my own network . Neither of the solutions work of my own al...
How to output the second layer of a network ?
Python : I have a 200x3 matrix in python which I would like to plot . However , by using Matplotlib I get the following figure . How can I plot an image which looks nicer ? my code : <code> import matplotlib.pyplot as pltplt.imshow ( spectrum_matrix ) plt.show ( )
matplotlib aspect ratio for narrow matrices
Python : I have a strange issue that comes and goes randomly and I really ca n't figure out when and why.I am running a snakemake pipeline like this : I installed snakemake 5.9.1 ( also tried downgrading to 5.5.4 ) within a conda environment.This works fine if I just run this command , but when I qsub this command to t...
snakemake cluster script ImportError snakemake.utils
Python : Let 's say I have a module which fails to import ( there is an exception when importing it ) .eg . test.py with the following contents : [ Obviously , this is n't my actual file , but it will stand in as a good proxy ] Now , at the python prompt : What 's the best way to find the path/file location of test.py ...
How do I find the path for a failed python import ?
Python : Recently I read an interesting discussion on how to make a singleton in Python.One of the solutions was a tricky decorator defining a class inside its code as a substitute for decorated class : Output is : It is stated , that if we use super ( MyClass , self ) .__init__ ( text ) inside __init__ of MyClass , we...
Why a recursion happens here ?
Python : I want to interpolate one axis of data inside a 3-dimensional array . The given x-values for the different vales differ slightly but they should all be mapped to the same x-values.Since the given x-values are not identical , currently I do the following : Using two nested for-loops is unsurprisingly very slow ...
Fast interpolation of one array axis
Python : I have a list of url 's and headers from a newspaper site in my country . As a general example : Each URL element has a corresponding sequence of 'news ' elements , which can differ in length . In the example above , URL1 has 3 corresponding news and URL3 has only one.Sometimes a URL has no corresponding `` ne...
How to create a dictionary using a single list ?
Python : I posted a similar question a few days ago but without any code , now I created a test code in hopes of getting some help.Code is at the bottom.I got some dataset where I have a bunch of large files ( ~100 ) and I want to extract specific lines from those files very efficiently ( both in memory and in speed ) ...
Python mmap - slow access to end of files [ with test code ]
Python : I have the following piece of code where I try to override a method : However , when I run it I get TypeError exception : What is the problem ? <code> import Queueclass PriorityQueue ( Queue.PriorityQueue ) : def put ( self , item ) : super ( PriorityQueue , self ) .put ( ( item.priority , item ) ) super ( ) a...
Python bizarre class problem
Python : I have a node.js API as below to which I send a POST request from python as below , the issue am facing is if I remove the headers= { `` Content-Type '' : `` application/json '' } the POST goes thorugh , if not i get a Read timed out . error , can anyone provide guidance on how to fix this timeout error ? node...
Read timed out . error while sending a POST request to a node.js API