lundi 29 juin 2015

SciPy package on Fedora 20: ImportError: cannot import name anderson_ksamp


I'm trying to run a Python package called D3E for single-cell differential gene expression. I have Python 2.7.5 on Fedora 20. I just installed the SciPy package using the instructions here:

sudo yum install numpy scipy python-matplotlib ipython python-pandas sympy python-nose

However, when I try to run the script, I keep getting a SciPy error:

bash-4.2$ python D3ECmd.py ~/Documents/geneExpressionTable.txt ~/outputFile.txt cellType1 cellTYpe2 -n=0, -z=1

    Traceback (most recent call last):
      File "D3ECmd.py", line 34, in <module>
        from D3EUtil import readData, getParamsBayesian, getParamsMoments, cramerVonMises, logStatus, goodnessOfFit, distributionTest
      File "/home/user/Software/D3E/D3EUtil.py", line 36, in <module>
        from scipy.stats import gmean, ks_2samp, anderson_ksamp
    ImportError: cannot import name anderson_ksamp

What would you recommend I try to fix this error?

Thanks.


How to place text above hatched zone using matplotlib?


How to place text above hatched zone using matplotlib? An example is shown below. enter image description here Below are my sample code for easy understanding

from pylab import *
fig=figure()
x=array([0,1])
yc=array([0.55,0.48])


yhc=array([0.55,0.68])

yagg=array([0.45,0.48])

plot(x,yc,'k-',linewidth=1.5)
plot(x,yhc,'k-',linewidth=1.5)
plot(x,yagg,'k-',linewidth=1.5)

xticks(fontsize = 22)
yticks(fontsize = 22)
ylim(0,1)
ax=axes()


p=fill_between(x, yc, yhc,color="none")

from matplotlib.patches import PathPatch 
for path in p.get_paths(): 
    p1 = PathPatch(path, fc="none", hatch="/") 
    ax.add_patch(p1) 
    p1.set_zorder(p.get_zorder()-0.1) 

props = dict(boxstyle='round',facecolor='white', alpha=1,frameon='false')
text(0.6, 0.55, 'hi',fontsize=22)
fig.savefig('vp.png', transparent=True,bbox_inches='tight')

enter image description here

The hatched zone really makes it hard to see the text.


Adding labels iteratively to Tkinter form


I am trying to iteratively add fields to a Tkinter form by looping through a list. The form generates with no errors, but the labels are not present. What is going on here?

from Tkinter import *
class User_Input:

    def __init__(self, parent):
        fields = ['Text Box 1', 'Text Box 2']
        GUIFrame =Frame(parent, width=300, height=200)
        GUIFrame.pack(expand=False, anchor=CENTER)
        field_index = 10
        for field in fields:
            self.field = Entry(text=field)
            self.field.place(x=65, y = field_index)
            field_index += 25

        self.Button2 = Button(parent, text='exit', command= parent.quit)
        self.Button2.place(x=160, y=60)

root = Tk()
MainFrame =User_Input(root)

root.mainloop()


Viewing the content of a Spark Dataframe Column


I'm using Spark 1.3.1.

I am trying to view the values of a Spark dataframe column in Python. With a Spark dataframe, I can do df.collect() to view the contents of the dataframe, but there is no such method for a Spark dataframe column as best as I can see.

For example, the dataframe df contains a column named 'zip_code'. So I can do df['zip_code'] and it turns a pyspark.sql.dataframe.Column type, but I can't find a way to view the values in df['zip_code'].


Python suds attirbuteError: Fault instance has no attribute 'detail'


Howdie do,

I've created a package class that sets some default values such as shipper, consignee, packages and commodities.

The issue is that when I go to call the method shippackage that is a suds client, I receive the error:

AttributeError: Fault instance has no attribute 'detail'

The first file listed below is my test file which sets the necessary dictionaries:

import ship

# Create a new package object
package1 = ship.Package('TX')

# Set consignee
package1.setconsignee('Dubs Enterprise', 'JW', '2175 14th Street', 'Troy', 'NY', '12180', 'USA')

# Set default packaging
package1.setdefaults('CUSTOM', '12/12/15', 'oktoleave')

# Add commodity description with each package
package1.addpackage('12.3 lbs', '124.00')
package1.addcommodity('This is package number 1', '23.5 lbs')

# Add commodity list to defaults dictionary
package1.setcommoditylist()

# Add package list to packages dictionary
package1.setpackagelist()
package1.shippackage()

The module that is being imported is the following:

from suds.client import Client
from suds.bindings import binding

binding.envns = ('SOAP-ENV', 'http://ift.tt/18hkEkn')
client = Client('http://localhost/ProgisticsAMP/amp.svc/wsdl', headers={'Content-Type': 'application/soap+xml'},
                faults=False)


class Package(object):

    def __init__(self, shipper):
        self.commoditylist = []
        self.commodityContents = {}
        self.consignee = {}
        self.defaults = {}
        self.packagelist = []
        self.packages = {}

        self.defaults['shipper'] = shipper

    def setconsignee(self, company, contact, address, city, state, zip, country):
        self.consignee['company'] = company
        self.consignee['contact'] = contact
        self.consignee['address1'] = address
        self.consignee['city'] = city
        self.consignee['stateProvince'] = state
        self.consignee['postalCode'] = zip
        self.consignee['countrySymbol'] = country

        self.defaults['consignee'] = self.consignee

    def setdefaults(self, packaging, shipdate, deliverymethod):
        self.defaults['packaging'] = packaging
        self.defaults['shipdate'] = shipdate
        self.defaults['deliveryMethod'] = deliverymethod

    def addcommodity(self, description, unitweight):
        commodity = {}
        commodity['description'] = description
        commodity['unitWeight'] = {'value': unitweight}

        self.commoditylist.append(commodity)

    def addpackage(self, weight, declarevalue):
        package = {}
        package['weight'] = {'value': weight}
        package['declaredValueAmount'] = {'amount': declarevalue, 'currency': 'USD'}
        self.packagelist.append(package)

    def setcommoditylist(self):
        self.commodityContents = {'item': self.commoditylist}

        self.defaults['commodityContents'] = self.commodityContents

    def setpackagelist(self):
        self.packages = {'item': self.packagelist}

    def shippackage(self):
        print self.defaults
        print self.packages

        # print client
        response = client.service.Ship('CONNECTSHIP_UPS.UPS.GND', self.defaults, self.packages, True, 'release')
        result = response.result
        print result

Within the shippackage method, I print self.packages and self.defaults and confirm that they have data within them before I call

client.service.Ship()

So I know it does have values within it before I call the client.service.Ship()

Am I missing something here? Why won't it take the defaults and packages dictionary that I've set?


How can I extract all satellite adjectives from WordNet NLTK and save them to a text file? (Python))


I am trying to extract all satellite adjective synsets from WordNet and save them to a text file. Note that satellite adjectives are denoted as 's' in the synset name, e.g., "(fantastic.s.02)". The following is my code:

    def extract_sat_adjectives():
      sat_adj_counter = 0
      sat_adjectives = []
      for i in wn.all_synsets():
        if i.pos() in ['s']:
          sat_adj_counter +=1
          sat_adjectives = sat_adjectives + [i.name()]
   fo = open("C:\\Users\\Nora\\Desktop\\satellite_adjectives.txt", "wb")
   for x in sat_adjectives:
     fo.write("%s\n" % x)
   fo.close()


extract_sat_adjectives()

The error I get is:

TypeError: 'str' does not support the buffer interface  

How can I save the adjectives to the text file? Thanks in advance.


Python goto text file line without reading previous lines


I am working with a very large text file (tsv) around 200 million entries. One of the column is date and records are sorted on date. Now I want to start reading the record from a given date. Currently I was just reading from start which is very slow since I need to read almost 100-150 million records just to reach that record. I was thinking if I can use binary search to speed it up, I can do away in just max 28 extra record reads (log(200 million)). Does python allow to read nth line without caching or reading lines before it?


variable with tree structure save to txt file python


****this code reads the structure tree from the cad software CATIA. i need to save the tree in a txt file but it doesn't work ... thanks for help.****

already tried:

import pickle
file = open('dump.txt', 'w')
pickle.dump(tree, file)
file.close()




from catialib import *
a=CatiaLibrary()
a.OpenFile("Mastermodell.CATPart")
tree=a.ReadTree(show=False)
print (tree)
a.CloseWindow()


Python Django: Time Zone Conversion


I'm parsing an XML file that has the dates in GMT time. It's my first time working with timezones so I'm having some difficulty displaying the right time. In the XML file the date is like this.

2015-06-29 23:05

I set up my model with a basic datetime field like this:

date = models.DateTimeField()

...my settings.py has:

 USE_TZ = True
 TIME_ZONE = 'America/Toronto'

However when I display the time via views it shows 3:05. Not exactly sure what I'm suppost to do next.


How to check for certain ANSI Hex code in a string python


So I'm getting an error when I parse data from an .csv file and insert the data into a database. The code from the excel file has some characters that aren't compatible for UTF8 encoding. I'm looking for a way to replace these characters so that I can insert it into the databases.

One example special character is 0x92 which is the double dash in microsoft documments. Here's the psuedocode I'm looking for

special_character = 0x92
if special_character in word:
    replace special_character with "" in word

here's the error I'm getting:

 [Mon Jun 29 13:26:35.423226 2015] [wsgi:error] [pid 12439:tid 
 140199602177792] [remote 10.0.2.2:188] DataError: (psycopg2.DataError) 
 invalid byte sequence for encoding "UTF8": 0x92

I know there has to be an issuing with the formatting, but I'm not sure what exactly to change


Incorrect results with Sympy when utilizing (numpy's) floats


I am trying to calculate a velocity tensor from a time dependent rotationmatrix RE(t) (Namely the earth rotation at latitude 48.3°). This is achieved by determining the skew symmetric matrix SE(t) = dRE(t)/dt * RE.T. I am obtaining incorrect results when utilizing a float instead of a Sympy expression, as shown in the following example:

from IPython.display import display
import sympy as sy

sy.init_printing()  # LaTeX like pretty printing for IPython


def mk_rotmatrix(alpha, coord_ax="x"):
    """ Rotation matrix around coordinate axis """
    ca, sa = sy.cos(alpha), sy.sin(alpha)
    if coord_ax == "x":
        return sy.Matrix([[1,  0,   0],
                          [0, ca, -sa],
                          [0, sa, +ca]])
    elif coord_ax == 'y':
        return sy.Matrix([[+ca, 0, sa],
                          [0,   1,  0],
                          [-sa, 0, ca]])
    elif coord_ax == 'z':
        return sy.Matrix([[ca, -sa, 0],
                          [sa, +ca, 0],
                          [0,    0, 1]])
    else:
        raise ValueError("Parameter coord_ax='" + coord_ax +
                         "' is not in ['x', 'y', 'z']!")


t, lat = sy.symbols("t, lat", real=True)  # time and latitude
omE = 7.292115e-5  # rad/s -- earth rotation rate (15.04107 °/h)
lat_sy = 48.232*sy.pi/180  # latitude in rad
lat_fl = float(lat_sy)  # latitude as float
print("\nlat_sy - lat_fl = {}".format((lat_sy - lat_fl).evalf()))

# earth rotation matrix at latitiude 48.232°:
RE = (mk_rotmatrix(omE*t, "z") * mk_rotmatrix(lat - sy.pi/2, "y"))
# substitute latitude with sympy and float value:
RE_sy, RE_fl = RE.subs(lat, lat_sy), RE.subs(lat, lat_fl)

# Angular velocity in world coordinates as skew symmetric matrix:
SE_sy = sy.simplify(RE_sy.diff(t) * RE_sy.T)
SE_fl = sy.simplify(RE_fl.diff(t) * RE_fl.T)

print("\nAngular velocity with Sympy latitude ({}):".format(lat_sy))
display(SE_sy)  # correct result
print("\nAngular velocity with float latitude ({}):".format(lat_fl))
display(SE_fl)  # incorrect result

The result is:

calculation results

For the float latitude the result is totally wrong in spite of the difference of only -3e-17 to the Sympy value. It is not clear to me, why this happens. Numerically, this calculation does not seem to be problematic.

My question is, how to work around such deficits. Should I avoid mixing Sympy and float/Numpy data types? They are quite difficult to detect for more complex settings.

PS: The Sympy version is 0.7.6.


Why BeautifulSoup and lxml don't work?


I'm using mechanize library to log in website. I checked, it works well. But problem is i can't use response.read() with BeautifulSoup and 'lxml'.

#BeautifulSoup
response = browser.open(url)
source = response.read()
soup = BeautifulSoup(source)  #source.txt doesn't work either
for link in soup.findAll('a', {'class':'someClass'}):
    some_list.add(link)

This doesn't work, actually doesn't find any tag. It works well when i use requests.get(url).

#lxml->html
response = browser.open(url)
source = response.read()
tree = html.fromstring(source)  #souce.txt doesn't work either
print tree.text
like_pages = buyers = tree.xpath('//a[@class="UFINoWrap"]')  #/text() doesn't work either
print like_pages

Doesn't print anything. I know it has problem with return type of response, since it works well with requests.open(). What could i do? Could you, please, provide sample code where response.read() used in html parsing?

By the way, what is difference between response and requests objects?

Thank you!


Odoo 8 - get products many2many attribute id (taxes_id) in python


I am trying to get the taxes_id from product template which is a many2many attribute field. I think I somehow need to read an array?

Can anyone point me in the right direction how to read the id?

My tests where: bla = self.pool.get('product.template').browse(cr, uid, id, context) bla.taxes_id

But not working...


Script to send json using POST/REST and requests in python doesn't work


I'm trying to send a json in POST method using REST, but i got error:

    "Could not parse JSON data: Expecting value: line 1 column 1 
    (char 0)", "status": 500, "type": "ValueError", 
    "request": {"client_addr": "127.0.0.1", 
    "user_agent": "python-requests/2.3.0 CPython/3.4.2 Linux/3.16.0-41-generic", 
    "method": "POST", "path": "/api/adley/doc"}}
    )

I'm trying to fix, use a json.dumps or json.loads, but nothing seems to work.

I need to send one key and two values. Here is the base:

   {
metadata: {
   idx_exp: false,
   idx_exp_time: 0,
   file_ext: false,
   password: "",
   description: "base de teste",
   idx_exp_url: "",
   model: {
      item: "Text"
   },
   dt_base: "29/06/2015 14:47:10",
   name: "adley",
   id_base: 5,
   file_ext_time: 0,
   },
   content: [
   {
    field: {
          required: false,
          multivalued: false,
          alias: "Texto",
          datatype: "Text",
          name: "item",
          indices: [
               "Ordenado"
          ],
          description: "placeholder"
         }
     }
  ]
}

My to send a post script:

import requests, json
url = "http://ift.tt/1SYFCtA"
json_data = {'value':{'item':'test'}}
response = requests.post(url, params=json_data)
print(response.text)

I can't see what's wrong with my script


Retrieve the reviews of a particular user on Yelp using Python


Given a user ID on YELP.com, how can I fetch the reviews written by that person? PS, I'm using yelpapi package in Python. Any help would be appriciated,


Unable to extract ZIP file created with Python using zipfile.ZIP_DEFLATED compression method


I have two programs (one in Java and one in Python) that ZIP a folder, upload it to a WebServer and trigger a UNZIP method on them.

The Java version of the program works without issues and the file is extracted on the server without problems.

Here I'm using the ArchiveStreamFactory class i.e. new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, this.currentOutputStream);

The Python version only works if I use zipfile.ZIP_STORED method (which does not compress the file). If I use the zipfile.ZIP_DEFLATED method I get internal server error.

I don't have access to the server so for this I can only rely on what I'm able to figure out on my side.

The Java program does seem to use the ZIP_DEFLATED method also as the archive is compressed (smaller) and not just stored.

I've also run zipinfo on the both archives (the one created with Java and the one with Python with DEFLATE - which doesn't work) too see what's different.

Here's the output:

# Java
-rw----     2.0 fat    14398 bl defN  4-Jun-15 13:55 somefile.txt

# Python
-rw-r--r--  2.0 unx      183 b- defN 28-Jun-15 21:39 someotherfile.txt

Both seem to be compressed with DEFLATE (defN) method so why does the archive generated by Java works while the one generated by Python doesn't?


Would anyone be willint to critique my unfinished script? [on hold]


I am working on a script that selects different amenities that fall into a country boundary and export into their own feature class. I have print statement just for error checking and plan to remove them once the script works. I also have to put in a loop for the amenities, but have not figured that out yet.

import arcpy
arcpy.env.overwriteOutput = True
# Set up country and amenity to examine.
amenity = ['school', 'hospital', 'place of worship']
country = 'El Salvador'

# Set up paths to the datasets I want to use.
countries = r"C:\WCGIS\Geog485\Lesson3\Project 3\CentralAmerica.shp"
points = r"C:\WCGIS\Geog485\Lesson3\Project 3\OSMpoints.shp"

# Set up the workspace where I want to save output.
arcpy.env.workspace = r"C:\WCGIS\Geog485\Lesson3\Project 3"

# Create a feature layer of the country I want to work with.
try:
    countrySelection = '"NAME" ='+"'"+ country + "'"
    arcpy.MakeFeatureLayer_management(countries, 'country',      countrySelection)

except:
    print ("An error occurred one")

# Create feature layers of  the amenities.
try:
    amenitySelection = '"amenity" ='+"'" + amenity +"'"
    arcpy.MakeFeatureLayer_management(points, 'schoolpoints',  amenitySelection)
    for amenity in amenity:
        ## Not sure how to do this.
    except:
    print ("An error occured two")

# Select the amenity of interest within the country.
try:
    arcpy.SelectLayerByLocation_management('schoolpoints', "WITHIN", 'country')

except:
    print ("An error occured three")
    # Create an output path preping to run the Copy Features.
outputFile = amenity + ".shp"
arcpy.CopyFeatures_management('schoolpoints', outputFile)

# Add a new field labeled "Source", populate the field with "OpenStreetMap".
arcpy.AddField_management(points, "Source", "TEXT", field_length =15)

with arcpy.da.UpdateCursor(points, ("Source",)) as cursor:
    row[0] = "OpenStreetMap"

# Delete feature classes no longer needed.
arcpy.Delete_management("countries")
arcpy.Delete_management("points")


Using DataFrame to get matrix of identifiers


I am an R user who is new to python. I have some data

dat1=DataFrame({'user_id':['a1','a1','a4','a3','a1','a15', 'a8', 'a15'      ,'a1', 'a5'],
 'Visits':[1,4,2,1,3,1,1,8,1,9],'cell': [14,21,14,14,19,10,18,17,10,11], 
 'date': ['2011-01-05', '2011-01-05', '2011-01-12', '2011-01-12', '2011-01-12',   '2011-01-12', '2011-01-02', '2011-01-19', '2011-01-19', '2011-01-19' ] })




 dat1['date']=pd.to_datetime(dat1['date'])

 dat2=dat1.sort_index(by='date')    

This gives me a DataFrame of the form

Visits  cell     date     user_id
   1    18   2011-01-02      a8
   1    14   2011-01-05      a1
   4    21   2011-01-05      a1
   2    14   2011-01-12      a4
   1    14   2011-01-12      a3
   3    19   2011-01-12      a1
   1    10   2011-01-12     a15
   8    17   2011-01-19     a15
   1    10   2011-01-19      a1
   9    11   2011-01-19      a5

I want to create a DataFrame such that each column is identified with a unique user_id and each row is a unique date. Each cell contains a 0 or 1 depending on whether the user_id and the date share a row in the original DataFrame. In R

I would use sapply and a user defined function for this operation, but in Python I am struggling to find a solution.

With my array of user_ids denoted as

user_names= dat2['user_id'].unique()

My final DataFrame should be of the form

a8 a1 a4 a3 a15 a5
1  0  0  0  0  0
0  1  0  0  0  0
0  1  1  1  1  0
0  1  0  0  1  1


How to insertmany from a cursor using Pymongo?


I am interested in using a cursor to duplicate a database from one mongod to another. I want to limit the amount of insert requests sent so instead of inserting each document in the cursor individually I want to do an insert_many of each cursor batch.

Is there a way to do this in pymongo/python?

I have tried converting the cursor to a list and then calling insert_many and this works, but if the collection is over the amount of ram that I have then it won't work.

Any ideas on how to grab a batch from a cursor and convert it to a list would be appreciated

Thanks!


Installing pzmq with Cygwin


For two days I have been struggling to install pyzmq and I am really not sure what the issue is.

The error message I receive after:

pip install pyzmq

is:

 error: command 'gcc' failed with exit status 1

I have gcc installed.

which gcc
/usr/bin/gcc

Python is installed at the same location. I am really struggling to find a solution.

Edit: Adding to the output from the error, here is the output that describes the error further:

 bundled/zeromq/src/signaler.cpp:62:25: fatal error: sys/eventfd.h: No  such file or directory
  #include <sys/eventfd.h>
                         ^
compilation terminated.
error: command 'gcc' failed with exit status 1

----------------------------------------
Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip- build-INbMj2/pyzmq/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), 
__file__, 'exec'))" install --record /tmp/pip-n8hQ_h-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-INbMj2/pyzmq


Differing Reponse Codes from Django Application


For both GET and POST requests I simply want to print the associated QueryDict in my test view:

if request.method == 'GET':
    print request.GET

if request.method == 'POST':
    print request.POST

When I make requests using both methods I get different response codes. I could use some help.

enter image description here


Combinations between two tuples in Python


I have two tuples:

t1 = ('A', 'B')
t2 = ('C', 'D')

I wonder how to create combinations between tuples, so the result should be:

AC, AD, BC, BD

EDIT

Using

list(itertools.combinations('abcd',2))

I could generate list of combinations for a given string. If I insert tuple instead of string the following error occurs:

TypeError: sequence item 0: expected string, tuple found

Any suggestion how to proceed?


how to add multiple attrs in Django forms


How can I add multiple attributes to an input tag in Django ?

Example: For adding a single attribute I can use this code

email = forms.EmailField(
        widget = forms.TextInput(attrs={'placeholder': 'Email'}))

But if I want to add 'class', 'size' and 'placeholder' attributes then what is the way of doing it in django forms?


How to render combo box text insenstive?


A rather brief question:
How would I make text within a combo box insensitive/diabled, using pygtk (not GTK3)?


Relabel levels in pandas


In a pandas DataFrame I'm trying to relabel the two levels of a variable with one single name but leave the 'Nan' values in the variable untouched.

Below is a reproducible example using a modified version of the 'mtcars' dataset. Here I want to relabel the 'yes' and 'no' levels of the 'am' variable to 'new' for example.

                    mpg   cyl  disp  hp drat    wt  qsec vs  am  
Mazda RX4           21.0  six 160.0 110 3.90 2.620 16.46  0  yes     
Mazda RX4 Wag       21.0  two 160.0 110 3.90 2.875 17.02  0  NaN    
Datsun 710          22.8  six 108.0  93 3.85 2.320 18.61  1  no    
Hornet 4 Drive      21.4  two 258.0 110 3.08 3.215 19.44  1  NaN   
Hornet Sportabout   18.7  six 360.0 175 3.15 3.440 17.02  0  yes  
Valiant             18.1  two 225.0 105 2.76 3.460 20.22  1  NaN   
Duster 360          14.3  two 360.0 245 3.21 3.570 15.84  0  no   

Result would look like this:

                    mpg   cyl  disp  hp drat    wt  qsec vs  am  
Mazda RX4           21.0  six 160.0 110 3.90 2.620 16.46  0  new     
Mazda RX4 Wag       21.0  two 160.0 110 3.90 2.875 17.02  0  NaN    
Datsun 710          22.8  six 108.0  93 3.85 2.320 18.61  1  new    
Hornet 4 Drive      21.4  two 258.0 110 3.08 3.215 19.44  1  NaN   
Hornet Sportabout   18.7  six 360.0 175 3.15 3.440 17.02  0  new  
Valiant             18.1  two 225.0 105 2.76 3.460 20.22  1  NaN   
Duster 360          14.3  two 360.0 245 3.21 3.570 15.84  0  new


How many small squares needed to fill a rectangle?


I am trying to solve a problem on codeforces. I am a beginner and I am just trying to understand how to solve this problem I do not want to copy someone's code.

Requirements are :

There is 1 big rectangle of nm units. (n and m are length and width). And small squares of length a are suppose to fill it up. Its okay to fill a little more are if a squares don't cover the big square (nm) completely.

If n = 6 and m = 6. area of n*m becomes 36 units. and suppose a = 4 then each tile covers 16 units of area.

Now when we lay down small squares on big rectangle it comes to 4 small squares needed to cover big rectangle.

I can easily calculate the area of large rectangle:

l_area = n * m

area of small squares :

s_area = a*a

Now how to calculate the number of small squares needed to cover the big rectangle.

The divide operator does not work for obvious reason.


Texas Hold'em Python [on hold]


I'm having trouble figuring out how to make my program work in the way it is supposed to. I have quite a bit done this far but I'm not sure how to continue on in order to play Texas holdem. Here is some of the information from the assignment that might make helping me easier

"Our game is simplified in two ways:

  1. We only compare categories to determine the winner, not the value of the hands. For example, in a real poker game the winner of hands with exactly one pair would be determined by which pair had the highest card rank. That is, a pair of 10s wins over a pair of 3s. In our game, two hands with exactly one pair is considered a tie with no consideration given to the card ranks.

  2. The Card class ranks an Ace as the lowest card in a suit; whereas traditional poker ranks an Ace as highest. For simplicity, we will keep Aces as the lowest ranked card because we are only comparing categories not values. In particular, the cards 10h, Jh, Qh, Kh, Ah are not considered to make a straight in our game (they would under normal poker rules).

Assignment Specifications

  1. Your program will use the Card and Deck classes found in the file named cards.py. You may not modify the contents of that file: we will test your project using our copy of cards.py. We have included a cardsDemo.py program to illustrate how to use the Card and Deck classes.

  2. Your program will be subdivided into meaningful functions. Use a function for each category (except that “high-card” doesn’t need a function). See hints below.

  3. Your program will display each player’s dealt cards, the community cards, and announce the winner of the hand. Also, your program will display the winning combination (or either of the winning combinations, if a tie) as well as the category of the winning hand (see sample output below). For example, if the winning combination is “four-of-a-kind”, those four cards will be displayed; the fifth card in the hand will not be displayed. The display will be appropriately labeled and formatted.

  4. After each run, the program will prompt the user if they want to see another hand: “do you want to continue: y or n”. The program should continue if user enters “y” or “Y”; otherwise, the program should halt. Also, if there are fewer than 9 cards left in the deck, the program should halt. Do not shuffle between hands; only shuffle at the beginning of the program.

  5. Using dictionaries in this assignment is very useful as you can find how many cards have the same suit, or how many of them have the same rank. Most of my functions used a dictionary that had rank as the key, so I created a separate function to build such a dictionary from a hand.

Hints

  1. There are 9 categories of hands. For each category (except high-card), I wrote a function that would take as an argument a list of 7 cards and return either a sub-list of cards that satisfied that category or an empty list. That design let me use the functions in Boolean expressions since an empty list evaluates to False whereas a non-empty list evaluates to True. Returning a list of cards also allowed me to use functions within functions, e.g., a straight flush must be a flush. Returning a list of cards also made testing easier because I could see not only that the function had found a combination of that type, but I also could easily check that it was correct. By the way, the function to find a straight was the hardest function to write.

  2. Finding a winner is simple: start with the highest category and work your way down the categories in a cascade of “if” and “elif” statements. The result is a long, but repetitive structure. (You do not need to check all possible combinations of hands because you are only trying to find the highest category that a hand fits.)

  3. Think strategically for testing. Custom build a set of hands for testing by creating particular cards, e.g. H1 = [5c, 2c, 5h, 4s, 3d, 2h, 5d] can be used to test for a full house (I had to create each card first, e.g. c1 = cards.Card(5,1) to create the 5c card in H1. It took many lines to create the testing hands, but once built they proved useful.) Test each category function separately using the custom hands you created for testing. For example, result = full_house(H1) should yield a result [5c, 5h, 5d, 2c, 2h].

  4. I found dictionaries useful within functions. Sometimes using the rank as key worked best; other times using the suit as key was best.

  5. In order for sort() and sorted() to work on any data type the less-than operation must be defined. That operation is not defined in the Cards class so neither sort() nor sorted() work on Cards. (We tried to make the Cards class as generic as possible to work with a wide variety of card games, and the ordering of cards considering both rank and suit varies across card games.)"

    import cards
    
    the_deck=cards.Deck()
    the_deck.shuffle()
    
    def deal_cards():
        player1_list=[]
        player2_list=[]
        for i in range( 2 ):
            player1_card= the_deck.deal()
            player2_card= the_deck.deal()
            player1_list.append(player1_card)
            player2_list.append(player2_card)
    
        print("=======Player 1=======")
        print(player1_list)
        print()
        print("=======Player 2=======")
        print(player2_list)
        print()
    
        community_list=[]
        for j in range(5):
            community_cards=the_deck.deal()
            community_list.append(community_cards)
        print("=======Community Cards=======")
        print(community_list)
        print()
    deal_cards()
    
    class poker_hand():
        def __init__(self, card_list):
            self.card_list = card_list
        def __repr__(self):
            short_desc = "Nothing."
            numeral_dict = cards.defaultdict(int)
            suit_dict = cards.defaultdict(int)
            for my_card in self.card_list:
                numeral_dict[my_card.numeral] += 1
                suit_dict[my_card.suit] += 1
            # Pair
            if len(numeral_dict) == 4:
                short_desc = "One pair."
            # Two pair or 3-of-a-kind
            elif len(numeral_dict) == 3:
                if 3 in numeral_dict.values():
                    short_desc ="Three-of-a-kind."
                else:
                    short_desc ="Two pair."
            # Full house or 4-of-a-kind
            elif len(numeral_dict) == 2:
                if 2 in numeral_dict.values():
                    short_desc ="Full house."
                else:
                    short_desc ="Four-of-a-kind."
            else:
                # Flushes and straights
                straight, flush = False, False
                if len(suit_dict) == 1:
                    flush = True
                min_numeral = min([cards.index(x) for x in numeral_dict.keys()])
                max_numeral = max([cards.index(x) for x in numeral_dict.keys()])
                if int(max_numeral) - int(min_numeral) == 4:
                    straight = True
                # Ace can be low
                low_straight = set(("Ace", "2", "3", "4", "5"))
                if not set(numeral_dict.keys()).difference(low_straight):
                    straight = True
                if straight and not flush:
                    short_desc ="Straight."
                elif flush and not straight:
                    short_desc ="Flush."
                elif flush and  straight:
                    short_desc ="Straight flush."
            enumeration = "/".join([str(x) for x in self.card_list])
            return "{enumeration} ({short_desc})".format(**locals())
    
    

Does Django ManyToManyField create table with a redundant index?


If I have a model Foo that has a simple M2M field to model Bar:

class Foo(Model):
    bar = ManyToManyField(Bar)

Django seems to create a table foo_bar which has the following indices:

index 1: primary, unique (id)
index 2: unique (foo_id, bar_id)
index 3: non_unique (foo_id)
index 4: non_unique (bar_id)

I recall from my basic knowledge of SQL, that if a query needs to look for conditions on foo_id, index 2 would suffice (since the left-most column can be used for lookup). index 3 seems to be redundant.

Am I correct to assume that index 3 does indeed take up index space while offering no benefit? That I'm better off using a through table and manually create a unique index on (foo_id, bar_id), and optionally, another index on (bar_id) if needed?


Django Get Latest Entry from Database


I've got 2 questions, but they are related to the same topic.

I know how to retrieve data from a for loop using template tags

{% for status in status %}

    <tr>
        <td>{{ status.status}}</td>
    </tr>

{% endfor %}

However when I want to retrieve a single object i get an error even when i use:

po = Status.objects.latest('id')

and remove the for loop.

I get:

'Status' object is not iterable

My questions are:

  1. How can I get the latest entry from the database for a given model?
  2. How can I setup my templates tags to allow for just a single record?

Performance monitoring/profiling for python server process (similar to New Relic)


Is there a tool/service that can automatically and perpetually instrument and profile python server processes? I'm thinking about processes like Celery or RQ workers? I'd like to get method-level performance timers averaged across multiple similar job executions.

New Relic will do this for Celery but it only has experimental support for RQ. Unfortunately it's not recommended for short lived tasks, and we have lots of those.

I'm aware of cProfile and line_profiler, but I'm hoping to find a service I can use in production where I don't have to capture the output and aggregate it myself. While a permanent service/tool would be preferred, if there's a tool that will aggregate the output of multiple cProfile runs that might work as well.

BTW the processes are running on Heroku non-web worker dynos.


install python module in custom directory on windows


I am trying to install pip on my company's windows machine, but I don't have admin permission, so I have to install it else where.

When I set the path in prefix:

python setup.py install --prefix="C:\Developers\lib"

There goes the error:

running install
Checking .pth file support in C:\Developers\pythonLib\Lib\site-packages\
C:\Program Files (x86)\Python27\pythonw.exe -E -c pass
TEST FAILED: C:\Developers\pythonLib\Lib\site-packages\ does NOT support .pth files
error: bad install directory or PYTHONPATH

You are attempting to install a package to a directory that is not
on PYTHONPATH and which Python does not read ".pth" files from.  The
installation directory you specified (via --install-dir, --prefix, or
the distutils default setting) was:
    C:\Developers\lib\Lib\site-packages\
and your PYTHONPATH environment variable currently contains:

''

Here are some of your options for correcting the problem:

* You can choose a different installation directory, i.e., one that is
  on PYTHONPATH or supports .pth files

* You can add the installation directory to the PYTHONPATH environment
  variable.  (It must then also be on PYTHONPATH whenever you run
  Python and want to use the package(s) you are installing.)

* You can set up the installation directory to support ".pth" files by
  using one of the approaches described here:

  http://ift.tt/KJcLvw

Please make the appropriate changes for your system and try again.

Do you have any suggestions? Thanks!

UPDATE:

I don't have the permission to edit environment variables, so I thought I cannot edit the Pythonpath. but I noticed that I can use

set PYTHONPATH=C:\Developers\pythonLib\Lib\site-packages

, and then

python setup.py install --prefix="C:Developers\pythonLib"

to solve the issue.


Python to Javascript JSON objects (Flask)


I am trying to create a simple Flask app where an array of integers is generated on the server and sent to the client. I want to view the array of integers in the console. Here is some sample (working) code in app.py:

from flask import Flask, render_template, request, url_for

import random, json

app = Flask(__name__)

@app.route('/',  methods=['GET'])
def form():
    json_helper = {}
    json_helper['randoms'] = [random.random() for _ in range(40)]
    json_object = json.dumps(json_helper)
    return render_template('sim0625.html', s_data=json_object)

if __name__ == '__main__':
  app.run(debug=True)

And here is a snippet of the Javascript frontend:

<script>

  var data_xyz = {{ s_data|tojson }};

  var JSONObject = JSON.parse({{data_xyz}});
  console.log(JSONObject.randoms);  

 </script>

Unfortunately, none of the javascript works on my webpage, and the error message shown is "Uncaught SyntaxError: Unexpected token u".

Can someone please explain what's wrong? Thanks. My guess is the JSON objects are becoming strings.

Note: The code from the front-end was adapted from this SO question: Extracting data from json object in jQuery or JS


Count occurences of digit 'x' in range (0,n]


So I'm trying to write a python function that takes in two arguments, n and num, and counts the occurrences of 'n' between 0 and num. For example,

countOccurrences(15,5) should be 2.

countOccurrences(100,5) should be 20.

I made a simple iterative solution to this problem:

def countOccurrences(num,n):
  count=0
  for x in range(0,num+1):
    count += countHelper(str(x),n)
  return count

def countHelper(number,n):
  count=0
  for digit in number:
    if digit==n:
      count += 1
  return count

This ran into obvious problems if I tried to call countOccurrences(100000000000,5). What my question is is how can I make this more efficient? I want to be able to handle the problem "fairly" fast, and avoid out of memory errors. Here is my first pass at a recursive solution trying to do this:

def countOccurence(num, n):
  if num[0]==n:
    return 1
  else:
    if len(num) > 1:
      return countOccurence(num[1:],n) + countOccurence(str((int(num)-1)),n)
    else:
      return 0


Compute "less-than count" on df column using pandas


My raw data is as follows:

id_2    column_A
602     1
602     1
602     1
602     1
602     3
602     8
602     15
602
602

My dataframe:

df = pd.read_csv('xxyy.csv')    
df = df.fillna(np.nan)

My requirement is: I have to find the less than count for each value for ex:(for 1 its 0, for 3 its 4,etc)

EDIT:

def func1(value):                   
    return df['column_A'][df['column_A'] < value].count()

for name, df in df.groupby(['id_2']):
    for j in df.index:
       y = func1(df['column_A'].ix[j])   
       print y

what i am getting is:

for 3 its 5, for 8 its 6, for 15 its 4, what should i want is: for 3 it should be 6, for 8 it should be 7, for 15 it should be 8 (included 2 nan)


Django, initial checked input


How can I pre-check a CheckboxInput of a form?

I tried this in __init__:

self.fields['name_field'].widget.attrs['checked'] = 'checked'

But it doesn't work..

My field is a boolean field in model and in my form it's a checkbox input.


How do I make a sine graph in Python that has adjustable values for A B C and D in the equation y=Asin(B*(X-C)+D? Beginner programmer :v


import matplotlib.pyplot as plt
import numpy as np


A = 2 
B = 2 
C = 3
D = 4
sample = 16
x = np.arange(sample)
y = (A*np.sin(B*(x-C))+D) 
plt.plot(x, y)
plt.xlabel('voltage(V)')
plt.ylabel('sample(n)')
plt.show()

the y= part is the equation the A B C D values are on top. whenever I try to graph this it comes out wrong


JIRA not recognizing dictionary object in cURL call


This is the error I am currently getting while using the jira-python python module to automate some logging to JIRA.

Traceback (most recent call last):
  File "/home/csd-user/test/libs/utils/butler.py", line 217, in <module>
    main()
  File "/home/csd-user/test/libs/utils/butler.py", line 214, in main
    b.log_bug_exec(url)
  File "/home/csd-user/test/libs/utils/butler.py", line 47, in log_bug_exec
    cls.process_file(stdout)
  File "/home/csd-user/test/libs/utils/butler.py", line 108, in process_file
    cls.submit_bug(bug)
  File "/home/csd-user/test/libs/utils/butler.py", line 207, in submit_bug
    iss = cls.my_server.create_issue(fields=bug.json_dict['fields'])
  File "/opt/clearsky/lib/python2.7/site-packages/jira/client.py", line 706, in create_issue
    r = self._session.post(url, data=json.dumps(data))
  File "/opt/clearsky/lib/python2.7/site-packages/jira/resilientsession.py", line 81, in post
    return self.__verb('POST', url, **kwargs)
  File "/opt/clearsky/lib/python2.7/site-packages/jira/resilientsession.py", line 74, in __verb
    raise_on_error(r, verb=verb, **kwargs)
  File "/opt/clearsky/lib/python2.7/site-packages/jira/utils.py", line 120, in raise_on_error
    r.status_code, error, r.url, request=request, response=r, **kwargs)
# This is the important part...
jira.utils.JIRAError: JiraError HTTP 400
    text: data was not an object
    url: http://ift.tt/1U0OIYc

My problem is that, as far as I can see, the dict object that I am passing it is perfectly valid.

    BUG FIELDS :: {'environment': 'node => 62-qa-driver12 (M3 - HA Only)\nversion => \nurl => http://ift.tt/1GI5xgu => 2015-06-29_11-11-15\njob name => BugLoggerTest\nbuild number => 144\nversion number => Not present. Check git hash. Maybe add in processing of full failure list!\n', 'description': '', 'summary': 'Fill in Something', 'project': {'key': 'QABL'}, 'assignee': 'qa-auto', 'issuetype': {'name': 'Bug'}, 'priority': {'name': 'Major'}}


CLASS :: <type 'dict'>

Is formatted by this...

# creating JSON object (bug should not have to be changed after initialization)
        self.json_dict = ( {"fields": {
            "project": {'key': self.project},
            "issuetype": {'name': self.issue_type},
            "priority": {'name': self.priority},
            "assignee": self.assignee,
            "environment": self.environment,
            "description": self.description,
            "summary": self.summary } } )

This is the call to create the issue where the error is being thrown...

iss = cls.my_server.create_issue(fields=bug.json_dict['fields'])
# This calls a cURL POST or PUT command.

I'd love some help trying to figure this out. Been banging my head against a wall all day so far. Thanks!


Conditional passing of arguments to methods in python


I have many possible arguments from argparse that I want to pass to a function. If the variable hasn't been set, I want the method to use its default variable. However, handling which arguments have been set and which haven't is tedious:

import argparse
def my_func(a = 1, b = 2):
  return a+b

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Get the numeric values.')
    parser.add_argument('-a', type=int)
    parser.add_argument('-b', type=int)
    args = parser.parse_args()

    if not args.a is None and not args.b is None:
        result = my_func(a = args.a, b = args.b)
    elif not args.a is None and args.b is None:
        result = my_func(a = args.a)
    elif not args.b is None and args.a is None:
        result = my_func(b = args.b)
    else:
        result = my_func()

It seems like I should be able to do something like this:

result = my_func(a = args.a if not args.a is None, b = args.b if not args.b is None)

But this gives a syntax error on the comma.

I could set default values in the argparser, but I want to use the defaults set in the method definition.


Django - Query to retrieve pk from other model


I am trying to create a query to grab the pk of the current post from the database. Then set it as the foreign key of the new post. I am using formview, and the model I am trying to retrieve the 'id' from is called Projects. Id is the primary key of the model Projects.

How would I be able to go about this?

pk=5 because I didn't know how to get the current one.

views.py

class ProjectDetailToDoForm(FormView):
    model = ProjectsToDo
    form_class = ProjectToDoForm
    success_url = '../..'

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(ProjectDetailToDoForm, self).dispatch(request, *args, **kwargs)

    def form_valid(self,form):
        self.object = form.save(commit=False)
        self.object.project = Projects.objects.get(pk=5)
        self.object.save()

        return super(ProjectDetailToDoForm, self).form_valid(form)

class ProjectDetail(generic.DetailView):
    model = Projects
    context_object_name = 'indprojects'
    template_name = 'projectpage.html'

    def get_context_data(self, *args, **kwargs):
        context = super(ProjectDetail, self).get_context_data(*args, **kwargs)
        context['todolist'] = ProjectsToDo.objects.order_by('project_tododate')
        context['todoform'] = ProjectToDoForm()
        context['form'] = ProjectForm(instance=Projects.objects.get(slug=self.kwargs['slug']))
        return context

    def get_queryset(self):
        return Projects.objects.filter(user=self.request.user)

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(ProjectDetail, self).dispatch(request, *args, **kwargs)

models.py

class Projects(models.Model):
    user = models.ForeignKey(User)
    slug = models.SlugField()
    project_title = models.CharField(max_length=30)
    project_shortdesc = models.CharField(max_length=248)
    project_desc = models.TextField()

    def save(self):
        super(Projects, self).save()
        date = datetime.date.today()
        self.slug = '%i%i%i%s' % (
            date.year, date.month, date.day, slugify(self.project_title)
        )
        super(Projects, self).save()


class ProjectsToDo(models.Model):
    project_tododate = models.DateField()
    project_tododesc = models.TextField(max_length = 500)
    project = models.ForeignKey(Projects)

    def __unicode__(self):
            return '%s %s' % (self.project_tododesc, self.project_tododate)


Custom get_queryset with LIMIT for django admin panel


I would to have a custom query to show a List of element in my admin django panel.

So, to have this I use a code like this:

class MyAdmin(admin.ModelAdmin):
....
   def get_queryset(self, request):
        return Post.objects.filter(author_type=AuthorType.USER)

This work well but I need also to add a LIMIT for this queryset:

class MyAdmin(admin.ModelAdmin):
....
   def get_queryset(self, request):
        return Post.objects.filter(author_type=AuthorType.USER)[:500]

But when I add the limit clause [:500] I have this error:

Exception Value: Cannot reorder a query once a slice has been taken.

any suggestions?


How can I make a View Item readonly AND scrollable in Enthought Traitsui?


I am using the views in Enthought Traitsui. Within a view, I am using Item('strings', enabled_when='len(x)>20'), where 'strings' is a list of strings and len(x)>20 is never true. If there are more than three strings in the list, I cannot see them all. I would like to be able to scroll through all the strings but at the same time not be allowed to edit the strings. Does anybody know if I can have a readonly AND scrollable item, and if not what are the alternatives? Thank you.


Django form not visible


Only the button is visible and headings are visible cannot see CharField

forms.py

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from compare.forms import NameForm

def get_name(request):
   if request.method == 'POST':
      form = NameForm(request.POST)
   if form.is_valid():
      return HttpResponseRedirect('/thanks/')

   else:
      form = NameForm()

   return render(request, 'name.html', {'form': form})

index.htm

    <form action="/your-name/" method="post">
        {% csrf_token %}
        {{ form }}
    <input type="submit" value="Submit" />
    </form>


Django Form context data lost on validation fail


My form (code below) loads and saves fine. However, if there is a validation error in the form and it is reloaded, the context['uploaded_files'] which I assign in the get_context_data method is empty. Why is that and how can I once again pass the context['uploaded_files'] it when the form is reloaded on validation fail?

class BusinessEditView(UpdateView):
    template_name = 'directory/business_edit.html'
    model = Appuser
    form_class = BusinessEditForm

    def get_context_data(self, **kwargs):
        context = super(BusinessEditView, self).get_context_data(**kwargs)
        user_object = context['appuser']
        files = [user_object.logo]
        context['uploaded_files'] = files
        return context

    def get_object(self, queryset=None):
        return self.request.user

    def post(self, request, *args, **kwargs):
        form = BusinessEditForm(request.POST, instance=self.request.user)
        if form.is_valid():
            form.save(commit=False)
            return HttpResponseRedirect('/profile/')
        else:
            return render_to_response('directory/business_edit.html', {'form': form}, context_instance=RequestContext(request))

As per @Alasdair's suggestion, I amended the else clause as follows:

context = self.get_context_data()
return render_to_response('directory/business_edit.html', context, context_instance=RequestContext(request))

It however, caused an exception as follows:

Traceback:
File "/Users/h/.virtualenvs/pony/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/h/.virtualenvs/pony/lib/python2.7/site-packages/django/views/generic/base.py" in view
  69.             return self.dispatch(request, *args, **kwargs)
File "/Users/h/.virtualenvs/pony/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
  87.         return handler(request, *args, **kwargs)
File "/Users/h/Development/Pony/pony/directory/views.py" in post
  296.             context = self.get_context_data()
File "/Users/h/Development/Pony/pony/directory/views.py" in get_context_data
  272.         context = super(BusinessEditView, self).get_context_data(**kwargs)
File "/Users/h/.virtualenvs/pony/lib/python2.7/site-packages/django/views/generic/detail.py" in get_context_data
  100.         if self.object:

Exception Type: AttributeError at /profile/business/edit/
Exception Value: 'BusinessEditView' object has no attribute 'object'


Make tkinter window taskbar


I'm making a music player GUI and I can't make it appear on the taskbar or in Alt-Tab. I have set overrideredirect() to true to remove the borders and the title. I also made it so that when the user does a 'mouse click and drag' action the window moves. Here's the code:

import tkinter
import sys
import os


class Win(tkinter.Tk):
    global imgfile
    imgfile = r"play.png"

    def __init__(self, master=None):
        def close():
            self.destroy()
            sys.exit()

        def dirchosen():
            global songlist
            songlist = []
            try:
                os.chdir(dirinput.get())
            except:
                print("Invalid Directory")
                raise
            for file in os.listdir(dirinput.get()):
                songlist.append(file)

        tkinter.Tk.__init__(self, master)
        self.overrideredirect(True)
        self._offsetx = 0
        self._offsety = 0

        self.bind('<Button-1>', self.clickwin)
        self.bind('<B1-Motion>', self.dragwin)

        self.geometry("350x200")
        self.config(bg="#FF4766")

        titlelabel = tkinter.Label(self, text="FoxSGR Media Player", bg="#FF4766", font=("Segoe UI", 12))
        titlelabel.pack(ipady=4)

        chdirbutton = tkinter.Button(self, relief="groo", activebackground="#FF8080", command=dirchosen)
        chdirbutton.config(text="Choose Directory", bg="#FF4766", font=("Segoe UI", 8))
        chdirbutton.pack()
        chdirbutton.place(relx=0.66, rely=0.22)

        dirinput = tkinter.Entry(self, font=("Segoe UI", 8), width="34")
        dirinput.pack()
        dirinput.place(relx=0.05, rely=0.23)

        xbutton = tkinter.Button(self, text="x", height="1", command=close)
        xbutton.config(bg="red", activebackground="#FF8080", relief="groo", font=("Segoe UI", 8))
        xbutton.pack()
        xbutton.place(relx=0.90, rely=0.05)

    def dragwin(self, event):
        x = self.winfo_pointerx() - self._offsetx
        y = self.winfo_pointery() - self._offsety
        self.geometry('+{x}+{y}'.format(x=x, y=y))

    def clickwin(self, event):
        self._offsetx = event.x
        self._offsety = event.y

win = Win()

# Had to set the images appart from up there

imgplay = tkinter.PhotoImage(file=imgfile)
playbutton = tkinter.Button(win, image=imgplay, bg="#FF4766", relief="flat")
playbutton.pack()
playbutton.place(rely=0.45, relx=0.4)

imgnext = tkinter.PhotoImage(file="next.png")
nextbutton = tkinter.Button(win, image=imgnext, bg="#FF4766", relief="flat")
nextbutton.pack()
nextbutton.place(rely=0.45, relx=0.57)

imgprev = tkinter.PhotoImage(file="previous.png")
prevbutton = tkinter.Button(win, image=imgprev, bg="#FF4766", relief="flat")
prevbutton.pack()
prevbutton.place(rely=0.45, relx=0.30)

win.mainloop()

Is there any way that I can make it at least appear in Alt-Tab?


Finding intersect values using Python matplotlib-venn


I've been using matplotlib-venn to generate a venn diagram of 3 sets. Shown below.

I wanted to ask how can find the values of the intersects of these sets. For example, what are the 384 values that intersect set A and set B? What are the 144 values that intersect set A, set B, and set C? and so worth.

Thank you.

Rodrigo

Matplotlib-venn diagram


Extract Information From a File


I have some 40,000 lines of information in a file that I would like to extract the IP addresses of a certain system using Python 3.4. The file is broken into each block starting with "lease" and ends with "}". I would like to search for the "SYSTEM123456789" and extract the IP address "10.0.0.2". How do I go about doing that and what is the preferred approach?

1) Read in the file, break them up in the list, and then search?
2) Copy the file and then search within that file?

lease 10.0.0.1 {
  starts 1 2015/06/29 07:22:01;
  ends 2 2015/06/30 07:22:01;
  tstp 2 2015/06/30 07:22:01;
  cltt 1 2015/06/29 07:22:01;
  binding state active; 
  next binding state free;
  hardware ethernet 08:2e:5f:f0:8b:a1;
}
lease 10.0.0.2{
  starts 1 2015/06/29 07:31:20;
  ends 2 2015/06/30 07:31:20;
  tstp 2 2015/06/30 07:31:20;
  cltt 1 2015/06/29 07:31:20;
  binding state active; 
  next binding state free;
  hardware ethernet ec:b1:d7:87:6f:7a;
  uid "\001\354\261\327\207oz";
  client-hostname "SYSTEM123456789";
}


Finding the length of longest repeating?


I have tried plenty of different methods to achieve this, and I don't know what I'm doing wrong.

reps=[]
len_charac=0
def longest_charac(strng)
    for i in range(len(strng)):
        if strng[i] == strng[i+1]:
            if strng[i] in reps:
                reps.append(strng[i])
                len_charac=len(reps)
    return len_charac


Re-open a file in binary mode with Python


Say I have a file object which was opened in mode 'r' (such as from the default open() call), but I need to read it in binary mode ('rb').

Is there a way to change the mode directly, or do I need to make a new file object using something like open(foo.name, 'rb') (assuming my file object is named foo)?

EDIT: Ideally, the solution to this problem should be platform-independent.


Python Decorator recreating Locals()


Some of my functions use a "fail_silently" flag. It is used in the following way:

def test(a, b, c=1, fail_silently = False)
    try:
        return int(a) + c
    except:
       if fail_silently:
           return None
       raise

Therefore, if there is an error, we catch it and fail gracefully. The key here is that it can be toggled dynamically by whoever is calling it.

I am using this for a many different functions and class methods and thought to make it a decorator.

There are a few problems:

  1. I want to be able name the flag "raise_exception" or "fail_silently" or "whatever"...
  2. The flag may or may not have a default value
  3. The flag may or may not be passed in (usually not)
  4. It needs to work with class methods too

Thus my decorator needs to look for (assuming the flag is called "fail_silently") the flag in the following locations in this order

  1. **kwargs (the passed in function arguments), simple dictionary get on flag
  2. *args - get the positional argument of the flag, then scan for index in args (which might not be there)
  3. Get the default value of the flag from the function

The problem is the code is now getting really messy and has many points of failure.

def try_except_response(parameter = 'fail_silently'):
    def real_decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs) # the function itself, 
            except: # if it raises an Exception!
                # check to see if the Flag is in passed in kwargs!
                if kwargs.get(parameter)== True: 
                    return None
                elif kwargs.get(parameter) == False:
                    raise
                else:
                    # Flag is not in kwargs, check to see if it is in args
                    function_args, vargs, kewords, defaults = inspect.getargspec(func) # get the index of argument of interest
                    try:
                        argument_index = function_args.index(parameter)  # get the index of argument of interest
                    except ValueError:
                        raise ValueError('The inputted decorator for "fail_silently" was not found!  The behavior will not work.')

                    if len(args) > argument_index: # check to see if it is inputted

                        keyword = args[argument_index] # get the value!!
                        if keyword == True: 
                            return None
                        elif kwargs == False:
                            raise
                        else:
                            raise ValueError('The "fail_silently" flag did not return a value that we understand.  Must be True or False')

                    else:
                        # not in args either! let's go get the default value.
                        # TODO MORE STUFF!!!
                        raise
                    raise
                raise
        return wrapper

What is the best way this can be cleaned up? Or alternatives? I am thinking about implementing a version of locals() that will create a dictionary of all parameters passed into the function and then check from there...


My for-Loop isn't working as intended


I want to fill in the list_of_occurences with the correct item from the list grundformen.

My for-loop doesn't work as intended though. It doesn't restart from the beginning and only goes through the rows in the reader once. Therefore it won't fill the list completely.

This is what it prints (you can see the part where something is missing - because it doesn't start searching from the beginning of the list - ):

# List_of_occurrences (1 line - wrapped for easier reading)
[['NN', 1328, ('Ziel',)], ['ART', 771, ('der',)], 
 ['$.', 732, ('_',)], ['VVFIN', 682, ('schlagen',)], 
 ['PPER', 592, ('sie',)], ['$,', 561, ('_',)], 
 ['ADV', 525, ('So',)], ['APPR', 507, ('in',)], 
 ['NE', 433, ('Johanna',)], ['$(', 363, ('_',)], 
 ['VAFIN', 334, ('haben',)], ['ADJA', 307, ('tragisch',)], 
 ['ADJD', 278, ('recht',)], ['KON', 228, ('Doch',)], 
 ['VVPP', 194, ('reichen',)], ['VVINF', 161, ('stören',)], 
 ['KOUS', 151, ('Während',)], ['PPOSAT', 120, ('ihr',)], 
 ['PTKVZ', 104, ('weiter',)], ['PRF', 98, ('sich',)], 
 ['APPRART', 90, ('zu',)], ['PTKNEG', 87, ('nicht',)], 
 ['VMFIN', 76, ('sollen',)], ['PIAT', 66, ('kein',)], 
 ['PIS', 65, ('etwas',)], ['PTKZU', 52, ('zu',)], 
 ['PRELS', 51, ('wer',)], ['PROAV', 42, ('dabei',)],  
 ['PDS', 38, ('jener',)], ['PDAT', 37, ('dieser',)], 
 ['PWAV', 30, ('wie',)], ['PWS', 26, ('Was',)], 
 ['CARD', 24, ('drei',)], ['KOKOM', 21, ('wie',)], 
 ['VAINF', 18, ('werden',)], ['KOUI', 15, ('um',)], 
 ['VMINF', 10, ('können',)], ['VVIZU', 10, ('aufklären',)], 
 ['VAPP', 10], ['PTKA', 6], ['PTKANT', 6], ['PWAT', 4], 
 ['VVIMP', 4], ['PRELAT', 4], ['APZR', 3], ['APPO', 2], 
 ['FM', 1]]

# Grundformen (1 line, wrapped for reading)
['Ziel', 'der', '_', 'schlagen', 'sie', '_', 'So', 'in', 'Johanna',
 '_', 'haben', 'tragisch', 'recht', 'Doch', 'reichen', 'stören', 
 'Während', 'ihr', 'weiter', 'sich', 'zu', 'nicht', 'sollen', 'kein', 
 'etwas', 'zu', 'wer', 'dabei', 'jener', 'dieser', 'wie', 'Was', 
 'drei', 'wie', 'werden', 'um', 'können', 'aufklären']  


occurences = collections.Counter()

with open("material-2.csv", mode='r', newline='', encoding="utf-8") as material:
    reader = csv.reader(material, delimiter='\t', quotechar="\t")
    for line in reader:
        if line:
            occurences[line[5]] += 1
        else:
            pass

list_of_occurences = [list(elem) for elem in occurences.most_common()]

grundformen = []
with open('material-2.csv', mode='r', newline='', encoding="utf-8") as material:
    reader = csv.reader(material, delimiter='\t', quotechar="\t")
    for elem in list_of_occurences:
        for row in reader:
            if row != [] and row[5] == elem[0]:
                grundformen.append(row[2])
                break

iterator = 0
for elem in grundformen:
    list_of_occurences[iterator].insert(2, elem)
    iterator = iterator + 1
    pass

print(list_of_occurences)
print(grundformen)


whole inputfile: http://ift.tt/1CF67ed

Part of my input file:

1 Als Als _ _ KOUS _ _ 6 6 CP CP _ _ 2 es es _ _ PPER _ 3|Nom|Sg|Neut 6 6 SB SB _ _ 3 zu zu _ _ PTKA _ _ 4 4 MO MO _ _ 4 schneien schneien _ _ ADJD _ Comp|Dat|Sg|Fem 5 5 MO MO _ _ 5 aufgehört aufhören _ _ VVPP _ Psp 6 6 OC OC _ _ 6 hatte haben _ _ VAFIN _ 3|Sg|Past|Ind 8 8 MO MO _ _ 7 , _ _ _ $, _ _ 8 8 PUNC PUNC _ _ 8 verließ verlassen _ _ VVFIN _ 3|Sg|Past|Ind 0 0 ROOT ROOT _ _ 9 Johanna Johanna _ _ NE _ Nom|Sg|Masc 8 8 SB SB _ _ 10 von von _ _ APPR _ _ 5 5 SBP SBP _ _ 11 Rotenhoff Rotenhoff _ _ NE _ Dat|Sg|Neut 10 10 NK NK _ _ 12 , _ _ _ $, _ _ 8 8 PUNC PUNC _ _ 13 ohne ohne _ _ KOUI _ _ 18 18 CP CP _ _ 14 ein ein _ _ ART _ Nom|Sg|Neut 16 16 NK NK _ _ 15 rechtes recht _ _ ADJA _ Pos|Nom|Sg|Neut 16 16 NK NK _ _ 16 Ziel Ziel _ _ NN _ Nom|Sg|Neut 18 18 OA OA _ _ 17 zu zu _ _ PTKZU _ _ 18 18 PM PM _ _ 18 haben haben _ _ VAINF _ Inf 8 8 MO MO _ _ 19 , _ _ _ $, _ _ 18 18 PUNC PUNC _ _ 20 das der _ _ ART _ Nom|Sg|Neut 21 21 NK NK _ _ 21 Gutshaus Gutshaus _ _ NN _ Nom|Sg|Neut 16 16 APP APP _ _ 22 . _ _ _ $. _ _ 8 8 PUNC PUNC _ _

how can I change my loop, so that it can fill in everything?