samedi 27 juin 2015

calling a function on dataframe data

I am not sure what I am doing wrong here, I am simply trying to call a function with a if-then-else filter in it and apply to a dataframe.

In [7]:
df.dtypes

Out[7]:
Filler     float64
Spot       float64
Strike     float64
cp          object
mid        float64
vol        float64
usedvol    float64
dtype: object

In [8]:
df.head()

Out[8]:
          Filler  Spot  Strike cp  mid   vol  
    0       0.0   100      50  c   0.0   25.0   
    1       0.0   100      50  p   0.0   25.0   
    2       1.0   100      55  c   1.0   24.5  
    3       1.0   100      55  p   1.0   24.5   
    4       2.5   100      60  c   2.5   24.0 

I have the below function:

def badvert(df):
    if df['vol']>24.5:
        df['vol2'] = df['vol']*2
    else:
        df['vol2'] = df['vol']/2
    return(df['vol2'])

Which I call here:

df['vol2']=badvert(df)

Which generates this error message:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-bbf7a11a17c9> in <module>()
----> 1 df['vol2']=badvert(df)

<ipython-input-13-6132a4be33ca> in badvert(df)
      1 def badvert(df):
----> 2     if df['vol']>24.5:
      3         df['vol2'] = df['vol']*2
      4     else:
      5         df['vol2'] = df['vol']/2

C:\Users\camcompco\AppData\Roaming\Python\Python34\site-packages\pandas\core\generic.py in __nonzero__(self)
    712         raise ValueError("The truth value of a {0} is ambiguous. "
    713                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
--> 714                          .format(self.__class__.__name__))
    715 
    716     __bool__ = __nonzero__

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

My gut tells me that this is a simple "syntax" issue but I am at a loss. Any help would be greatly appreciated

In Django REST / OAuth2 toolkit what is the difference between TokenHasScope and TokenHasReadWriteScope?

In Django REST / OAuth2 toolkit what is the difference between TokenHasScope and TokenHasReadWriteScope?

For example in views.py:

from rest_framework import generics
from django.contrib.auth.models import User
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope, TokenHasScope
from oauth2.provider.views.mixins import ScopedResourceMixin

class UserView1(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    model = User

class UserView2(ScopedResourceMixin, viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasScope]
    required_scopes = ['what_is_this']
    model = User

What is the significance of the required_scopes value?

Reference: http://ift.tt/1Ho4RU3

MS WindowsServer 2012: Python request - SSL: UNKNOWN_PROTOCOL] unknown protocol

on MS Windows Server 2012, the Python script is doing https request into open github repository, see full log at

http://ift.tt/1CB2ztm

The problem is (Python 2.7.10) with Windows Server 2012 connection to https sites of github, which are open for public. On all other Windows servers (including CI testing on appveyor.com) this connection works.

Maybe this is issue related to Windows Server 2012. Any help please how to modify this line ?

update.fetch_url('http://ift.tt/1Ho4RDL', 'update.py')

tkinter child program not closed

I have 2 tkinter programs. The main program will have button to open the second program. The problem is when i try to close the child program, the main program is closed instead. I close the second program with command app.destroy(). How to fix this?
Thanks in advance.

All of the programs have this script

from Tkinter import *
import Tkinter as tk
import os

class SeaofBTCapp(tk.Tk):

    def __init__(self,*args,**kwargs):

        tk.Tk.__init__(self)
        container = tk.Frame(self, background="black")
        container.pack(side="top", fill="both", expand = True)

        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)



        self.frames = {}

        for F in (StartPage, PageCheck, PageUpdate, PageDigital, PageAnalog,
                  PageResult, PageHasil):

            frame = F(container, self)

            self.frames[F] = frame

            ##self.overrideredirect(1)

            self.geometry("800x480")
            self.title("IC Checker")
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()

##frame class

app = SeaofBTCapp()
app.mainloop()

(Python) Vehicle number plates verification and file saving

My aim is to create code that can verify inputted number plates and verify them to the format: AA/11/AAA 2 letter, 2 numbers, 3 letters. If the entered plate is incorrect, it is saved to a file called 'invalidplates' which shows an array of all of the number plates that exceed the desired speed limit.

Here are the questions

a) On many major roads average speed checks are in place. Two sensors are placed a known distance apart and vehicle number plate recognition is used to identify a vehicle and the time it enters the section of road being monitored. The time is recorded when the vehicle leaves the monitored section. By using the time taken to travel the known distance, the average speed of a vehicle can be calculated. Create a program for calculating average speeds for a vehicle travelling through a section of road. Output a list of those vehicles exceeding the speed limit set for that section of road.

b)In the UK most vehicle registrations are in the format: • two letters • two numbers • three letters. For example, AZ01 XYZ. The vehicle number plate recognition system will provide this information as a string of characters. By identifying any vehicle registrations that do not match this pattern, a list of non-standard vehicle registrations and average speeds in excess of the speed limit should be compiled and saved. Create a program for saving a file with these non-standard registrations for those vehicles exceeding the speed limit set for that section of road.

c) The authorities have a file of known vehicle registrations and the vehicle’s owner. Those vehicles with standard registrations can be looked up in this file and a fine automatically sent out. A new file is created by comparing the information from the average speed recording system with the file of registered vehicles and their owners’ details. This new file should include the owner’s name and address details, the registration of the vehicle and the average speed of the vehicle in the section of road. Create a program for creating a file of details for vehicles exceeding the speed limit set for a section of road. You will need to create a suitable file with test data, including standard registrations and vehicle owner information.

Here is my code:

file = open("Speeders.txt", "w")
import random, string, time
Speeders = [] #Array

while True:
    try:
        Distance = float(input("Enter a known distance.(Metres ONLY)"))
        break
    except ValueError: #Allows ONLY numbers to be inputted, anything else is rejected
        print ("Invalid input (Numbers ONLY)")

while True:
    try:
        TimeTaken = float(input("Enter the time taken to pass the distance"))
        break
    except ValueError:#Allows ONLY numbers to be inputted, anything else is rejected
        print ("Invalid input (Numbers ONLY)")

while True:
    try:
        Limit = int(input("Enter the speed limit in metres per second"))
        break
    except ValueError:#Allows ONLY numbers to be inputted, anything else is rejected
        print ("Invalid input (Numbers ONLY)")

Speed = (Distance) / (TimeTaken)
print (("The speed of the vehicle was " + str(Speed) + " metres per second"))
while True:
    try:
        if (Speed) > (Limit):
            def NumPlate(self):
                plateFormat = ['L', 'L', 'N', 'N', 'L', 'L', 'L']
                NumPlate = []

                for i in plateFormat:
                    if i == 'L':
                        NumPlate.append(random.choice(string.ascii_letters[26:]))

                    elif i == 'N':
                        NumPlate.append(str(random.randint(0, 9)))
                        NumPlate.insert(4, " ")
                        NumPlate = str(input("Enter the vehicle's number plate."))
                        Speeders.append (NumPlate)
                        return  "".join(NumPlate)
                    break




        while True:
            reply = input('Enter Y to add another number plate N to print list: ')

            if reply == "Y":
                while True:
                    try:
                        Distance = float(input("Enter a known distance.(Metres ONLY)"))
                        break
                    except ValueError: #Allows ONLY numbers to be inputted, anything else is rejected
                        print ("Invalid input (Numbers ONLY)")

                while True:
                    try:
                        TimeTaken = float(input("Enter the time taken to pass the distance"))
                        break
                    except ValueError:#Allows ONLY numbers to be inputted, anything else is rejected
                        print ("Invalid input (Numbers ONLY)")

                while True:
                    try:
                        Limit = int(input("Enter the speed limit in metres per second"))
                        break
                    except ValueError:#Allows ONLY numbers to be inputted, anything else is rejected
                        print ("Invalid input (Numbers ONLY)")

                Speed = (Distance) / (TimeTaken)
                print (("The speed of the vehicle was " + str(Speed) + " metres per second"))

                if (Speed) > (Limit):
                        NumPlate = str(input("Enter the vehicle's number plate."))
                        Speeders.append (NumPlate)

                        while True:
                            reply = input('Enter Y to add another number plate N to print list: ')

                file.write("Here is a list of the Speeders' number plates on the roads\n")
                file.write("List" + str(Speeders))

            if reply == "N":
                for i in Speeders:
                    print("This is the list of current number plates that are speeding: " + str(Speeders))

Any help to improve/fix my code will be greatly appreciated :)

Who prepares input for R tasks

I am new to R.

Suppose to have some data that we have to parse for maybe building a representation in vectorial space of several items that will have to be clustered; it involves some text processing and manipulation. Other goals of the parsing might be to output a .csv, or a tab separated file. When doing this in Python, I would often use data structures such as dictionaries, sets, hash-maps.. such data structures seems not to be available on R.

I would like to know, do R users usually prepare/build their input data (that will be printed as a .csv or a tab separated file as above pointed out) with R itself, or do they usually rely on other programming languages more powerful for doing it, like Python?

At first glance, it seems to me that R is quite assuming that suitable input data are already available in right format, and we are not going to use R also for parsing some source to build a more structured input.

Need help on programming . Beginner Python

Sound level L in units of decibel (dB) is determined by L = 20 log10(p/p0) where p is the sound pressure of the sound (in Pascals, abbreviated Pa), and p0 is a reference sound pressure equal to 20 × 10–6 Pa (where L is 0 dB).

The following table gives descriptions for certain sound levels. Threshold of pain 130 dB Possible hearing damage 120 dB Jack hammer at 1 m 100 dB Traffic on a busy roadway at 10 m 90 dB Normal conversation 60 dB Calm library 30 dB Light leaf rustling 0 dB Write a program that reads a value and a unit, either dB or Pa, and then prints the closest description from the list above.

L=input('What can you hear outside')
L=L.upper()
if L == "JACKHAMMER":
   print(L)
from math import *
Pa=2
Pa=(Pa)
p0=(20*10)**(-6)(2)
p0=round(p0)
LdB = 20(log(Pa/p0)) 

so far i have this but there is an error