text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : I was recently comparing the amount of memory occupied by a Python set to that occupied by a frozenset using Pympler : Why would a frozenset created from a set occupy a different amount of memory than one created from some other iterable ? Or is this just a quirk of how Pympler approximates the amount of memor...
memory occupied by set vs frozenset in Python 2.7
Python : I have four different lists . headers , descriptions , short_descriptions and misc . I want to combine these into all the possible ways to print out : like if i had ( i 'm skipping short_description and misc in this example for obvious reasons ) I want it to print out like : What would you say is the best/clea...
Most efficent way to create all possible combinations of four lists in Python ?
Python : I 'm trying to write a decorator that preserves the arguments of the functions it decorates . The motivation for doing this is to write a decorator that interacts nicely with pytest.fixtures.Suppose we have a function foo . It takes a single argument a.If we get the argument spec of fooWe frequently want to cr...
Python create decorator preserving function arguments
Python : I have an array and I need to get the indices satisfying both where a condition is true , and where the same condition is false , e.g . : In my use case x is quite large , this code is called inside a loop , and profiling has revealed that np.where is actually the bottleneck . I 'm currently doing something an...
numpy np.where scan array once to get both sets of indices corresponding to T/F condition
Python : I have a dictionary of dictionaries : And I want to convert it to : The requirement is that new_d [ key ] [ i ] and new_d [ another_key ] [ i ] should be in the same sub-dictionary of d.So I created new_d = { } and then : This gives me what I expected , but I am just wondering if there are some built-in functi...
Convert a dictionary of dictionaries to dictionary of lists
Python : My IPython shell becomes sluggish after I instantiate a QApplication object . For example , even from a fresh start , the following code will make my shell sluggish enough where I have to restart it.As soon as that is submitted , my typing becomes lagged by 2 or 3 seconds . My computer is not fantastic , but I...
QApplication instance causing python shell to be sluggish
Python : I 'm developing a GUI with PySide and I create pixmap from images like this : This works perfectly when I run the program but when I test it with py.test this happens : It says that the pixmap is null , so it seems like the image was n't loaded properly.I really want to test my code and I ca n't find any infor...
Image assets wo n't load when using pytest
Python : Adding seaborn figures to subplots is usually done by passing 'ax ' when creating the figure . For instance : This method , however , does n't apply to seaborn.palplot , which visualizes seaborn color palettes . My goal is to create a figure of different color palettes for scalable color comparison and present...
Add seaborn.palplot axes to existing figure for visualisation of different color palettes
Python : Consider the following example : How could I make it so that an exception will be raised if I try to set a member that is not set in __init__ ? Code above wo n't fail when it is executed , but gives me a fun time to debug the problems.Like with str : Thanks ! <code> class A ( ) : def __init__ ( self ) : self.v...
How to protect againt typos when setting value for class members ?
Python : I am curious why the following would output that there was a match : The newline is before the end of the string , yes ? Why is this matching ? <code> import refoo = 'test\n'match = re.search ( '^\w+ $ ' , foo ) if match == None : print `` It did not match '' else : print `` Match ! ''
Why does \w+ match a trailing newline ?
Python : The following sorting method works perfectly.However the case sensitive related section of the lambdas vi.name if cs else vi.name.lower ( ) gets used 3 times which irks my repeated code gene.Out of interest , can the case aspect be set in advance somehow , but without making permenant changes to the name attri...
Set part of a lambda function in advance to avoid repeated code
Python : I 'm parsing a document that have some UTF-16 encoded string.I have a byte string that contains the following : When converting to utf-8 , I get the following output : The first two chars þÿ indicate it 's a BOM for UTF-16BE , as indicated on WikipediaBut , what I do n't understand is that if I try the UTF16 B...
Struggling with utf-16 encoding/decoding
Python : My simulation needs to implementThis overflows for large x , i. e. I 'm getting the RuntimeWarning : overflow encountered in cosh warning . In principle , as logarithm decreases the number in question , in some range of x , cosh should overflow while log ( cosh ( ) ) should not . Is there any solution for that...
Avoiding overflow in log ( cosh ( x ) )
Python : I m trying to execute several batch-scripts in a python loop . However the said bat-scripts contain cmd /K and thus do not `` terminate '' ( for lack of a better word ) . Therefore python calls the first script and waits forever ... Here is a pseudo-code that gives an idea of what I am trying to do : My questi...
loop over a batch script that does not terminate
Python : I have a sentence and a list This indicates that 5th word in the sentence is a disease type . Now I need to get the starting and ending position of the 5th word . If I just do string search with 'cold ' it will give me the starting position of the `` cold '' which occurs first . <code> str = 'cold weather give...
Find the start and end position of a word in a string based on the index position of that word from a label list
Python : While trying to plot a cumulative distribution function ( CDF ) using matplotlib 's hist function , the last point goes back to zero . I read some threads explaining that this is because of the histogram-like format , but could n't find a solution for my case.Here 's my code : which produces the following imag...
Matplotlib CDF goes back to zero
Python : ProblemHow can I dump a pickle object with its own dependencies ? The pickle object is generally generated from a notebook.I tried creating virtualenv for the notebook to track dependencies , however this way I do n't get only the imports of the pickle object but many more that 's used in other places of the a...
How to use requirements.txt or similar for a pickle object
Python : I have the following function signature : I need the number of positional arguments . How can I return the number ( 2 ) of positional arguments ( x & s ) . The number of keyword arguments is not relevant . <code> # my signaturedef myfunction ( x , s , c=None , d=None ) : # some irrelevant function body
Count positional arguments in function signature
Python : I am trying to compile a script utilizing multiprocessing into a Windows executable . At first I ran into the same issue as Why python executable opens new window instance when function by multiprocessing module is called on windows when I compiled it into an executable . Following the accepted answer I adjust...
Multiprocessing python within frozen script
Python : The ProblemI 'm trying to use the Django ORM to do the equivalent of a SQL NOT IN clause , providing a list of IDs in a subselect to bring back a set of records from the logging table . I ca n't figure out if this is possible.The ModelWhat I 've TriedMy first attempt was to use exclude , but this does NOT to n...
Django ORM : Equivalent of SQL ` NOT IN ` ? ` exclude ` and ` Q ` objects do not work
Python : I would like to improve the way this code is written . Right now I have six methods that are almost copy-paste , only one line is changing . How can I make a generic method and depending on the property of the data input to change the calculations ? I was thinking to use functional programming to achieve that ...
How can I use functional programming to make a generic method in python ?
Python : I am trying to create a matrix in a random way in the intervals [ -5 , -1 ] and [ 1,5 ] . How can I create a matrix taking into account the intervals ( no 0 values ) with random values ? I tried to do it with randint of numpy and with piecewise . In the first case it is not posible to indicate 2 intervals and ...
Generate a matrix without 0 values in a random way
Python : I have a dataset that I want to map over using several Pyspark SQL Grouped Map UDFs , at different stages of a larger ETL process that runs on ephemeral clusters in AWS EMR . The Grouped Map API requires that the Pyspark dataframe be grouped prior to the apply , but I have no need to actually group keys.At the...
Pyspark SQL Pandas Grouped Map without GroupBy ?
Python : Ok so I have two lists : I compare them in such a way so I get the following output : The basic is idea to go through each list and compare them . If they have an element in common remove that element . But only one of that element not all of them . If they do n't have an element in common leave it . Two ident...
Looking for more pythonic list comparison solution
Python : When I run the following codeWhere myfile looks like this : I getWhen the expected output is a list of numbers : The corresponding command I run in the terminal isSo far , I have tried playing around with escaping and quoting in different ways , such as escaping slashes in the sed or adding extra quotation mar...
Python subprocess communicate ( ) yields None , when list of number is expected
Python : This question is based on this older question : Given an array : And given its indices : How would I be able to stack them neatly one against the other to form a new 2D array ? This is what I 'd like : This solution by Divakar is what I currently use for 2D arrays : Now , if I wanted to pass a 3D array , I nee...
Generalise slicing operation in a NumPy array
Python : I 've just started using pyparsing this evening and I 've built a complex grammar which describes some sources I 'm working with very effectively . It was very easy and very powerful . However , I 'm having some trouble working with ParsedResults . I need to be able to iterate over nested tokens in the order t...
` pyparsing ` : iterating over ` ParsedResults `
Python : I 've noticed some strange behaviour that may or may not be specific to my system . ( lenovo t430 running windows 8 ) With this script : I get the following output ( what I would consider nominal ) with a browser open . However without a browser open I observe a severe per loop latency . Obviously this is coun...
Why is time.sleep ( ) accuracy influenced by Chrome ?
Python : I was playing around with different implementations of the Euclidean distance metric and I noticed that I get different results for Scipy , pure Python , and Java.Here 's how I compute the distance using Scipy ( = option 1 ) : here 's an implementation in Python I found in a forum ( option 2 ) : and lastly , h...
Euclidean distance , different results between Scipy , pure Python , and Java
Python : Recently I tried compiling program something like this with GCC : and it ran just fine . When I inspected the stack frames the compiler optimized the program to use only one frame , by just jumping back to the beginning of the function and only replacing the arguments to f. And - the compiler was n't even runn...
Detecting Infinite recursion in Python or dynamic languages
Python : I 'm trying to run rqscheduler with django-rq on Heroku with RedisToGo . I 've implemented django-rq as described in their readme ( https : //github.com/ui/django-rq ) .I have a worker that starts an rqworker , and another worker that starts up rqscheduler using the management command suggested in the readme ....
RQScheduler on Heroku
Python : So I am relatively new to python , and in order to learn , I have started writing a program that goes online to wikipedia , finds the first link in the overview section of a random article , follows that link and keeps going until it either enters a loop or finds the philosophy page ( as detailed here ) and th...
Wikipedia philosophy game diagram in python and R
Python : I have some pandas.Series – s , below – that I want to one-hot-encode . I 've found through research that the ' b ' level is not important for my predictive modeling task . I can exclude it from my analysis like so : But when I go to transform a new series , one containing both ' b ' and a new level , 'd ' , I...
sklearn.preprocessing.OneHotEncoder : using drop and handle_unknown='ignore '
Python : I am a beginner at python . As most beginners , I am trying to make a text based rpg . I have finally gotten to the leveling up system and am at another roadblock . When the character levels up , they get to allot x skill points to a skill ( add x to a variable x times ) . two of these variables effect the hea...
Variable X not updating when variables that should effect X change
Python : I am working on a simple 2d game where many enemies continually spawn and chase the player or players in python + pygame . A problem I ran into , and one many people that have programmed this type of game have run into is that the enemies converge very quickly . I have made a temporary solution to this problem...
directing a mass of enemies at once
Python : The result of this comparison surprised me ( CPython 3.4 ) : My understanding of the the docs is that the left operand should be cast to float to match the type of the right operand : Python fully supports mixed arithmetic : when a binary arithmetic operator has operands of different numeric types , the operan...
Why does 9007199254740993 ! = 9007199254740993.0 ?
Python : I was trying to create a module , where portal users could modify the associated partner data . But I get a security error that only admin users could modify configs . File `` ... /server/openerp/addons/base/res/res_config.py '' , line 541 , in execute raise openerp.exceptions.AccessError ( _ ( `` Only adminis...
How can a portal user modify his own partner data in Odoo 8 ?
Python : I have two binary integers , x0 and x1 that are 8 bits ( so they span from 0 to 255 ) . This statement is always true about these numbers : x0 & x1 == 0 . Here is an example : So I need to do the following operation on these numbers . First , interpret these binary representations as ternary ( base-3 ) numbers...
How to merge two binary numbers into a ternary number
Python : I 've seen this quite often : Why do some people use the default value of None for the the owner parameter ? This is even done in the Python docs : <code> def __get__ ( self , instance , owner=None ) : descr.__get__ ( self , obj , type=None ) -- > value
Why do people default owner parameter to None in __get__ ?
Python : Different results for enchant library ( enchant 1.6.6 ) In MAC OSX 10.11.12 ( El Capitan ) : In Linux Ubuntu 14.04 LTS : Any ideas why I get different results and other alternatives in NLTK for `` suggest '' functionality ? MAC OSUbuntuIn my Ubuntu tried : But still same results <code> > > > import enchant > >...
Enchant dictionary across different platforms
Python : Is sequence unpacking atomic ? e.g . : I 'm under the impression it is not.Edit : I meant atomicity in the context of multi-threading , i.e . whether the entire statement is indivisible , as atoms used to be . <code> ( a , b ) = ( c , d )
Is sequence unpacking atomic ?
Python : I want to process stock level-2 data in pandas . Suppose there are four kinds data in each row for simplicity : millis : timestamp , int64 last_price : the last trade price , float64 , ask_queue : the volume of ask side , a fixed size ( 200 ) array of int32bid_queue : the volume of bid side , a fixed size ( 20...
Is there any elegant way to define a dataframe with column of dtype array ?
Python : I want to perform bagging using python scikit-learn.I want to combine RFE ( ) , recursive feature selection algorithm.The step is like below.Make 30 subsets allowing redundant selection ( bagging ) Perform RFE for each data setGet output of each classificationfind top 5 features from each outputI tried to use ...
Bagging ( bootstrap ) of RFE using python scikit-learn
Python : Consider some given sequence and a window length , say the list ( so that ) and window length 3.I 'd like to take the sliding window sum of this sequence , but cyclically ; i.e. , to calculate the length-24 list : The best I could come up with , using collections.deque and Stupid Lambda Tricks , wasIs there so...
Cyclical Sliding Window Iteration
Python : I was wondering if numpy could be used to build the most basic cube model where all cross-combinations and their computed value are stored.Let 's take the following example of data : And to be able to build something like : I 'm hoping that the usage of using something like meshgrid might get me 75 % there . B...
Build a basic cube with numpy ?
Python : One of the biggest challenges in tesseract OCR text recognition is the uneven illumination of images.I need an algorithm that can decide the image is containing uneven illuminations or not . Test Images I Attached the images of no illumination image , glare image ( white-spotted image ) and shadow containing i...
Robust Algorithm to detect uneven illumination in images [ Detection Only Needed ]
Python : I have a script that I want to execute both in Python3.5 and IronPython2.7.The script is originally written with Python3 in mind , so I have some nested loops similar to the code below : Now if I run this in IronPython2.7 I do n't get the same result because zip returns a list and not an iterator.To circumvent...
zip in IronPython 2.7 and Python3.5
Python : I have a large set of csv files ( file_1.csv , file_2.csv ) , separated by time period , that cant be fit into memory . Each file will be in the format mentioned below . Each file is about instrument logs that are consistent in their format . There are set of instruments which can emit different codes ( code )...
How to separate files using dask groupby on a column
Python : I used Taylor expansion in image classification task . Basically , firstly , pixel vector is generated from RGB image , and each pixel values from pixel vector is going to approximated with Taylor series expansion of sin ( x ) . In tensorflow implementation , I tried possible of coding up this with tensorflow ...
make input features map from expansion neurons for convolutional layer in keras
Python : Now I have a numpy array , and a vector.I want to perform a contain operation between the array and the vector row wise . In other words , I want to check whether the first row [ 1 , 2 ] contain 2 , whether the second row [ 3 , 4 ] contain 5 . The expected output would look like : How could I implement this fu...
How to perform contain operation between a numpy array and a vector row-wise ?
Python : I have a dataframe and want to eliminate duplicate rows , that have same values , but in different columns : Rows [ 1 ] , [ 2 ] have the values { x , y , e , f } , but they are arranged in a cross - i.e . if you would exchange columns c , d with a , b in row [ 2 ] you would have a duplicate . I want to drop th...
Pandas find Duplicates in cross values
Python : I am using the arrays modules to store sizable numbers ( many gigabytes ) of unsigned 32 bit ints . Rather than using 4 bytes for each element , python is using 8 bytes , as indicated by array.itemsize , and verified by pympler.eg : I have a large number of elements , so I would benefit from storing them withi...
Can I force python array elements to have a specific size ?
Python : I have the task of porting some python code to Scala for research purposes . Now I use the Apache Math3 commons library and am having difficulty with the MersenneTwister.In Python : In Scala : What am I missing here ? Both are MersenneTwister 's , and Int.MaxValue = 2147483647 = ( 2**31 ) - 1 <code> SEED = 123...
Java Apache Math3 MersenneTwister VS Python random
Python : Since it 's my first time learning systems programming , I 'm having a hard time wrapping my head around the rules . Now , I got confused about memory leaks . Let 's consider an example . Say , Rust is throwing a pointer ( to a string ) which Python is gon na catch.In Rust , ( I 'm just sending the pointer of ...
How to stop memory leaks when using ` as_ptr ( ) ` ?
Python : I find it annoying that I ca n't clear a list . In this example : The second time I initialize a to a blank list , it creates a new instance of a list , which is in a different place in memory , so I ca n't use it to reference the first , not to mention it 's inefficient.The only way I can see of retaining the...
Clearing a list
Python : Say I have one large string and an array of substrings that when joined equal the large string ( with small differences ) .For example ( note the subtle differences between the strings ) : How can I best align the strings to produce a new set of sub strings from the original large_str ? For example : Additiona...
How can I find the best fit subsequences of a large string ?
Python : I have a program written with Python 3.7.4 on Windows that opens web pages in a browser . It displays the default browser and gives the user the chance to change which browser they want to use to open programs with.The default browser is detected when the program is initialised using this technique : And links...
How to override the default browser selection in Windows 7 when opening webppages with Python
Python : I have been working on my project Deep Learning Language Detection which is a network with these layers to recognise from 16 programming languages : And this is the code to produce the network : So my last language class is SQL and in the test phase , it can never predict SQL correctly and it scores 0 % on the...
Keras network can never classify the last class
Python : When I compile my code from setup.py , it ca n't find the C++11 include file < array > - but C++11 compiler features do work.When I paste the same command line that setup.py generates into my shell , it all compiles perfectly well ( ! ) Code demonstrating this behavior can be seen here and is also pasted below...
Cython build ca n't find C++11 STL files - but only when called from setup.py
Python : I need to randomly pick an n-dimensional vector with length 1 . My best idea is to pick a random point in the sphere an normalize it : The only problem is the volume of an n-ball gets smaller as the dimension goes up , so using a uniform distribution from random.random takes very long for even small n like 17 ...
Computationally picking a random point on a n-sphere
Python : My dataframe looks like this : and I want : ie I have only 1 column that values differs and I want to create a new dataframe with columns added when new values are observed . Is there an easy way to do this ? <code> pd.DataFrame ( [ [ `` t1 '' , '' d2 '' , '' e3 '' , '' r4 '' ] , [ `` t1 '' , '' d2 '' , '' e2 ...
Create a new column only if values differ
Python : Using Cython , I am trying to convert a Python list to a Cython array , and vice versa . The Python list contains numbers from the range 0 - 255 , so I specify the type of the array as an unsigned char array . Here is my code to do the conversions : The problem lies in the fact that pieces of garbage data are ...
Extra elements in Python list
Python : I 've had to do some introspection in python and it was n't pretty : To get something likeIn our debugging output.I 'd ideally like to prepend anything to stderr with this sort of information -- Is it possible to change the behaviour of print globally within python ? <code> name = sys._getframe ( 1 ) .f_codena...
How do I do monkeypatching in python ?
Python : With Python 3.5 on OS X 10.10.4 , I get spurious ] characters in the output syslog messages . This can be seen with the following sample program : If I run this , I see syslog output like this : ( Note the spurious ] character after Test ) .If I change the formatter string slightly to remove the initial [ char...
Why do I get a spurious ' ] ' character in syslog messages with Python 's SysLogHandler on OS X ?
Python : Hi I have following code snippet which gives KeyError . I have checked other links specifying make __init__ call to Ordered Dict which I have done . But still no luck.Error : <code> from collections import OrderedDictclass BaseExcelNode ( OrderedDict ) : def __init__ ( self ) : super ( BaseExcelNode , self ) ....
KeyError : '_OrderedDict__root ?
Python : I have written an extension module that uses C++ function pointers to store sequences of function calls . I want to 'run ' these call sequences in separate processes using python 's multiprocessing module ( there 's no shared state , so no synchronization issues ) .I need to know if function pointers ( not dat...
Do function pointers remain valid across processes ?
Python : I 've read about this cool new dictionary type , the transformdictI want to use it in my project , by initializing a new transform dict with regular dict : which succeeds but when I run this : I get : How would you suggest to execute the transform function on the parameter ( regular ) dict when creating the ne...
python - Executing transform function on parameter dict when creating new transformdict
Python : BackgroundWe are working in Python3.4 / Django1.8.4 and we are witnessing a strange phenomenon with respect to our user model , and specifically the timezone field of this model.Every so often when we are making migrations the new migration file will include an operation to alter said timezone field , but all ...
Django detecting redundant migrations repetitively
Python : How do we read a file ( non-blocking ) and print it to the standard output ( still non-blocking ) ? This is the esiest way I can think of but it leaves you with a feeling there must be a better way . Something exposing some LineReceiver - like line by line modification - functionality would be even more prefer...
Reading file to stdout with twisted
Python : I have few experience with languages like Python , Perl and Ruby , but I have developed in Smalltalk from some time . There are some pretty basic Smalltalk classes which are very popular and cross-Smalltalk implementation : Which classes would be the equivalent or valid semantic replacements in Python , Perl a...
Collections and Stream classes equivalences between Smalltalk , Perl , Python and Ruby
Python : I was wrestling with a weird `` UnboundLocalError : local variable referenced before assignment '' issue in a multi-submodule project I am working on and slimmed it down to this snippet ( using the logging module from standard library ) : Which has this output ( I tried python 2.7 and 3.3 ) : Apparently the pr...
python import inside function hides existing variable
Python : Update : I 've noticed that entities are saved ( and available at the Datastore Viewer ) when I save them using views ( and the create_object function ) . But when I use shell ( manage.py shell ) to create and save new entity it is n't commited to the storage ( but still can be seen in Tes.objects.all ( ) ) .I...
Saving entities in django-nonrel with google appengine
Python : Is there a way to trick argparse into accepting arbitrary numeric arguments like HEAD ( 1 ) ? is equivalent to My current approach is to use parse_known_args ( ) and then handle the remainder , but I 'd wish there was something a tad more elegant . <code> head -5 test.txt head -n 5 test.txt
python argparse to handle arbitrary numeric options ( like HEAD ( 1 ) )
Python : I create a package connecting to other libraries ( livelossplot ) . It has a lot of optional dependencies ( deep learning frameworks ) , and I do n't want to force people to install them.Right now I use conditional imports , in the spirit of : However , it means that it imports big libraries , even if one does...
Conditional import in Python when creating an object inheriting from it
Python : I am a little confused by the object model of Python . I have two classes , one inherits from the other.What I am trying to do is not to override the __init__ ( ) method , but to create an instance of atom that will have attributes symbol and identifier.Like this : Thus I want to be able to access Atom.identif...
Understanding objects in Python
Python : If i have dataset like this : If we sum that salary column then we will get 316000I really want to know how much person who named 'alexander , smith , etc ' ( in distinct ) makes in salary if we sum all of the salaries from its splitting name in this dataset ( that contains same string value ) .output : as we ...
pandas : Group by splitting string value in all rows ( a column ) and aggregation function
Python : I am trying to create a schema for documents that have dependencies that reference fields higher up in the document . For example : What I 'm struggling with here is enforcing the dependency between build-steps.needs-some-package and packages.some-package . Whenever build-steps contains `` needs-some-package '...
How can a Cerberus dependency reference a field higher up in the document ?
Python : I am a former Excel power user repenting for his sins . I need help recreating a common calculation for me.I am trying to calculate the performance of a loan portfolio . In the numerator , I am calculating the cumulative total of losses . In the denominator , I need the original balance of the loans included i...
Conditional Cumulative Sums in Pandas
Python : I have the following data structures in numpy : My goal is to take each entry i in b , find the x , y coordinates/index positions of all values in a that are < = i , then randomly select one of the values in that subset : This `` works '' , but I 'd like to vectorize the sampling operation ( i.e . replace the ...
Numpy : Vectorize np.argwhere
Python : The following is in python 2.7 with MySQLdb 1.2.3.I needed a class wrapper to add some attributes to objects which did n't support it ( classes with __slots__ and/or some class written in C ) so I came out with something like this : I was expecting that the dir ( ) builtin called on my instance of Wrapper shou...
What kind of python magic does dir ( ) perform with __getattr__ ?
Python : Need help figuring out an 8-bit checksum . The data is 132byte vectors . I thought I had the checksum figured out as I am able to transfer ~30kb of data before I hit the last segment of data shown blow which the checksum fails on . Its off by one.Output : <code> d1 = [ 0x00 , 0x00 , 0xff , 0x00 , 0x00 , 0x44 ,...
8-bit checksum is off by one
Python : I 'm trying to parse a webpage using lxml and I 'm having trouble trying to bring back all the text elements within a div . Here 's what I have so far ... As of now `` foo '' brings back an empty list [ ] . Other pages bring back some content , but not all of the content that is in tags within the < div > . Ot...
What am I doing wrong ? Parsing HTML using lxml
Python : Hoping someone can help me here.I 'm very new to Python , and I 'm trying to work out what I 'm doing wrong.I 've already searched and found out that that Python variables can be linked so that changing one changes the other , and I have done numerous tests with the id ( ) function to get to grips with this co...
Python : copying a list within a list
Python : I am trying to use this code to find candidates for rsa by brute force it seems like it should work but it does n't can anyone help me out ? z = ( p − 1 ) ( q − 1 ) for the calculation of z is used prior to thiswith p = 47 and q = 59 , e = 17 and d = 157 but after the program runs it finds no matches but it sh...
Python gcd calulation of rsa
Python : In python , how can I split a long list into a list of lists wherever I come across '- ' . For example , how can I convert : to Many thanks in advance . <code> [ ' 1 ' , ' a ' , ' b ' , ' -- - ' , ' 2 ' , ' c ' , 'd ' , ' -- - ' , ' 3 ' , '123 ' , ' e ' , ' -- - ' , ' 4 ' ] [ [ ' 1 ' , ' a ' , ' b ' ] , [ ' 2 ...
a list > a list of lists
Python : I try to capture fragments of string that looks like % a , % b , etc . and replace them with some values . Additionally , I want to be able to escape % character by typing % % .In an example string % d % % f % x % % % g I want to match % d % % f % x % % % g ( % d , % x , % g ) .My regular expression looks like...
Previous group match in Python regex
Python : We have numbers in a string like this : We want to sort this and return : ( only unique numbers ! ) How to do it in ONE line ? <code> numbers = `` 1534423543 '' `` 1,2,3,4,5 ''
sort numbers in one line
Python : Let 's say we have a n x n matrix . Taking n=4 as example : This is what I want to achieve : When cut=1 , given from function parameter , the matrix becomes : When cut=3 : When cut=5 : As we can see , the diagonal is being cut like a forward-slash , everything under the first slash would be zeros out.I am usin...
Zero out matrix higher diagonal using numpy
Python : I hope this is n't a stupid question but I found some code where they imported classmethod and some code where they do n't so there is difference ? I 'm using python 3.6 but the code originally I think was for python 2.7 ( it used from __builtin__ import ) <code> import unittestfrom selenium import webdriverfr...
Import or not to import classmethod ?
Python : I enjoy python one liners with -c , but it is limited when indentation is needed.Any ideas ? <code> python -c `` for x in range ( 1,10 ) print x ''
How can I make this one-liner work in DOS ?
Python : In addition to pre-existing warning categories , users can define their own warning classes , such as in the code below : When invoking Python , the -W flag controls how to filter warnings . But when I try to get it to ignore my freshly minted warning category , I 'm told the filter is ignored : How can I use ...
Filtering based on custom warning categories
Python : Given this snippet of code : I would expect it to print [ 0 , 1 , 2 ] , but instead it prints [ 2 , 2 , 2 ] . Is there something fundamental I 'm missing about how lambdas work with scope ? <code> funcs = [ ] for x in range ( 3 ) : funcs.append ( lambda : x ) print [ f ( ) for f in funcs ]
Python lambdas and scoping
Python : Referring to the Django Book , chapter 3 : What determines why one thing is included as a string , and another as regular variable ? Why admin.site.urls but not 'admin.site.urls ' ? All other includes are included as strings ... I see no logical pattern here . <code> from django.conf.urls import patterns , inc...
Why do some includes in Django need strings , and others variable names ?
Python : How can I make a function that will create a list , increasing the amount of numbers it contains each time to a specified value ? For example if the max was 4 , the list would containIt 's difficult to explain what I 'm looking for , but from the example I think you 'll understand ! Thanks <code> 1 , 2 , 2 , 3...
Create List With Numbers Getting Greater Each Time Python
Python : I 'd like to sort a 2D list where each `` row '' is of size 2 , like that for exampleThese rows represent ranges in fact , so Its always [ a , b ] where a < = bI want to sort it exactly this way , each element of the list being a 2-list , I 'd have ( by order of priority ) : [ a1 , b1 ] compared to [ a2 , b2 ]...
Sorted function using compare function
Python : I 'm trying to free myself of JMP for data analysis but can not determine the pandas equivalent of JMP 's Split Columns function . I 'm starting with the following DataFrame : I can handle some of the output scenarios of JMP 's function using the pivot_table function , but I 'm stumped on the case where the Va...
pandas DataFrame reshape by multiple column values
Python : I have a list of lists over which I need to iterate 3 times ( 3 nested loops ) I can achieve this using product of product as followsThe output looks as followsIts a tuple of tuple . My questions areIs this a good approach ? If so , what is the bestway to unpack theoutput of the product val into 3 separate var...
Python itertools : Best way to unpack product of product of list of lists
Python : As I learn Python I have encountered some different styles . I am wondering what the difference between using `` else '' is as opposed to just putting code outside of the `` if '' statement . To further explain my question , here are two blocks of code below . I understand that this is returning False if x ! =...
What is the difference between `` else : return True '' and just `` return True ? ''
Python : I saw this example at pythontips . I do not understand the second line when defaultdict takes an argument `` tree '' and return a `` tree '' .After I run this code , I checked the type of some_dict <code> import collectionstree = lambda : collections.defaultdict ( tree ) some_dict = tree ( ) some_dict [ 'color...
do n't understand this lambda expression with defaultdict
Python : I know that dicts and sets are n't ordered , so equal sets or dicts may print differently ( all tests with Python 3.6.1 ) : And I just realized that pprint ( “ pretty-print ” ) sorts dicts but not sets : It 's documentation also says `` Dictionaries are sorted by key before the display is computed '' . But why...
pprint sorting dicts but not sets ?